Example #1
0
void AudioSoundIo::startProcessing()
{
	m_outBufFrameIndex = 0;
	m_outBufFramesTotal = 0;
	m_outBufSize = mixer()->framesPerPeriod();

	m_outBuf = new surroundSampleFrame[m_outBufSize];

	int err;
	if ((err = soundio_outstream_start(m_outstream)))
	{
		fprintf(stderr, "soundio unable to start stream: %s\n", soundio_strerror(err));
	}
}
Example #2
0
void AudioSoundIo::writeCallback(int frameCountMin, int frameCountMax)
{
	const struct SoundIoChannelLayout *layout = &m_outstream->layout;
	SoundIoChannelArea *areas;
	int bytesPerSample = m_outstream->bytes_per_sample;
	int err;

	const float gain = mixer()->masterGain();

	int framesLeft = frameCountMax;

	while (framesLeft > 0)
	{
		int frameCount = framesLeft;
		if ((err = soundio_outstream_begin_write(m_outstream, &areas, &frameCount)))
		{
			errorCallback(err);
			return;
		}

		if (!frameCount)
			break;

		for (int frame = 0; frame < frameCount; frame += 1)
		{
			if (m_outBufFrameIndex >= m_outBufFramesTotal)
			{
				m_outBufFramesTotal = getNextBuffer(m_outBuf);
				m_outBufFrameIndex = 0;
			}

			for (int channel = 0; channel < layout->channel_count; channel += 1)
			{
				float sample = gain * m_outBuf[m_outBufFrameIndex][channel];
				memcpy(areas[channel].ptr, &sample, bytesPerSample);
				areas[channel].ptr += areas[channel].step;
			}
			m_outBufFrameIndex += 1;
		}

		if ((err = soundio_outstream_end_write(m_outstream)))
		{
			errorCallback(err);
			return;
		}

		framesLeft -= frameCount;
	}
}
Example #3
0
void game_snd_buffer(uint16_t *stream, int size)
{
	for (int i=0;i<size; i++) {
		if (sample_in_tick++>=Player.samplesPerTick) {
			// check button for next song ...
			if (0){
				loadNextFile();
			} else {
				player();
			}
			sample_in_tick=0;
		}
		stream[i] = mixer(stream); 
	}
} 
Example #4
0
// DISPLAY UPDATE FUNCTION
//-------------------------------------------------------------------------
void Display::update(){
	consoleSelect(&mainConsole);
	iprintf("\e[37m\x1b[1;20H%4d.%1d.%1d", midi->bars, midi->beats, midi->quarters);
	consoleSelect(&subConsole);

	tempoLeds();
	switch (Cfg::mode){
		case KAOSS:
			if (Cfg::previousMode != KAOSS){
				Cfg::previousMode = KAOSS;
				kaoss();
			}
			if (!input->paused)
				kaossUpdate();
			break;
		case PADS:
			if (Cfg::previousMode != PADS){
				Cfg::previousMode = PADS;
				pads();
			}
			padsUpdate();
			break;
		case MIXER:
			if (Cfg::previousMode != MIXER){
				Cfg::previousMode = MIXER;
				mixer();
			}
			mixerUpdate();
			break;
		case SLIDERS:
			if (Cfg::previousMode != SLIDERS){
				Cfg::previousMode = SLIDERS;
				sliders();
			}
			slidersUpdate();
			break;
	}

	for (u8 c = 0; c < 16; ++c){
		for (u8 v = 0; v < 128; ++v)
			Cfg::ccChangedVblank[c][v] = false;
	}
	oamUpdate(&oamSub);
	oamUpdate(&oamMain);
	++frame;
}
Example #5
0
	void DrumKit_HddTest::RunTest()
	{


		std::string workingDirectory("/home/jeremy/Desktop/Prog/RaspiDrums/Data/");
		std::string kitLocation(workingDirectory + "Kits/default.xml");


		DrumKit::Kit kit;

		DrumKit::Module module(workingDirectory);
		module.LoadKit(kitLocation, kit);


		std::string xmlFileLoc(workingDirectory + "alsaConfig.xml");

		Sound::AlsaParams aParams;
		Sound::Alsa::ReadXmlConfig(aParams, xmlFileLoc);


		Sound::Mixer mixer(module.soundParameters, aParams);
		Sound::Alsa  alsa(aParams, mixer);

		std::string sensorFile(workingDirectory + "../out.raw");

		IO::HddSensor hddSensor(sensorFile);
		DrumKit::Trigger snareTrigger(kit.drum[0], mixer);

		alsa.Start();

		int N = hddSensor.GetDataLength();

		for(int i = 0; i < N; i++)
		{

			short value = hddSensor.GetOutput();
			snareTrigger.Trig(value);

		}

		alsa.Stop();


		return;
	}
Example #6
0
void game_snd_buffer(uint16_t *stream, int size)
{
	for (int i=0;i<size; i++) {

		if (sample_in_tick++==Player.samplesPerTick) {

			// check button for next song ...
			if (!button_state() && prev_but){
				set_led(vga_frame & 64);
				loadNextFile();
			} else {
				player();
			}
			prev_but=button_state();
			sample_in_tick=0;
		}
		stream[i] = mixer(stream); 
	}
} 
Example #7
0
AudioJack::AudioJack( bool & _success_ful, Mixer*  _mixer ) :
	AudioDevice( tLimit<int>( ConfigManager::inst()->value(
					"audiojack", "channels" ).toInt(),
					DEFAULT_CHANNELS, SURROUND_CHANNELS ),
								_mixer ),
	m_client( NULL ),
	m_active( false ),
	m_tempOutBufs( new jack_default_audio_sample_t *[channels()] ),
	m_outBuf( new surroundSampleFrame[mixer()->framesPerPeriod()] ),
	m_framesDoneInCurBuf( 0 ),
	m_framesToDoInCurBuf( 0 )
{
	_success_ful = initJackClient();
	if( _success_ful )
	{
		connect( this, SIGNAL( zombified() ),
				this, SLOT( restartAfterZombified() ),
				Qt::QueuedConnection );
	}

}
Example #8
0
void AudioSdl::sdlAudioCallback( Uint8 * _buf, int _len )
{
	if( m_stopped )
	{
		memset( _buf, 0, _len );
		return;
	}

	while( _len )
	{
		if( m_convertedBufPos == 0 )
		{
			// frames depend on the sample rate
			const fpp_t frames = getNextBuffer( m_outBuf );
			if( !frames )
			{
				m_stopped = true;
				m_stopSemaphore.release();
				memset( _buf, 0, _len );
				return;
			}
			m_convertedBufSize = frames * channels()
						* sizeof( int_sample_t );

			convertToS16( m_outBuf, frames,
						mixer()->masterGain(),
						(int_sample_t *)m_convertedBuf,
						m_convertEndian );
		}
		const int min_len = qMin( _len, m_convertedBufSize
							- m_convertedBufPos );
		memcpy( _buf, m_convertedBuf + m_convertedBufPos, min_len );
		_buf += min_len;
		_len -= min_len;
		m_convertedBufPos += min_len;
		m_convertedBufPos %= m_convertedBufSize;
	}
}
Example #9
0
void VAModel(double *dstatesdt, double *states_out, double *MVs_out, double *measurements, 
            double states[], double MVs[], double time, int is_initial, int disturbance_ID)
{

    //--------------------------------------------------------------------------
    /*output:
        dstatesdt: state derivatives
        states_out: states (generated in initialization)
        MVs_out: (duplicated when no perfect control is selected), (partially calculated when perfect control is selected) or (generated in initialization)
        measurements: total available measurements, which can be easily extended by a user  
    --------------------------------------------------------------------------*/

    //--------------------------------------------------------------------------
    /*input:
        states
        MVs
        time: current running time in minute
        is_initial: 1 for loading initial steady state data, 0 for dynamic simulation
        disturbance_ID: 1 and 2
    --------------------------------------------------------------------------*/
    
    /*---------------------------------constants-------------------------------*/
    //physical properties
    //Data is not the same as Table 1 in Luyben's paper
    double Vi[7] = {64.178, 37.400, 49.347, 52.866, 101.564, 18.01, 61.445};
    double AIJ[7][7]=
    {
        {0., 0., 0., 0., 0., 0., 0.},
        {0., 0., 0., 0., 0., 0., 0.},
        {0., 0., 0., 0., 0., 0., 0.},
        {0., 0., 0., 0., 0., 0., 0.},
        {0., 0., 0., 0., 0., 1384.6, -136.1},
        {0., 0., 0., 0., 2266.4, 0., 670.7},
        {0., 0., 0., 0., 726.7, 230.6, 0.},
    };
    /*Data from Table 2 (Pure component physical properties).*/
    double MW[7] = {32., 44.01, 28.052, 30.068, 86.088, 18.008, 60.052};
    double SpG[7] = {0.5, 1.18, 0.57, 0.57, 0.85, 1.0, 0.98};    /*liquid specific gravity based on the density od water at 0 degC*/
    double HVAP[7] = {2300., 2429., 1260., 1260., 8600., 10684., 5486.};
    double HCAPLa[7] = {0.3, 0.6, 0.6, 0.6, 0.44, 0.99, 0.46};
    double HCAPLb[7] = {0., 0., 0., 0., 0.0011, 0.0002, 0.0012};
    double HCAPVa[7] = {0.218, 0.23, 0.37, 0.37, 0.29, 0.56, 0.52};
    double HCAPVb[7] = {0.0001, 0., 0.0007, 0.0007, 0.0006, -0.0016, 0.0007};
    /*Data from Table 3 (Component vapor pressure antoine coefficients*/
    double A[7] = {9.2, 7.937, 9.497, 9.497, 12.6564, 14.6394, 14.5236};
    double B[7] = {0., 0., -313., -313., -2984.45, -3984.92, -4457.83};
    double C[7] = {273.16, 273.16, 273.16, 273.16, 226.66, 233.43, 258.45};
    /*Others*/
    double R = 1.987;               /*Gas constant, kcal/(kmol*K)*/
    double Dw = 999.;               /*density of water at 0 degC, kg/m3*/
    double T_ref = 273.16;          /*Reference Temperature, K*/
    
    /*---------------------------------constants-------------------------------*/
    //feed stream properties
    /*F_O2 is MV 1*/
    double y_O2[7]={1., 0., 0., 0., 0., 0., 0};
    double T_O2[1]={30.};
    double P_O2[1]={150.};
    /*F_C2H4 is MV 2*/
    double y_C2H4[7]={0., 0., 0.999, 0.001, 0., 0., 0};
    double T_C2H4[1]={30.};
    double P_C2H4[1]={128.};
    /*F_HAc is MV 3*/
    double x_HAc[7]={0., 0., 0., 0., 0., 0., 1.};
    double T_HAc[1]={30.};
    double P_HAc[1]={150.};
    
    /*---------------------------------constants-------------------------------*/
    /*Vaporizer*/
    double Total_Volume_vaporizer[1] = {17.}; /*m3, which is 600/(3.2808)^3 in TMODS, not used in our model*/
    double Working_Volume_vaporizer[1] = {4.}; /*m3, maximum measurable liquid holdup (100% level)*/
    /*-----------------------------------------------------------------------------*/
    /*Reactor*/
    double friction_factor[1]={0.000794745091749963}; /*0.00147*2.20462*(3.2808)^3/144: deltaP=friction_factor*density*volumetric flowrate*volumetric flowrate*/
    int NR[1] = {11}; 
    double tube_L[1] ={10.};
    int tube_number[1] = {622};
    double tube_diameter[1] ={0.0371};
    double tube_area[1] = {0.67240058914293}; /*tube_area=1/4*pi*tube_diameter*tube_diameter*tube_number. total intersection area, m^2*/
    double UA_reactor[1] = {269.839144893182}; /*UA=4000*0.252*9/5/10/tube_area/1;   kcal/min m^3 degC*/
    double cata_bulk_density[1] = {385.};
    double cata_heatcapacity[1] = {0.23};
    double cata_porosity[1] = {0.8};
    double cata_weight[1] = {2588.74226820028}; /*cata_weight=tube_area*tube_L*cata_bulk_density;*/
    double E_r1[1] = {-42100.}; 	/*heat of reaction for r1, kcal/kmol*/
    double E_r2[1] = {-316000.};	/*heat of reaction for r2, kcal/kmol*/
    double sto1[7]={-0.5, 0., -1., 0., 1., 1., -1.};
    double sto2[7]={-3., 2., -1., 0., 0., 2., 0.};
    /*-----------------------------------------------------------------------------*/
    /*FEHE*/
    double UA_FEHE[1]={6483./60.0};     /*kcal/min degC*/
    double Ref_hotflow[1]={589.670};    /*kg/min*/
    double Ref_coolflow[1]={498.952};   /*kg/min*/
    double Ref[1]={0.8};
    /*-----------------------------------------------------------------------------*/
    /*Separator*/
    double Total_Volume_separator[1]={15.};     /*m3, which is 535/3.2808/3.2808/3.2808 in TMODS, not used in our model*/
    double Working_Volume_separator[1]={8.};    /*m3, maximum measurable liquid holdup (100%  level)*/
    double Total_Gas_Loop_Volume[1]={170.};     /*m3, which is 6002/3.2808/3.2808/3.2808 in TMODS*/
    double UA_separator[1]={20007.*0.252*9/5};   /*kcal/min degC*/  
    /*-----------------------------------------------------------------------------*/
    /*Compressor*/
    double Compressor_coefficient[1]={15000.};   /*delta_P=Compressor_coefficient*density/144*/
    /*-----------------------------------------------------------------------------*/
    /*Absorber*/
    int NT_absorber[1]={8};
    int NF_absorber[1]={2};
    double Working_Volume_absorber[1]={8.5};    /*m3, which is 300/3.2808/3.2808/3.2808 in TMODS*/
    double M0_absorber[8]={30/2.20462, 30/2.20462, 30/2.20462, 30/2.20462, 30/2.20462, 30/2.20462, 30/2.20462, 30/2.20462};
    double L0_absorber[8]={16.327, 16.311, 0.911, 0.885, 0.853, 0.844, 0.829, 0.815};
    double hydtau_absorber[1]={0.1};
    double Nmt[8]={60/2.20462, 60/2.20462, 60/2.20462, 60/2.20462, 60/2.20462,60/2.20462, 60/2.20462, 60/2.20462};
    double Qmt[8]={400*0.252, 400*0.252, 200*0.252, 200*0.252, 200*0.252, 200*0.252, 200*0.252, 200*0.252};
    /*-----------------------------------------------------------------------------*/
    /*CO2 Remove*/
    double CO2_F_ref[1]={6.41360260517487};
    double CO2_x_ref[1]={0.0134241598608995};
    /*-----------------------------------------------------------------------------*/
    /*Column*/
    int NT_column[1]={20};
    int NF_column[1]={15};
    double P_top[1]={18.};
    double P_bottom[1]={30.};
    double K_decanter[3]={395., 0.05, 1.}; /*decanter partition coefficients*/
    double hydtau_column[1]={0.1};
    double M0_column[20]; /*Tray holdup (kmol)*/
    double L0_column[20];
    double Bottom_Working_Level_Volume[1]={5.66};/*m3, which is 200/3.2808/3.2808/3.2808 in TMODS*/
    double Organic_Working_Level_Volume[1]={1.7};/*m3, which is 60/3.2808/3.2808/3.2808 in TMODS*/
    double Aqueous_Working_Level_Volume[1]={1.7};/*m3, which is 60/3.2808/3.2808/3.2808 in TMODS*/
    double HAcTank_Working_Level_Volume[1]={2.83};/*m3, which is 100/3.2808/3.2808/3.2808 in TMODS*/
    double T_Column[20]={131, 121, 106, 96, 93, 92, 91, 90, 89, 88, 88, 87, 86, 85, 84, 80, 78, 77, 76, 75};  //initial guess of column temperature profile
    /*---------------------------------constants-------------------------------*/


    /*---------------------------------variables-------------------------------*/
    //vaporizer states
    double x_vaporizer[7], hup_vaporizer[1], T_vaporizer[1];
    /*---------------------------------variables-------------------------------*/
    //reactor states 
    double C_O2[11], C_CO2[11], C_C2H4[11], C_VAc[11], C_H2O[11], C_HAc[11], T_reactor[11];
    /*---------------------------------variables-------------------------------*/
    //separator states 
    double x_separator[7], hup_separator[1], TL_separator[1];
    double y_separator[7], P_separator[1], TV_separator[1];
    /*---------------------------------variables-------------------------------*/
    //absorber states 
    double x_absorber[8][7], M_absorber[8], TL_absorber[8];    double x_base[7], hup_base[1], T_base[1];
    /*---------------------------------variables-------------------------------*/
    //column, decanter and HAc tank states 
    double x_column[20][7], M_column[20], x_bottom[7], hup_bottom[1];
    double x_organic[7], hup_organic[1], x_aqueous[7], hup_aqueous[1];
    double x_HAcTank[7], hup_HAcTank[1], T_HAcTank[1];
    /*---------------------------------variables-------------------------------*/
    //other states 
    double T_VapHeaterOut[1], T_ABSIN_Gas[1], T_Circulation[1], T_Scrub[1], T_decanter[1], T_FEHEColdOut[1], T_SEPIN[1]; 
    /*---------------------------------variables-------------------------------*/
    
    
    /*---------------------------------MVs-------------------------------*/
    double F_O2, F_C2H4, F_HAc, Q_Duty_Vaporizer, F_vaporizer, Q_Heater;
    double Shell_T_RCT, F_SepLiquidOUT, Shell_T_Sep, F_SepVaporOUT;
    double Q_Compressor, F_AbsLiquidOut, F_Circulation, Q_Circulation, F_Scrub, Q_Scrub;
    double F_CO2, F_Purge, bypass, F_Reflux, Q_Reboiler, F_Organic, F_Aqueous, F_Bottom, Q_Condenser, F_VapLiquidIn; 
    /*---------------------------------MVs-------------------------------*/
    
    
    /*---------------------------------Other Variables-------------------------------*/
    double F_GasRemovalIn[1], x_GasRemovalIn[7], T_GasRemovalIn[1];
    double F_ABSIN_Gas2[1], y_ABSIN_Gas2[7], T_ABSIN_Gas2[1];
    double F_COLIN[1], x_COLIN[7], T_COLIN[1];
    double F_CompressorIn[1],y_CompressorIn[7],T_CompressorIn[1];
    double F_ABSIN_Gas[1], y_ABSIN_Gas[7], T_CompCoolerIn[1], P_recycle[1];
    double dummy[1], HV_ABSIN_Gas[1], temp_x_HAcTank[7]={0.,0.,0.,0.,0.,0.,0.};
    double temp_HV[1], HV_CompCoolerIn[1];
    double AAA, BBB, CCC;
    double Level[1], TV[8], TL[8];
    double F_AbsGasOut[1], y_AbsGasOut[7], T_AbsGasOut[1], x_AbsLiquidOut[7];
    double T_AbsLiquidOut[1];
    double F_CO2Purge[1], y_CO2Purge[7], T_CO2Purge[1], y_Purge[7], T_Purge[1], F_ToVap[1], y_ToVap[7];
    double T_ToVap[1], F_FEHEIN_cold[1], y_FEHEIN_cold[7], T_FEHEIN_cold[1];
    double ps[7], g[7];
    double P_vaporizer[1], y_vaporizer[7], HV_vaporizer[1], HV_heaterOut[1];
    double F_RCTIN[1], y_RCTIN[7], T_RCTIN[1], P_RCTIN, C_RCTIN, P_Drop, r_RCTIN, G_RCTIN, V_RCTIN;
    double C_FEHEIN_hot, F_FEHEIN_hot[1], y_FEHEIN_hot[7], T_FEHEIN_hot[1], F_FEHEColdOut[1], y_FEHEColdOut[7];
    double F_SEPIN[1], y_SEPIN[7], F_VapVapIn[1], y_VapVapIn[7], T_VapVapIn[1], x_VapLiquidIn[7]={0.,0.,0.,0.,0.,0.,0.}, T_VapLiquidIn[1]; 
    double P_Column[20], beta_out[1];
    double Level_Vaporizer[1], y_Vaporizer[7], T_Vaporizer[1], P_Vaporizer[1];
    double x_Organic[7], T_Organic[1], x_Aqueous[7], T_Aqueous[1];
    double states_abs[72], states_vap[8], states_rct[70], states_sep[16], states_col[73]; 
    double dstatesdt_abs[72], dstatesdt_vap[8], dstatesdt_rct[70], dstatesdt_sep[16], dstatesdt_col[73], dstatesdt_other[7];
    double Q_Circulation_out[1], Q_Scrub_out[1], Q_Condenser_out[1];
    int i, j;
    double sum1, sum2, sum3, temp_single_1[1], temp_single_2[1];

    double VIJ[7][7];
    for (i=0;i<7;i++)
    {
        for (j=0;j<7;j++)
            VIJ[i][j] = Vi[j]/Vi[i];
    };
    for (i=0;i<NF_column[0];i++)
    {
    	M0_column[i]=2.3;   
    	L0_column[i]=8.7947;
    };
    for (i=NF_column[0];i<NT_column[0];i++)
    {
    	M0_column[i]=2.3;
    	L0_column[i]=4.9741;
    }

    //if disturbance 1
    if ((disturbance_ID==1) && (is_initial!=1))
    {
        y_C2H4[2]=0.997;
        y_C2H4[3]=0.003;
    }
    //if disturbance 3
    if ((disturbance_ID==3) && (is_initial!=1))
    {
        MVs[2]=0;
    }
    //if disturbance 4
    if ((disturbance_ID==4) && (is_initial!=1))
    {
        MVs[0]=0;
    }

    /*---------------------------------variables-------------------------------*/

    /*--------------------------------------------------------------------------------------*/
    /*load initial states and MVs if requested                                      	    */
    /*--------------------------------------------------------------------------------------*/
    if (is_initial==1)
    {
        time=0; //make sure time=0 in order to calculate process measurements
        steadystate(MVs, states); /*load steadystate*/
    };
    
    /*--------------------------------------------------------------------------------------*/
    /*set states variables 									*/
    /*--------------------------------------------------------------------------------------*/
    /*The Vaporizer has 8 states								*/
    x_vaporizer[0] = states[0];
    x_vaporizer[1] = states[1];
    x_vaporizer[2] = states[2];
    x_vaporizer[4] = states[3];
    x_vaporizer[5] = states[4];
    x_vaporizer[6] = states[5];
    hup_vaporizer[0]=states[6];                       
    T_vaporizer[0]=states[7];
    /*The Reactor has 70 states                                                            */
    for (i=0;i<NR[0]-1;i++)
    {
        C_O2[i+1]=states[i+8];
        C_CO2[i+1]=states[NR[0]-1+i+8];
        C_C2H4[i+1]=states[2*NR[0]-2+i+8];
        C_VAc[i+1]=states[3*NR[0]-3+i+8];
        C_H2O[i+1]=states[4*NR[0]-4+i+8];
        C_HAc[i+1]=states[5*NR[0]-5+i+8];
        T_reactor[i+1]=states[6*NR[0]-6+i+8];
    };
    /*The Separator has 16 states                                                            */
    for (i=0;i<3;i++)
    {
        x_separator[i]=states[i+78];
        x_separator[i+4]=states[i+3+78];
    };
    hup_separator[0]=states[84];           
    TL_separator[0]=states[85];
    for (i=0;i<3;i++)
    {
        y_separator[i]=states[i+86];
        y_separator[i+4]=states[i+3+86];
    };
    P_separator[0]=states[92];
    TV_separator[0]=states[93];
    /*The Absorber has 72 states                                                            */
    for (i=0;i<NT_absorber[0];i++)
    {
        x_absorber[i][0]=states[i+94];
        x_absorber[i][1]=states[i+NT_absorber[0]+94];
        x_absorber[i][2]=states[i+2*NT_absorber[0]+94];
        x_absorber[i][4]=states[i+3*NT_absorber[0]+94];   
        x_absorber[i][5]=states[i+4*NT_absorber[0]+94];
        x_absorber[i][6]=states[i+5*NT_absorber[0]+94];
        M_absorber[i]=states[i+6*NT_absorber[0]+94];
        TL_absorber[i]=states[i+7*NT_absorber[0]+94];
    };
    x_base[0]=states[8*NT_absorber[0]+94];
    x_base[1]=states[8*NT_absorber[0]+1+94];
    x_base[2]=states[8*NT_absorber[0]+2+94];
    x_base[4]=states[8*NT_absorber[0]+3+94];
    x_base[5]=states[8*NT_absorber[0]+4+94];
    x_base[6]=states[8*NT_absorber[0]+5+94]; 
    hup_base[0]=states[164];
    T_base[0]=states[165];
    /*The Column has 69 states     								*/
    for (i=0;i<NT_column[0]; i++)
    {
        x_column[i][0]=states[i+166];
        x_column[i][2]=states[i+NT_column[0]+166];
        M_column[i]=states[i+2*NT_column[0]+166];
    };
    x_bottom[0]=states[226];
    x_bottom[2]=states[227];
    hup_bottom[0]=states[228];
    x_organic[0]=states[229];
    x_organic[2]=states[230];
    hup_organic[0]=states[231];
    x_aqueous[0]=states[232];
    x_aqueous[2]=states[233];
    hup_aqueous[0]=states[234];            
    /*The HAc Tank has 4 states                                                              */
    x_HAcTank[0]=states[235];
    x_HAcTank[2]=states[236];
    hup_HAcTank[0]=states[237];            
    T_HAcTank[0]=states[238];
    /*states for heater/cooler temperatures               								*/
    T_VapHeaterOut[0]=states[239];
    T_ABSIN_Gas[0]=states[240];
    T_Circulation[0]=states[241];
    T_Scrub[0]=states[242];
    T_decanter[0]=states[243]; 
    T_FEHEColdOut[0]=states[244];
    T_SEPIN[0]=states[245];

    /*--------------------------------------------------------------------------------------*/
    /*set MVs                                        										*/	
    /*--------------------------------------------------------------------------------------*/
    F_O2=MVs[0];                    
    F_C2H4=MVs[1];                  
    F_HAc=MVs[2];                   
    Q_Duty_Vaporizer=MVs[3];        
    F_vaporizer=MVs[4];             
    Q_Heater=MVs[5];                
    Shell_T_RCT=MVs[6];             
    F_SepLiquidOUT=MVs[7];          
    Shell_T_Sep=MVs[8];             
    F_SepVaporOUT=MVs[9];           
    Q_Compressor=MVs[10];           
    F_AbsLiquidOut=MVs[11];         
    F_Circulation=MVs[12];          
    Q_Circulation=MVs[13];          
    F_Scrub=MVs[14];                
    Q_Scrub=MVs[15];                
    F_CO2=MVs[16];                  
    F_Purge=MVs[17];                
    bypass=MVs[18];                 
    F_Reflux=MVs[19];               
    Q_Reboiler=MVs[20];             
    Q_Condenser=MVs[21];            
    F_Organic=MVs[22];              
    F_Aqueous=MVs[23];              
    F_Bottom=MVs[24];               
    F_VapLiquidIn=MVs[25];          
    /*------------------------------------------------------------------------------------------*/

    /*------------------------------------------------------------------------------------------*/
    //get full values of separator liquid composition and absorber base liquid composition 
    sum1=0.;
    sum2=0.;
    x_separator[3]=0.;
    x_base[3]=0.;
    for (i=0;i<7;i++)
    {
        sum1+=x_separator[i];
        sum2+=x_base[i];
    };
    x_separator[3]=1-sum1;
    x_base[3]=1-sum2;
    
    //get mixer output  
    temp_single_1[0]=F_SepLiquidOUT;
    temp_single_2[0]=F_AbsLiquidOut;    
    mixer(F_GasRemovalIn,x_GasRemovalIn,T_GasRemovalIn, 0, temp_single_1, x_separator, TL_separator,temp_single_2,x_base,T_base,MW, HVAP, HCAPLa, HCAPLb, HCAPVa, HCAPVb);

    //calculate gas remove   
    Gas_Remove(F_ABSIN_Gas2, y_ABSIN_Gas2, T_ABSIN_Gas2, F_COLIN, x_COLIN, T_COLIN, F_GasRemovalIn,x_GasRemovalIn,T_GasRemovalIn);
    //if disturbance 2
    if ((disturbance_ID==2) && (is_initial!=1))
    {
        F_COLIN[0]=0;
    }

    //get full values of separator vapor composition
    sum1=0.;
    y_separator[3]=0.;
    for (i=0;i<7;i++)
        sum1+=y_separator[i];
    y_separator[3]=1-sum1;

    //get mixer output  
    temp_single_1[0]=F_SepVaporOUT;    
    mixer(F_CompressorIn,y_CompressorIn,T_CompressorIn, 1, temp_single_1,y_separator,TV_separator,F_ABSIN_Gas2,y_ABSIN_Gas2,T_ABSIN_Gas2, MW, HVAP,HCAPLa, HCAPLb, HCAPVa, HCAPVb);

    //calculate compressor
    Compressor(F_ABSIN_Gas,y_ABSIN_Gas,T_CompCoolerIn, P_recycle, F_CompressorIn,y_CompressorIn,TV_separator, P_separator, Compressor_coefficient, MW);
    
    //calculate compressor heat duty
    enthalpy_7(dummy, temp_HV, y_ABSIN_Gas, y_ABSIN_Gas, T_CompCoolerIn, MW, HVAP, HCAPLa, HCAPLb, HCAPVa, HCAPVb);
    HV_CompCoolerIn[0] = temp_HV[0];
   	sum1=0.;
   	BBB=0.;
   	AAA=0.;
   	for (i=0;i<7;i++)
   	{
   		sum1+=HVAP[i]*y_ABSIN_Gas[i];	
   		BBB+=HCAPVa[i]*MW[i]*y_ABSIN_Gas[i];
   		AAA+=0.5*HCAPVb[i]*MW[i]*y_ABSIN_Gas[i];
   	}
   	CCC=-(F_ABSIN_Gas[0]*HV_CompCoolerIn[0]-Q_Compressor)/F_ABSIN_Gas[0]+sum1;
   	if ((BBB*BBB-4*AAA*CCC)<0)
   		printf("error on compressor temp");
  	//calculate the temperature derivative, tau=2 minute
  	dstatesdt_other[1]=((-BBB+sqrt(BBB*BBB-4*AAA*CCC))/(2*AAA)-T_ABSIN_Gas[0])/2;

    //get full values of HAc tank liquid composition from 3 to 7
    sum1=0.;
    x_HAcTank[1]=0.;
    for (i=0;i<3;i++)
        sum1+=x_HAcTank[i];
    x_HAcTank[1]=1-sum1;
    temp_x_HAcTank[4] = x_HAcTank[0];
    temp_x_HAcTank[5] = x_HAcTank[1];
    temp_x_HAcTank[6] = x_HAcTank[2];

    //Calculate absorber
    for (i=94;i<166;i++)
    {
        states_abs[i-94] = states[i];
    }
    Absorber(dstatesdt_abs, dstatesdt_other, Level, TV, TL, F_AbsGasOut,
        y_AbsGasOut, T_AbsGasOut, x_AbsLiquidOut, T_AbsLiquidOut,
        states_abs,P_recycle[0],F_AbsLiquidOut,F_ABSIN_Gas[0], y_ABSIN_Gas, T_ABSIN_Gas[0], F_Scrub, temp_x_HAcTank, T_HAcTank[0],
        F_Circulation,Q_Circulation,Q_Scrub,NT_absorber[0], NF_absorber[0], Working_Volume_absorber[0], M0_absorber, L0_absorber,
        hydtau_absorber[0], Nmt, Qmt, T_Circulation, T_Scrub, VIJ, AIJ, MW, SpG, HVAP, HCAPLa, HCAPLb, HCAPVa, HCAPVb, A, B, C, R, Dw, T_ref);
    
    //Calculate CO2_Remove
    CO2_Remove(F_CO2Purge, y_CO2Purge, T_CO2Purge, y_Purge, T_Purge, F_ToVap, y_ToVap, T_ToVap,
            F_FEHEIN_cold, y_FEHEIN_cold, T_FEHEIN_cold, F_AbsGasOut, y_AbsGasOut,T_AbsGasOut, F_C2H4,
            y_C2H4, T_C2H4, bypass, F_Purge, F_CO2, CO2_F_ref[0], CO2_x_ref[0], MW, HVAP, HCAPLa, HCAPLb,  HCAPVa, HCAPVb);

    //get full values of vaporizer liquid composition
    sum1=0.;
    x_vaporizer[3]=0.;
    for (i=0;i<7;i++)  
        sum1+=x_vaporizer[i];
    x_vaporizer[3]=1-sum1;

    //Calculate reactor input    
    for (i=0;i<7;i++)
        ps[i]=exp(A[i]+B[i]/(T_vaporizer[0]+C[i]));
    gamma_wilson_7(g, T_vaporizer[0], x_vaporizer, VIJ, AIJ, R, T_ref);
    sum1=0.;
    for (i=0;i<7;i++)
        sum1+=x_vaporizer[i]*ps[i]*g[i];
    P_vaporizer[0]=sum1;
    for (i=0;i<7;i++)
        y_vaporizer[i]=x_vaporizer[i]*ps[i]*g[i]/P_vaporizer[0];

    enthalpy_7(dummy, temp_HV, y_vaporizer, y_vaporizer, T_vaporizer, MW, HVAP, HCAPLa, HCAPLb, HCAPVa, HCAPVb);
    HV_vaporizer[0] = temp_HV[0];
    sum1=0.;
    BBB=0.;
    AAA=0.;
    for (i=0;i<7;i++)
    {
       	sum1+=HVAP[i]*y_vaporizer[i];	
       	BBB+=HCAPVa[i]*MW[i]*y_vaporizer[i];
        AAA+=0.5*HCAPVb[i]*MW[i]*y_vaporizer[i];
    };
    CCC=-(F_vaporizer*HV_vaporizer[0]+Q_Heater)/F_vaporizer + sum1;
    if ((BBB*BBB-4*AAA*CCC)<0)
        printf("error on vaporizer heater temp");
    //calculate the temperature derivative, tau=2 minute
    dstatesdt_other[0]=((-BBB+sqrt(BBB*BBB-4*AAA*CCC))/(2*AAA)-T_VapHeaterOut[0])/2;

    temp_single_1[0]=F_vaporizer;
    temp_single_2[0]=F_O2;
    mixer(F_RCTIN,y_RCTIN,T_RCTIN, 1, temp_single_1, y_vaporizer,T_VapHeaterOut, temp_single_2, y_O2, T_O2, MW, HVAP, HCAPLa, HCAPLb, HCAPVa, HCAPVb);
    P_RCTIN=P_vaporizer[0];
    C_RCTIN=(P_RCTIN/14.696*101.325)/(8.314*(T_RCTIN[0]+T_ref));  /*Ideal Gas Law*/ 
    sum1=0.;
    for (i=0;i<7;i++)
        sum1+=MW[i]*y_RCTIN[i];
    G_RCTIN=F_RCTIN[0]*sum1;
    V_RCTIN=F_RCTIN[0]*8.314*(T_RCTIN[0]+273.15)/(P_RCTIN/14.696*101.325); /*volume flowrate*/
    r_RCTIN=G_RCTIN/V_RCTIN; /*density*/
    P_Drop=friction_factor[0]*r_RCTIN*V_RCTIN*V_RCTIN;  

    //Calculate FEHE input    
    T_FEHEIN_hot[0]=T_reactor[NR[0]-1];
    C_FEHEIN_hot = (P_RCTIN-P_Drop)/14.696*101.325/(8.314*(T_FEHEIN_hot[0]+T_ref));  /*Ideal Gas Law*/ 
    y_FEHEIN_hot[0] = C_O2[NR[0]-1]/C_FEHEIN_hot;
    y_FEHEIN_hot[1] = C_CO2[NR[0]-1]/C_FEHEIN_hot; 
    y_FEHEIN_hot[2] = C_C2H4[NR[0]-1]/C_FEHEIN_hot;
    y_FEHEIN_hot[4] = C_VAc[NR[0]-1]/C_FEHEIN_hot;
    y_FEHEIN_hot[5] = C_H2O[NR[0]-1]/C_FEHEIN_hot; 
    y_FEHEIN_hot[6] = C_HAc[NR[0]-1]/C_FEHEIN_hot;
    y_FEHEIN_hot[3] = 1-y_FEHEIN_hot[0]-y_FEHEIN_hot[1]-y_FEHEIN_hot[2]-y_FEHEIN_hot[4]-y_FEHEIN_hot[5]-y_FEHEIN_hot[6];
    sum1=0.;
    for (i=0;i<7;i++)
        sum1+=MW[i]*y_FEHEIN_hot[i];
    F_FEHEIN_hot[0]=G_RCTIN/sum1;
    
    //Calculate FEHE
    FEHE(dstatesdt_other,F_FEHEColdOut,y_FEHEColdOut, F_SEPIN, y_SEPIN, T_FEHEColdOut, T_SEPIN, F_FEHEIN_cold, y_FEHEIN_cold, T_FEHEIN_cold, F_FEHEIN_hot, y_FEHEIN_hot, T_FEHEIN_hot, UA_FEHE, Ref_hotflow, Ref_coolflow, Ref, MW, HVAP, HCAPLa, HCAPLb, HCAPVa,HCAPVb);
        
    //Calculate Vaporizer vapor input
    mixer(F_VapVapIn,y_VapVapIn,T_VapVapIn, 1, F_FEHEColdOut,y_FEHEColdOut,T_FEHEColdOut,F_ToVap,y_ToVap, T_ToVap, MW, HVAP, HCAPLa, HCAPLb, HCAPVa, HCAPVb);
    
    //Calculate Vaporizer liquid input
    x_VapLiquidIn[4]=x_HAcTank[0];
    x_VapLiquidIn[5]=x_HAcTank[1];
    x_VapLiquidIn[6]=x_HAcTank[2];
    T_VapLiquidIn[0]=T_HAcTank[0];

    //Calculate column pressure profile
    for (i=0;i<NT_column[0];i++)
        P_Column[i]=29.4-i*0.6; 

    //get full values of column liquid composition        
    sum1=0.;
    sum2=0.;
    sum3=0.;
    x_bottom[1]=0.;
    x_organic[1]=0.;
    x_aqueous[1]=0.;
    for (i=0;i<3;i++)
    {
        sum1+=x_bottom[i];
        sum2+=x_organic[i];
        sum3+=x_aqueous[i];
    };
    x_bottom[1]=1-sum1;
    x_organic[1]=1-sum2;
    x_aqueous[1]=1-sum3;

    /*---------------------------------------------------------------------------------------------*/
    //unit operation dynamics
    for (i=0;i<8;i++)
    {
        states_vap[i] = states[i];
        dstatesdt_vap[i]=0;        
    }
    Vaporizer(dstatesdt_vap,Level_Vaporizer,y_Vaporizer,T_Vaporizer,P_Vaporizer,
            states_vap, F_vaporizer, Q_Duty_Vaporizer, F_VapVapIn[0], y_VapVapIn, T_VapVapIn[0], 
            F_VapLiquidIn, x_VapLiquidIn, T_VapLiquidIn[0], Working_Volume_vaporizer[0], 
            VIJ, AIJ, MW, SpG, HVAP, HCAPLa, HCAPLb, HCAPVa, HCAPVb, A, B, C, R, Dw, T_ref);
    
    for (i=8;i<78;i++)
    {
        states_rct[i-8] = states[i];
    }
    Reactor(dstatesdt_rct, states_rct, time, F_RCTIN[0], y_RCTIN, T_RCTIN[0],
            P_RCTIN, C_RCTIN, P_Drop, Shell_T_RCT, sto1, sto2, NR[0], tube_L[0],
            tube_number[0], tube_diameter[0], tube_area[0], UA_reactor[0], cata_bulk_density[0],
            cata_heatcapacity[0], cata_porosity[0], cata_weight[0], E_r1[0], E_r2[0],
            MW, HVAP, HCAPLa, HCAPLb, HCAPVa, HCAPVb, T_ref);
    
    for (i=78;i<94;i++)
    {
        states_sep[i-78] = states[i];
        dstatesdt_sep[i-78]=0;
    } 
    Separator(dstatesdt_sep, states_sep, F_SEPIN[0], y_SEPIN, T_SEPIN[0], F_SepLiquidOUT, Shell_T_Sep,
            F_SepVaporOUT, Working_Volume_separator[0], Total_Gas_Loop_Volume[0],
            UA_separator[0], VIJ, AIJ, MW, SpG, HVAP, HCAPLa, HCAPLb, HCAPVa, HCAPVb, A, B, C, R, Dw, T_ref);
    
    for (i=166;i<239;i++)
    {
        states_col[i-166] = states[i]; 
        dstatesdt_col[i-166]=0;
    }
    Column(dstatesdt_col, dstatesdt_other, T_Column, x_Organic, T_Organic, x_Aqueous, T_Aqueous, beta_out,
            states_col, P_Column, F_COLIN[0], x_COLIN, T_COLIN[0], F_Reflux,
            Q_Reboiler, F_Organic,F_Aqueous,F_Bottom, T_Column, F_HAc, x_HAc, T_HAc[0], F_Scrub, F_VapLiquidIn, 
            20, 15, P_top[0], P_bottom[0], T_decanter, K_decanter, hydtau_column[0], M0_column, L0_column,
            Bottom_Working_Level_Volume[0], Organic_Working_Level_Volume[0], Aqueous_Working_Level_Volume[0],
            HAcTank_Working_Level_Volume[0], VIJ, AIJ, MW, SpG, HVAP, HCAPLa, HCAPLb,HCAPVa, HCAPVb, A, B, C, R, Dw,
            T_ref, Q_Condenser);

    for (i=0;i<8;i++)
        *(dstatesdt+i) = dstatesdt_vap[i];
    for (i=8;i<78;i++)
        *(dstatesdt+i) = dstatesdt_rct[i-8];
    for (i=78;i<94;i++)
        *(dstatesdt+i) = dstatesdt_sep[i-78];
    for (i=94;i<166;i++)
        *(dstatesdt+i) = dstatesdt_abs[i-94];
    for (i=166;i<239;i++)
        *(dstatesdt+i) = dstatesdt_col[i-166];
    for (i=239;i<246;i++)
        *(dstatesdt+i) = dstatesdt_other[i-239];

    /*--------------------------------------------------------------------------------------*/
    measurements[0]=P_vaporizer[0];
    measurements[1]=hup_vaporizer[0];
    measurements[2]=T_vaporizer[0];
    measurements[3]=T_VapHeaterOut[0];
    measurements[4]=T_reactor[NR[0]-1];    
    measurements[5]=F_FEHEIN_hot[0];
    measurements[6]=T_FEHEColdOut[0];
    measurements[7]=T_SEPIN[0];
    measurements[8]=hup_separator[0];
    measurements[9]=TL_separator[0];
    measurements[10]=T_ABSIN_Gas[0];
    measurements[11]=P_recycle[0];
    measurements[12]=hup_base[0];
    measurements[13]=T_Circulation[0];
    measurements[14]=T_Scrub[0];
    measurements[15]=F_ToVap[0]+F_FEHEIN_cold[0];
    measurements[16]=F_Organic;
    measurements[17]=hup_organic[0];
    measurements[18]=hup_aqueous[0];
    measurements[19]=T_decanter[0];
    measurements[20]=hup_bottom[0];
    measurements[21]=T_Column[4];
    measurements[22]=hup_HAcTank[0];
    measurements[23]=x_Organic[4];
    measurements[24]=x_Organic[5];
    measurements[25]=x_Organic[6];
    measurements[26]=x_bottom[0];
    measurements[27]=x_bottom[1];
    measurements[28]=x_bottom[2];
    measurements[29]=y_ToVap[0];
    measurements[30]=y_ToVap[1];
    measurements[31]=y_ToVap[2];
    measurements[32]=y_ToVap[3];
    measurements[33]=y_ToVap[4];
    measurements[34]=y_ToVap[5];
    measurements[35]=y_ToVap[6];
    measurements[36]=y_RCTIN[0];
    measurements[37]=y_RCTIN[1];
    measurements[38]=y_RCTIN[2];
    measurements[39]=y_RCTIN[3];
    measurements[40]=y_RCTIN[4];
    measurements[41]=y_RCTIN[5];
    measurements[42]=y_RCTIN[6];

    for (i=0;i<26;i++)
    {
	    MVs_out[i] = MVs[i];
    }

    for (i=0;i<246;i++)
    {
       	states_out[i] = states[i];
    }

    //if disturbance 5
    if ((disturbance_ID==5) && (is_initial!=1))
    {
        measurements[23]=0;
        measurements[24]=0;
        measurements[25]=0;
    }
    //if disturbance 6
    if ((disturbance_ID==6) && (is_initial!=1))
    {
        measurements[26]=0;
        measurements[27]=0;
        measurements[28]=0;
    }
    //if disturbance 7
    if ((disturbance_ID==7) && (is_initial!=1))
    {
        measurements[29]=0;
        measurements[30]=0;
        measurements[31]=0;
        measurements[32]=0;
        measurements[33]=0;
        measurements[34]=0;
        measurements[35]=0;
    }

}
bool BoardE1::KhompPvtE1::indicateBusyUnlocked(int cause, bool sent_signaling)
{
    DBG(FUNC, PVT_FMT(_target, "(E1) c"));

    if(!KhompPvt::indicateBusyUnlocked(cause, sent_signaling))
    {
        DBG(FUNC, PVT_FMT(_target, "(E1) r (false)"));
        return false;
    }

    if(call()->_flags.check(Kflags::IS_INCOMING))
    {
        if(!call()->_flags.check(Kflags::CONNECTED) && !sent_signaling)
        {
            if(!call()->_flags.check(Kflags::HAS_PRE_AUDIO))
            {
                int rb_value = callFailFromCause(call()->_hangup_cause);
                DBG(FUNC, PVT_FMT(target(), "sending the busy status"));

                if (sendRingBackStatus(rb_value) == RingbackDefs::RBST_UNSUPPORTED)
                {
                    DBG(FUNC, PVT_FMT(target(), "falling back to audio indication!"));
                    /* stop the line audio */
                    stop_stream();

                    /* just pre connect, no ringback */
                    if (!sendPreAudio())
                        DBG(FUNC, PVT_FMT(target(), "everything else failed, just sending audio indication..."));

                    /* be very specific about the situation. */
                    mixer(KHOMP_LOG, 1, kmsGenerator, kmtBusy);
                }
            }
            else
            {
                DBG(FUNC, PVT_FMT(target(), "going to play busy"));

                /* stop the line audio */
                stop_stream();

                /* be very specific about the situation. */
                mixer(KHOMP_LOG, 1, kmsGenerator, kmtBusy);

            }
        }
        else
        {
            /* already connected or sent signaling... */
            mixer(KHOMP_LOG, 1, kmsGenerator, kmtBusy);
        }

    }
    else if(call()->_flags.check(Kflags::IS_OUTGOING))
    {
        /* already connected or sent signaling... */
        mixer(KHOMP_LOG, 1, kmsGenerator, kmtBusy);
    }

    DBG(FUNC,PVT_FMT(_target, "(E1) r"));
    
    return true; 
}
status_t AudioStreamInALSA::setGain(float gain)
{
    return mixer() ? mixer()->setMasterGain(gain) : (status_t)NO_INIT;
}
Example #12
0
int AudioJack::processCallback( jack_nframes_t _nframes, void * _udata )
{
	for( int c = 0; c < channels(); ++c )
	{
		m_tempOutBufs[c] =
			(jack_default_audio_sample_t *) jack_port_get_buffer(
												m_outputPorts[c], _nframes );
	}

#ifdef AUDIO_PORT_SUPPORT
	const int frames = qMin<int>( _nframes, mixer()->framesPerPeriod() );
	for( jackPortMap::iterator it = m_portMap.begin();
						it != m_portMap.end(); ++it )
	{
		for( ch_cnt_t ch = 0; ch < channels(); ++ch )
		{
			if( it.data().ports[ch] == NULL )
			{
				continue;
			}
			jack_default_audio_sample_t * buf =
			(jack_default_audio_sample_t *) jack_port_get_buffer(
							it.data().ports[ch],
								_nframes );
			for( int frame = 0; frame < frames; ++frame )
			{
				buf[frame] = it.key()->firstBuffer()[frame][ch];
			}
		}
	}
#endif

	jack_nframes_t done = 0;
	while( done < _nframes && m_stopped == false )
	{
		jack_nframes_t todo = qMin<jack_nframes_t>(
						_nframes,
						m_framesToDoInCurBuf -
							m_framesDoneInCurBuf );
		const float gain = mixer()->masterGain();
		for( int c = 0; c < channels(); ++c )
		{
			jack_default_audio_sample_t * o = m_tempOutBufs[c];
			for( jack_nframes_t frame = 0; frame < todo; ++frame )
			{
				o[done+frame] = m_outBuf[m_framesDoneInCurBuf+frame][c] * gain;
			}
		}
		done += todo;
		m_framesDoneInCurBuf += todo;
		if( m_framesDoneInCurBuf == m_framesToDoInCurBuf )
		{
			m_framesToDoInCurBuf = getNextBuffer( m_outBuf );
			if( !m_framesToDoInCurBuf )
			{
				m_stopped = true;
				m_stopSemaphore.release();
			}
			m_framesDoneInCurBuf = 0;
		}
	}

	if( m_stopped == true )
	{
		for( int c = 0; c < channels(); ++c )
		{
			jack_default_audio_sample_t * b = m_tempOutBufs[c] + done;
			memset( b, 0, sizeof( *b ) * ( _nframes - done ) );
		}
	}

	return 0;
}
Example #13
0
AudioSoundIo::AudioSoundIo( bool & outSuccessful, Mixer * _mixer ) :
	AudioDevice( tLimit<ch_cnt_t>(
		ConfigManager::inst()->value( "audiosoundio", "channels" ).toInt(), DEFAULT_CHANNELS, SURROUND_CHANNELS ),
								_mixer )
{
	outSuccessful = false;
	m_soundio = NULL;
	m_outstream = NULL;
	m_disconnectErr = 0;
	m_outBufFrameIndex = 0;
	m_outBufFramesTotal = 0;

	m_soundio = soundio_create();
	if (!m_soundio)
	{
		fprintf(stderr, "Unable to initialize soundio: out of memory\n");
		return;
	}

	m_soundio->app_name = "LMMS";
	m_soundio->userdata = this;
	m_soundio->on_backend_disconnect = staticOnBackendDisconnect;

	const QString& configBackend = ConfigManager::inst()->value( "audiosoundio", "backend" );
	const QString& configDeviceId = ConfigManager::inst()->value( "audiosoundio", "out_device_id" );
	const QString& configDeviceRaw = ConfigManager::inst()->value( "audiosoundio", "out_device_raw" );

	int err;
	int outDeviceCount = 0;
	int backendCount = soundio_backend_count(m_soundio);
	for (int i = 0; i < backendCount; i += 1)
	{
		SoundIoBackend backend = soundio_get_backend(m_soundio, i);
		if (configBackend == soundio_backend_name(backend))
		{
			if ((err = soundio_connect_backend(m_soundio, backend)))
			{
				// error occurred, leave outDeviceCount 0
			}
			else
			{
				soundio_flush_events(m_soundio);
				if (m_disconnectErr)
				{
					fprintf(stderr, "Unable to initialize soundio: %s\n", soundio_strerror(m_disconnectErr));
					return;
				}
				outDeviceCount = soundio_output_device_count(m_soundio);
			}
			break;
		}
	}

	if (outDeviceCount <= 0)
	{
		// try connecting to the default backend
		if ((err = soundio_connect(m_soundio)))
		{
			fprintf(stderr, "Unable to initialize soundio: %s\n", soundio_strerror(err));
			return;
		}

		soundio_flush_events(m_soundio);
		if (m_disconnectErr)
		{
			fprintf(stderr, "Unable to initialize soundio: %s\n", soundio_strerror(m_disconnectErr));
			return;
		}

		outDeviceCount = soundio_output_device_count(m_soundio);

		if (outDeviceCount <= 0)
		{
			fprintf(stderr, "Unable to initialize soundio: no devices found\n");
			return;
		}
	}

	int selected_device_index = soundio_default_output_device_index(m_soundio);

	bool wantRaw = (configDeviceRaw == "yes");
	for (int i = 0; i < outDeviceCount; i += 1)
	{
		SoundIoDevice *device = soundio_get_output_device(m_soundio, i);
		bool isThisOne = (configDeviceId == device->id && wantRaw == device->is_raw);
		soundio_device_unref(device);
		if (isThisOne)
		{
			selected_device_index = i;
			break;
		}
	}

	SoundIoDevice *device = soundio_get_output_device(m_soundio, selected_device_index);
	m_outstream = soundio_outstream_create(device);
	soundio_device_unref(device);

	if (!m_outstream)
	{
		fprintf(stderr, "Unable to initialize soundio: out of memory\n");
		return;
	}

	int currentSampleRate = sampleRate();
	int closestSupportedSampleRate = -1;

	for (int i = 0; i < device->sample_rate_count; i += 1)
	{
		SoundIoSampleRateRange *range = &device->sample_rates[i];
		if (range->min <= currentSampleRate && currentSampleRate <= range->max)
		{
			closestSupportedSampleRate = currentSampleRate;
			break;
		}
		if (closestSupportedSampleRate == -1 ||
			abs(range->max - currentSampleRate) < abs(closestSupportedSampleRate - currentSampleRate))
		{
			closestSupportedSampleRate = range->max;
		}
	}

	if (closestSupportedSampleRate != currentSampleRate)
	{
		setSampleRate(closestSupportedSampleRate);
		currentSampleRate = closestSupportedSampleRate;
	}

	m_outstream->name = "LMMS";
	m_outstream->software_latency = (double)mixer()->framesPerPeriod() / (double)currentSampleRate;
	m_outstream->userdata = this;
	m_outstream->write_callback = staticWriteCallback;
	m_outstream->error_callback = staticErrorCallback;
	m_outstream->underflow_callback = staticUnderflowCallback;
	m_outstream->sample_rate = currentSampleRate;
	m_outstream->layout = *soundio_channel_layout_get_default(channels());
	m_outstream->format = SoundIoFormatFloat32NE;

	if ((err = soundio_outstream_open(m_outstream)))
	{
		fprintf(stderr, "Unable to initialize soundio: %s\n", soundio_strerror(err));
		return;
	}

	fprintf(stderr, "Output device: '%s' backend: '%s'\n",
			device->name, soundio_backend_name(m_soundio->current_backend));

	outSuccessful = true;
}
Example #14
0
int AudioAlsa::setHWParams( const ch_cnt_t _channels, snd_pcm_access_t _access )
{
	int err, dir;

	// choose all parameters
	if( ( err = snd_pcm_hw_params_any( m_handle, m_hwParams ) ) < 0 )
	{
		printf( "Broken configuration for playback: no configurations "
				"available: %s\n", snd_strerror( err ) );
		return err;
	}

	// set the interleaved read/write format
	if( ( err = snd_pcm_hw_params_set_access( m_handle, m_hwParams,
							_access ) ) < 0 )
	{
		printf( "Access type not available for playback: %s\n",
							snd_strerror( err ) );
		return err;
	}

	// set the sample format
	if( ( snd_pcm_hw_params_set_format( m_handle, m_hwParams,
						SND_PCM_FORMAT_S16_LE ) ) < 0 )
	{
		if( ( snd_pcm_hw_params_set_format( m_handle, m_hwParams,
						SND_PCM_FORMAT_S16_BE ) ) < 0 )
		{
			printf( "Neither little- nor big-endian available for "
					"playback: %s\n", snd_strerror( err ) );
			return err;
		}
		m_convertEndian = isLittleEndian();
	}
	else
	{
		m_convertEndian = !isLittleEndian();
	}

	// set the count of channels
	if( ( err = snd_pcm_hw_params_set_channels( m_handle, m_hwParams,
							_channels ) ) < 0 )
	{
		printf( "Channel count (%i) not available for playbacks: %s\n"
				"(Does your soundcard not support surround?)\n",
					_channels, snd_strerror( err ) );
		return err;
	}

	// set the sample rate
	if( ( err = snd_pcm_hw_params_set_rate( m_handle, m_hwParams,
						sampleRate(), 0 ) ) < 0 )
	{
		if( ( err = snd_pcm_hw_params_set_rate( m_handle, m_hwParams,
				mixer()->baseSampleRate(), 0 ) ) < 0 )
		{
			printf( "Could not set sample rate: %s\n",
							snd_strerror( err ) );
			return err;
		}
	}

	m_periodSize = mixer()->framesPerPeriod();
	m_bufferSize = m_periodSize * 8;
	dir = 0;
	err = snd_pcm_hw_params_set_period_size_near( m_handle, m_hwParams,
							&m_periodSize, &dir );
	if( err < 0 )
	{
		printf( "Unable to set period size %lu for playback: %s\n",
					m_periodSize, snd_strerror( err ) );
		return err;
	}
	dir = 0;
	err = snd_pcm_hw_params_get_period_size( m_hwParams, &m_periodSize,
									&dir );
	if( err < 0 )
	{
		printf( "Unable to get period size for playback: %s\n",
							snd_strerror( err ) );
	}

	dir = 0;
	err = snd_pcm_hw_params_set_buffer_size_near( m_handle, m_hwParams,
								&m_bufferSize );
	if( err < 0 )
	{
		printf( "Unable to set buffer size %lu for playback: %s\n",
					m_bufferSize, snd_strerror( err ) );
		return ( err );
	}
	err = snd_pcm_hw_params_get_buffer_size( m_hwParams, &m_bufferSize );

	if( 2 * m_periodSize > m_bufferSize )
	{
		printf( "buffer to small, could not use\n" );
		return ( err );
	}


	// write the parameters to device
	err = snd_pcm_hw_params( m_handle, m_hwParams );
	if( err < 0 )
	{
		printf( "Unable to set hw params for playback: %s\n",
							snd_strerror( err ) );
		return ( err );
	}

	return ( 0 );	// all ok
}
Example #15
0
/*****************************************************************************
 *	\brief		Signal processing
 * 				TODO: Add signal processing modules
 * 				TODO: Add on/off setting for each module
 *	\parameters	
 *	\return		None
 *****************************************************************************/
void true_voice(tvRxChannels_t rx, tvMicChannels_t mic, tvTxChannels_t tx, tvSpeakerChannels_t ls) {

	//VAD for LMR
	//init Elmr, bSpeechLMR, timer bLMRVadOverride
//	energy_vad(rx.psLmr, &q15Elmr, &bSpeechLMR, &timer_LMR_VAD);
//	if(bLMRVadOverride == true){
//		bSpeechLMR = 1;
//	}
//	if(bSpeechLMR == false){
//		memset(rx.psLmr, 0, sizeof(q15)*BUFLEN_8KHZ);
//	}

//    clock_t t_start, t_stop, t_overhead;
//    t_start = clock();
//    t_stop = clock();
//    t_overhead = t_stop - t_start;
//    t_start = clock();
	/*** Microphone noise reduction ***/
	if(tvSettings.platform == TV_CONFIG_BS){
		vadSettings.bVadStatus[NOIRED_MIC_CH_TECH] = nr_damp(mic.psTechHeadset, mic.psMicNoise, &nr_status[NOIRED_MIC_CH_TECH], vadSettings.bVadOverride[NOIRED_MIC_CH_TECH], vadSettings.sVadSensitivity[NOIRED_MIC_CH_TECH]);
		vadSettings.bVadStatus[NOIRED_MIC_CH_PILOT] = nr_damp(mic.psPilotHeadset, mic.psMicNoise, &nr_status[NOIRED_MIC_CH_PILOT], vadSettings.bVadOverride[NOIRED_MIC_CH_PILOT], vadSettings.sVadSensitivity[NOIRED_MIC_CH_PILOT]);
	}
	else if(tvSettings.platform == TV_CONFIG_CA){
		vadSettings.bVadStatus[NOIRED_MIC_CH_TECH] = nr_damp(mic.psTechHeadset, mic.psMicNoise, &nr_status[NOIRED_MIC_CH_TECH], vadSettings.bVadOverride[NOIRED_MIC_CH_TECH], vadSettings.sVadSensitivity[NOIRED_MIC_CH_TECH]);
		vadSettings.bVadStatus[NOIRED_MIC_CH_PILOT] = nr_damp(mic.psPilotHeadset, mic.psMicNoise, &nr_status[NOIRED_MIC_CH_PILOT], vadSettings.bVadOverride[NOIRED_MIC_CH_PILOT], vadSettings.sVadSensitivity[NOIRED_MIC_CH_PILOT]);
	}
	else if(tvSettings.platform == TV_CONFIG_PT){
		// I think that pilot channel should be input?
		vadSettings.bVadStatus[0] = nr_damp(mic.psTechHeadset, mic.psMicNoise, &nr_status[NOIRED_MIC_CH_PILOT], vadSettings.bVadOverride[NOIRED_MIC_CH_PILOT], vadSettings.sVadSensitivity[NOIRED_MIC_CH_PILOT]);
	}

//    t_stop  = clock();
//	printf("Noise reduction took: %f ms\n", (t_stop-t_start-t_overhead)/300E6*1000); //Enable clock first while in debug: Run->Clock->Enable

	/*** Microphone and LMR channel AGC ***/
	// agc(input buffer, struct with agc settings for this channel)
	agc(mic.psTechHeadset, &agcTech);

	if(tvSettings.platform == TV_CONFIG_BS || tvSettings.platform == TV_CONFIG_CA){
		agc(mic.psPilotHeadset, &agcPilot);
	}
	if(tvSettings.platform == TV_CONFIG_BS){
		agc(rx.psLmr, &agcLmr);
	}

	/*** Pilot switch ***/
	// Calculate what state the pilot switch is in (1st tech or CLT).
	pilot_switch(mic.psPilotCable, mic.psPilotCltCable);

	/*** CLT/FTN channels LEC ***/
	//tx.psCltToLine, tx.psFtnToLine is reference signals to be able to cancel the echo
	lec(rx.psClt2wire, rx.psClt4wire, tx.psCltToLine, tx.psFtnToLine, rx.psClt, rx.psFtn);

	/*** Pre mixer ***/
	// Pre mixer of technician and ftn so lec can be made on pilot-technician cable
	// Provide mixer with pointers to audio signals
	pre_mixer_channel_setup(rx, mic, tx, ls);

	pre_aircraft_mixer();

	/*** Pilot-Tech cable connection LEC ***/
	// insert LEC for pilot Tech Cable connection. Only needed when pilot in aircraft choose
	// to talk to technician i.e when tvSettings.bPilotSwitch = 1.
	// mic.psPilotCable = (Pilot+CLT+1st tech (+FTN)), ls.psPilotMonoCable = 1st tech (+FTN)
	// lec to remove 1st tech (+FTN) from mic.psPilotCable
	if (tvSettings.bPilotSwitch){
		lec_aircraft_cable(mic.psPilotCable, ls.psPilotMonoCable);
	}

	/*** DTMF tones ***/
	// Send to line only on BS. Send to LS on PT as well?
	if(tvSettings.platform == TV_CONFIG_BS){
		send_dtmf(DTMFset.psDTMFbuffer,DTMFqueue, &DTMFset);
		send_dtmf(DTMFsetLs.psDTMFbuffer,DTMFqueueLs, &DTMFsetLs);
	} else if(tvSettings.platform == TV_CONFIG_PT){
		send_dtmf(DTMFsetLs.psDTMFbuffer,DTMFqueueLs, &DTMFsetLs);
	}
	/*** Channel mixer ***/
	// Create pilot microphone signals from the processed headset signal or from one of the aircraft cables. Output to rx.psPilot (not on PT)
	pilot_channel_selection(mic.psPilotHeadset, mic.psPilotCable, mic.psPilotCltCable, rx.psPilot);

	// Provide mixer with pointers to audio signals
	mixer_channel_setup(rx, mic, tx, ls);
	// Creates mono output speaker signals and five channels that serve as input to directive audio. Line output signals are also created
	mixer();


	/*** Directive audio ***/
	// Create stereo signal from the five channels created in mixer()
	directive_audio(ls.psTechLeft, ls.psTechRight);

	/*** Volume and limiter adjustment on LS ***/
	// Add side tone, dtmf and MMI (since it has a fixed volume setting)
	if(tvSettings.platform == TV_CONFIG_PT) {
		// volume damping ls channels
		volume(ls.psTechLeft,  volumeSet.q15volumeTech);
		volume(ls.psTechRight, volumeSet.q15volumeTech);

		// volume damping sidetone, DTMF and MMI
		volume(rx.psMmiSounds, volumeSet.q15volumeMMI);
		volume(mic.psTechHeadset, volumeSet.q15volumeTechSidetone);
		volume(DTMFsetLs.psDTMFbuffer, volumeSet.q15volumeDTMF);

		// Add sidetone, dtmf and MMI to ls signal
		//TODO: Dtmf only if first tech. But empty if not making a call so maybe this is ok?
		add_sidetone_dtmf_mmi(mic.psTechHeadset,DTMFsetLs.psDTMFbuffer,rx.psMmiSounds, ls.psTechLeft, &limiterLsLeft);
		add_sidetone_dtmf_mmi(mic.psTechHeadset,DTMFsetLs.psDTMFbuffer,rx.psMmiSounds, ls.psTechRight, &limiterLsRight);

	} else if(tvSettings.platform == TV_CONFIG_BS) {
		// volume damping ls channels
		volume(ls.psTechMono,  volumeSet.q15volumeTech);
		volume(ls.psPilotMono, volumeSet.q15volumePilot);

		// volume damping sidetone, dtmf and mmi
		volume(rx.psPilot, volumeSet.q15volumePilotSidetone);
		volume(rx.psMmiSounds, volumeSet.q15volumeMMI);
		volume(mic.psTechHeadset, volumeSet.q15volumeTechSidetone);
		volume(DTMFsetLs.psDTMFbuffer, volumeSet.q15volumeDTMF);

		// Add sidetone, dtmf and mmi to ls signal

		add_sidetone_dtmf_mmi(mic.psTechHeadset,DTMFsetLs.psDTMFbuffer,rx.psMmiSounds, ls.psTechMono, &limiterLsTechMono);
		// rx.psPilot should only be put in ls.psPilotMono if pilot is connected with headset to CA/BS.
		// If connected with aircraft cable No sidetone and MMI and DTMF should be generated.
		if (tvSettings.bPilotConnection == HEADSET) {
			add_sidetone_dtmf_mmi(rx.psPilot,DTMFsetLs.psDTMFbuffer, rx.psMmiSounds, ls.psPilotMono, &limiterLsPilotMono);
		}

	} else if(tvSettings.platform == TV_CONFIG_CA) {
		// volume damping ls
		volume(ls.psTechLeft,  volumeSet.q15volumeTech);
		volume(ls.psTechRight, volumeSet.q15volumeTech);
		volume(ls.psPilotMono, volumeSet.q15volumePilot);

		// volume damping sidetone
		volume(rx.psPilot, volumeSet.q15volumePilotSidetone);
		volume(rx.psMmiSounds, volumeSet.q15volumeMMI);
		volume(mic.psTechHeadset, volumeSet.q15volumeTechSidetone);

		// Add sidetone and mmi to ls signal
		add_sidetone_mmi(mic.psTechHeadset, rx.psMmiSounds, ls.psTechLeft, &limiterLsLeft_CA);
		add_sidetone_mmi(mic.psTechHeadset, rx.psMmiSounds, ls.psTechRight, &limiterLsRight_CA);
		// rx.psPilot should only be put in ls.psPilotMono if pilot is connected with headset to CA/BS.
		// If connected with aircraft cable No sidetone and MMI and DTMF should be generated.
		if (tvSettings.bPilotConnection == HEADSET) {
			add_sidetone_mmi(rx.psPilot, rx.psMmiSounds, ls.psPilotMono, &limiterLsPilotMono_CA);
		}

	}

	#ifdef USE_DUMPDATA
	dumpdata_post_dump();
	#endif
}
Example #16
0
AudioSndio::AudioSndio(bool & _success_ful, Mixer * _mixer) :
	AudioDevice( tLimit<ch_cnt_t>(
	    ConfigManager::inst()->value( "audiosndio", "channels" ).toInt(),
	    DEFAULT_CHANNELS, SURROUND_CHANNELS ), _mixer ),
            m_convertEndian ( false )
{
	_success_ful = false;

	QString dev = ConfigManager::inst()->value( "audiosndio", "device" );

	if (dev == "")
	{
		m_hdl = sio_open( NULL, SIO_PLAY, 0 );
	}
	else
	{
		m_hdl = sio_open( dev.toLatin1().constData(), SIO_PLAY, 0 );
	}

	if( m_hdl == NULL )
	{
		printf( "sndio: failed opening audio-device\n" );
		return;
	}

	sio_initpar(&m_par);

	m_par.pchan = channels();
	m_par.bits = 16;
	m_par.le = SIO_LE_NATIVE;
	m_par.rate = sampleRate();
	m_par.round = mixer()->framesPerPeriod();
	m_par.appbufsz = m_par.round * 2;

	if ( (isLittleEndian() && (m_par.le == 0)) ||
	     (!isLittleEndian() && (m_par.le == 1))) {
		m_convertEndian = true;
	}

	struct sio_par reqpar = m_par;

	if (!sio_setpar(m_hdl, &m_par))
	{
		printf( "sndio: sio_setpar failed\n" );
		return;
	}
	if (!sio_getpar(m_hdl, &m_par))
	{
		printf( "sndio: sio_getpar failed\n" );
		return;
	}

	if (reqpar.pchan != m_par.pchan ||
		reqpar.bits != m_par.bits ||
		reqpar.le != m_par.le ||
		(::abs(static_cast<int>(reqpar.rate) - static_cast<int>(m_par.rate)) * 100)/reqpar.rate > 2)
	{
		printf( "sndio: returned params not as requested\n" );
		return;
	}

	if (!sio_start(m_hdl))
	{
		printf( "sndio: sio_start failed\n" );
		return;
	}

	_success_ful = true;
}
Example #17
0
void CharcoalFilter::filterImage()
{
    if (m_orgImage.isNull())
    {
        qCWarning(DIGIKAM_DIMG_LOG) << "No image data available!";
        return;
    }

    if (d->pencil <= 0.0)
    {
        m_destImage = m_orgImage;
        return;
    }

    // -- Applying Edge effect -----------------------------------------------

    register long i = 0;
    int kernelWidth = getOptimalKernelWidth(d->pencil, d->smooth);

    if ((int)m_orgImage.width() < kernelWidth)
    {
        qCWarning(DIGIKAM_DIMG_LOG) << "Image is smaller than radius!";
        return;
    }

    QScopedArrayPointer<double> kernel(new double[kernelWidth * kernelWidth]);

    if (kernel.isNull())
    {
        qCWarning(DIGIKAM_DIMG_LOG) << "Unable to allocate memory!";
        return;
    }

    for (i = 0 ; i < (kernelWidth * kernelWidth) ; ++i)
    {
        kernel[i] = (-1.0);
    }

    kernel[i / 2] = kernelWidth * kernelWidth - 1.0;
    convolveImage(kernelWidth, kernel.data());

    // -- Applying Gaussian blur effect ---------------------------------------

    BlurFilter(this, m_destImage, m_destImage, 80, 85, (int)(d->smooth / 10.0));

    if (!runningFlag())
    {
        return;
    }

    // -- Applying stretch contrast color effect -------------------------------

    StretchFilter stretch(&m_destImage, &m_destImage);
    stretch.startFilterDirectly();
    m_destImage.putImageData(stretch.getTargetImage().bits());

    postProgress(90);

    if (!runningFlag())
    {
        return;
    }

    // -- Inverting image color -----------------------------------------------

    InvertFilter invert(&m_destImage);
    invert.startFilterDirectly();
    m_destImage.putImageData(invert.getTargetImage().bits());

    postProgress(95);

    if (!runningFlag())
    {
        return;
    }

    // -- Convert to neutral black & white ------------------------------------

    MixerContainer settings;
    settings.bMonochrome    = true;
    settings.blackRedGain   = 0.3;
    settings.blackGreenGain = 0.59;
    settings.blackBlueGain  = 0.11;
    MixerFilter mixer(&m_destImage, 0L, settings);
    mixer.startFilterDirectly();
    m_destImage.putImageData(mixer.getTargetImage().bits());

    postProgress(100);

    if (!runningFlag())
    {
        return;
    }
}
status_t AudioStreamOutALSA::setVolume(float left, float right)
{
    return mixer()->setVolume (mHandle->curDev, left, right);
}
Example #19
0
AudioSndio::AudioSndio(bool & _success_ful, Mixer * _mixer) :
	AudioDevice( tLimit<ch_cnt_t>(
	    ConfigManager::inst()->value( "audiosndio", "channels" ).toInt(),
	    DEFAULT_CHANNELS, SURROUND_CHANNELS ), _mixer )
{
	_success_ful = FALSE;

	QString dev = ConfigManager::inst()->value( "audiosndio", "device" );

	if (dev == "")
	{
		m_hdl = sio_open( NULL, SIO_PLAY, 0 );
	}
	else
	{
		m_hdl = sio_open( dev.toAscii().data(), SIO_PLAY, 0 );
	}

	if( m_hdl == NULL )
	{
		printf( "sndio: failed opening audio-device\n" );
		return;
	}

	sio_initpar(&m_par);

	m_par.pchan = channels();
	m_par.bits = 16;
	m_par.le = SIO_LE_NATIVE;
	m_par.rate = sampleRate();
	m_par.round = mixer()->framesPerPeriod();
	m_par.appbufsz = m_par.round * 2;

	struct sio_par reqpar = m_par;

	if (!sio_setpar(m_hdl, &m_par))
	{
		printf( "sndio: sio_setpar failed\n" );
		return;
	}
	if (!sio_getpar(m_hdl, &m_par))
	{
		printf( "sndio: sio_getpar failed\n" );
		return;
	}

	if (reqpar.pchan != m_par.pchan ||
		reqpar.bits != m_par.bits ||
		reqpar.le != m_par.le ||
		(abs(reqpar.rate - m_par.rate) * 100)/reqpar.rate > 2)
	{
		printf( "sndio: returned params not as requested\n" );
		return;
	}

	if (!sio_start(m_hdl))
	{
		printf( "sndio: sio_start failed\n" );
		return;
	}

	_success_ful = TRUE;
}
Example #20
0
//TODO-MB: wouldn't it make more sense to DELETE the time track after 'mix and render'?
void MixAndRender(TrackList *tracks, TrackFactory *trackFactory,
                  double rate, sampleFormat format,
                  double startTime, double endTime,
                  WaveTrack::Holder &uLeft, WaveTrack::Holder &uRight)
{
   uLeft.reset(), uRight.reset();

   // This function was formerly known as "Quick Mix".
   Track *t;
   bool mono = false;   /* flag if output can be mono without loosing anything*/
   bool oneinput = false;  /* flag set to true if there is only one input track
                              (mono or stereo) */

   TrackListIterator iter(tracks);
   SelectedTrackListOfKindIterator usefulIter(Track::Wave, tracks);
   // this only iterates tracks which are relevant to this function, i.e.
   // selected WaveTracks. The tracklist is (confusingly) the list of all
   // tracks in the project

   int numWaves = 0; /* number of wave tracks in the selection */
   int numMono = 0;  /* number of mono, centre-panned wave tracks in selection*/
   t = iter.First();
   while (t) {
      if (t->GetSelected() && t->GetKind() == Track::Wave) {
         numWaves++;
         float pan = ((WaveTrack*)t)->GetPan();
         if (t->GetChannel() == Track::MonoChannel && pan == 0)
            numMono++;
      }
      t = iter.Next();
   }

   if (numMono == numWaves)
      mono = true;

   /* the next loop will do two things at once:
    * 1. build an array of all the wave tracks were are trying to process
    * 2. determine when the set of WaveTracks starts and ends, in case we
    *    need to work out for ourselves when to start and stop rendering.
    */

   double mixStartTime = 0.0;    /* start time of first track to start */
   bool gotstart = false;  // flag indicates we have found a start time
   double mixEndTime = 0.0;   /* end time of last track to end */
   double tstart, tend;    // start and end times for one track.

   WaveTrackConstArray waveArray;
   t = iter.First();

   while (t) {
      if (t->GetSelected() && t->GetKind() == Track::Wave) {
         waveArray.push_back(static_cast<WaveTrack *>(t));
         tstart = t->GetStartTime();
         tend = t->GetEndTime();
         if (tend > mixEndTime)
            mixEndTime = tend;
         // try and get the start time. If the track is empty we will get 0,
         // which is ambiguous because it could just mean the track starts at
         // the beginning of the project, as well as empty track. The give-away
         // is that an empty track also ends at zero.

         if (tstart != tend) {
            // we don't get empty tracks here
            if (!gotstart) {
               // no previous start, use this one unconditionally
               mixStartTime = tstart;
               gotstart = true;
            } else if (tstart < mixStartTime)
               mixStartTime = tstart;  // have a start, only make it smaller
         }  // end if start and end are different
      }  // end if track is a selected WaveTrack.
      /** @TODO: could we not use a SelectedTrackListOfKindIterator here? */
      t = iter.Next();
   }

   /* create the destination track (NEW track) */
   if ((numWaves == 1) || ((numWaves == 2) && (usefulIter.First()->GetLink() != NULL)))
      oneinput = true;
   // only one input track (either 1 mono or one linked stereo pair)

   auto mixLeft = trackFactory->NewWaveTrack(format, rate);
   if (oneinput)
      mixLeft->SetName(usefulIter.First()->GetName()); /* set name of output track to be the same as the sole input track */
   else
      mixLeft->SetName(_("Mix"));
   mixLeft->SetOffset(mixStartTime);
   decltype(mixLeft) mixRight{};
   if (mono) {
      mixLeft->SetChannel(Track::MonoChannel);
   }
   else {
      mixRight = trackFactory->NewWaveTrack(format, rate);
      if (oneinput) {
         if (usefulIter.First()->GetLink() != NULL)   // we have linked track
            mixLeft->SetName(usefulIter.First()->GetLink()->GetName()); /* set name to match input track's right channel!*/
         else
            mixLeft->SetName(usefulIter.First()->GetName());   /* set name to that of sole input channel */
      }
      else
         mixRight->SetName(_("Mix"));
      mixLeft->SetChannel(Track::LeftChannel);
      mixRight->SetChannel(Track::RightChannel);
      mixRight->SetOffset(mixStartTime);
      mixLeft->SetLinked(true);
   }



   int maxBlockLen = mixLeft->GetIdealBlockSize();

   // If the caller didn't specify a time range, use the whole range in which
   // any input track had clips in it.
   if (startTime == endTime) {
      startTime = mixStartTime;
      endTime = mixEndTime;
   }

   Mixer mixer(waveArray,
      Mixer::WarpOptions(tracks->GetTimeTrack()),
      startTime, endTime, mono ? 1 : 2, maxBlockLen, false,
      rate, format);

   ::wxSafeYield();

   int updateResult = eProgressSuccess;
   {
      ProgressDialog progress(_("Mix and Render"),
         _("Mixing and rendering tracks"));

      while (updateResult == eProgressSuccess) {
         sampleCount blockLen = mixer.Process(maxBlockLen);

         if (blockLen == 0)
            break;

         if (mono) {
            samplePtr buffer = mixer.GetBuffer();
            mixLeft->Append(buffer, format, blockLen);
         }
         else {
            samplePtr buffer;
            buffer = mixer.GetBuffer(0);
            mixLeft->Append(buffer, format, blockLen);
            buffer = mixer.GetBuffer(1);
            mixRight->Append(buffer, format, blockLen);
         }

         updateResult = progress.Update(mixer.MixGetCurrentTime() - startTime, endTime - startTime);
      }
   }

   mixLeft->Flush();
   if (!mono)
      mixRight->Flush();
   if (updateResult == eProgressCancelled || updateResult == eProgressFailed)
   {
      return;
   }
   else {
      uLeft = std::move(mixLeft),
         uRight = std::move(mixRight);
#if 0
   int elapsedMS = wxGetElapsedTime();
   double elapsedTime = elapsedMS * 0.001;
   double maxTracks = totalTime / (elapsedTime / numWaves);

   // Note: these shouldn't be translated - they're for debugging
   // and profiling only.
   printf("      Tracks: %d\n", numWaves);
   printf("  Mix length: %f sec\n", totalTime);
   printf("Elapsed time: %f sec\n", elapsedTime);
   printf("Max number of tracks to mix in real time: %f\n", maxTracks);
#endif
   }
}
Example #21
0
AudioOss::AudioOss( bool & _success_ful, Mixer*  _mixer ) :
	AudioDevice( tLimit<ch_cnt_t>(
		ConfigManager::inst()->value( "audiooss", "channels" ).toInt(),
					DEFAULT_CHANNELS, SURROUND_CHANNELS ),
								_mixer ),
	m_convertEndian( false )
{
	_success_ful = false;

	m_audioFD = open( probeDevice().toLatin1().constData(), O_WRONLY, 0 );

	if( m_audioFD == -1 )
	{
		printf( "AudioOss: failed opening audio-device\n" );
		return;
	}


	// Make the file descriptor use blocking writes with fcntl()
	if ( fcntl( m_audioFD, F_SETFL, fcntl( m_audioFD, F_GETFL ) &
							~O_NONBLOCK ) < 0 )
	{
		printf( "could not set audio blocking mode\n" );
		return;
	}

	// set FD_CLOEXEC flag for file descriptor so forked processes
	// do not inherit it
	fcntl( m_audioFD, F_SETFD, fcntl( m_audioFD, F_GETFD ) | FD_CLOEXEC );

	int frag_spec;
	for( frag_spec = 0; static_cast<int>( 0x01 << frag_spec ) <
		mixer()->framesPerPeriod() * channels() *
							BYTES_PER_INT_SAMPLE;
		++frag_spec )
	{
	}

	frag_spec |= 0x00020000;	// two fragments, for low latency

	if ( ioctl( m_audioFD, SNDCTL_DSP_SETFRAGMENT, &frag_spec ) < 0 )
	{
		perror( "SNDCTL_DSP_SETFRAGMENT" );
		printf( "Warning: Couldn't set audio fragment size\n" );
	}

	unsigned int value;
	// Get a list of supported hardware formats
	if ( ioctl( m_audioFD, SNDCTL_DSP_GETFMTS, &value ) < 0 )
	{
		perror( "SNDCTL_DSP_GETFMTS" );
		printf( "Couldn't get audio format list\n" );
		return;
	}

	// Set the audio format
	if( value & AFMT_S16_LE )
	{
		value = AFMT_S16_LE;
	}
	else if( value & AFMT_S16_BE )
	{
		value = AFMT_S16_BE;
	}
	else
	{
		printf(" Soundcard doesn't support signed 16-bit-data\n");
	}
	if ( ioctl( m_audioFD, SNDCTL_DSP_SETFMT, &value ) < 0 )
	{
		perror( "SNDCTL_DSP_SETFMT" );
		printf( "Couldn't set audio format\n" );
		return;
	}
	if( ( isLittleEndian() && ( value == AFMT_S16_BE ) ) ||
			( !isLittleEndian() && ( value == AFMT_S16_LE ) ) )
	{
		m_convertEndian = true;
	}

	// Set the number of channels of output
	value = channels();
	if ( ioctl( m_audioFD, SNDCTL_DSP_CHANNELS, &value ) < 0 )
	{
		perror( "SNDCTL_DSP_CHANNELS" );
		printf( "Cannot set the number of channels\n" );
		return;
	}
	if( value != channels() )
	{
		printf( "Couldn't set number of channels\n" );
		return;
	}

	// Set the DSP frequency
	value = sampleRate();
	if ( ioctl( m_audioFD, SNDCTL_DSP_SPEED, &value ) < 0 )
	{
		perror( "SNDCTL_DSP_SPEED" );
		printf( "Couldn't set audio frequency\n" );
		return;
	}
	if( value != sampleRate() )
	{
		value = mixer()->baseSampleRate();
		if ( ioctl( m_audioFD, SNDCTL_DSP_SPEED, &value ) < 0 )
		{
			perror( "SNDCTL_DSP_SPEED" );
			printf( "Couldn't set audio frequency\n" );
			return;
		}
		setSampleRate( value );
	}

	_success_ful = true;
}
Example #22
0
AudioPortAudio::AudioPortAudio( bool & _success_ful, Mixer * _mixer ) :
	AudioDevice( tLimit<ch_cnt_t>(
		ConfigManager::inst()->value( "audioportaudio", "channels" ).toInt(),
					DEFAULT_CHANNELS, SURROUND_CHANNELS ),
								_mixer ),
	m_paStream( NULL ),
	m_wasPAInitError( false ),
	m_outBuf( new surroundSampleFrame[mixer()->framesPerPeriod()] ),
	m_outBufPos( 0 ),
	m_stopSemaphore( 1 )
{
	_success_ful = false;

	m_outBufSize = mixer()->framesPerPeriod();

	PaError err = Pa_Initialize();
	
	if( err != paNoError ) {
		printf( "Couldn't initialize PortAudio: %s\n", Pa_GetErrorText( err ) );
		m_wasPAInitError = true;
		return;
	}

	if( Pa_GetDeviceCount() <= 0 )
	{
		return;
	}
	
	const QString& backend = ConfigManager::inst()->value( "audioportaudio", "backend" );
	const QString& device = ConfigManager::inst()->value( "audioportaudio", "device" );
		
	PaDeviceIndex inDevIdx = -1;
	PaDeviceIndex outDevIdx = -1;
	const PaDeviceInfo * di;
	for( int i = 0; i < Pa_GetDeviceCount(); ++i )
	{
		di = Pa_GetDeviceInfo( i );
		if( di->name == device &&
			Pa_GetHostApiInfo( di->hostApi )->name == backend )
		{
			inDevIdx = i;
			outDevIdx = i;
		}
	}

	if( inDevIdx < 0 )
	{
		inDevIdx = Pa_GetDefaultInputDevice();
	}
	
	if( outDevIdx < 0 )
	{
		outDevIdx = Pa_GetDefaultOutputDevice();
	}

	if( inDevIdx < 0 || outDevIdx < 0 )
	{
		return;
	}

	double inLatency = 0;//(double)mixer()->framesPerPeriod() / (double)sampleRate();
	double outLatency = 0;//(double)mixer()->framesPerPeriod() / (double)sampleRate();

	//inLatency = Pa_GetDeviceInfo( inDevIdx )->defaultLowInputLatency;
	//outLatency = Pa_GetDeviceInfo( outDevIdx )->defaultLowOutputLatency;
	const int samples = mixer()->framesPerPeriod();
	
	// Configure output parameters.
	m_outputParameters.device = outDevIdx;
	m_outputParameters.channelCount = channels();
	m_outputParameters.sampleFormat = paFloat32; // 32 bit floating point output
	m_outputParameters.suggestedLatency = outLatency;
	m_outputParameters.hostApiSpecificStreamInfo = NULL;
	
	// Configure input parameters.
	m_inputParameters.device = inDevIdx;
	m_inputParameters.channelCount = DEFAULT_CHANNELS;
	m_inputParameters.sampleFormat = paFloat32; // 32 bit floating point input
	m_inputParameters.suggestedLatency = inLatency;
	m_inputParameters.hostApiSpecificStreamInfo = NULL;
	
	// Open an audio I/O stream. 
	err = Pa_OpenStream(
			&m_paStream,
			supportsCapture() ? &m_inputParameters : NULL,	// The input parameter
			&m_outputParameters,	// The outputparameter
			sampleRate(),
			samples,
			paNoFlag,		// Don't use any flags
			_process_callback, 	// our callback function
			this );

	if( err == paInvalidDevice && sampleRate() < 48000 )
	{
		printf("Pa_OpenStream() failed with 44,1 KHz, trying again with 48 KHz\n");
		// some backends or drivers do not allow 32 bit floating point data
		// with a samplerate of 44100 Hz
		setSampleRate( 48000 );
		err = Pa_OpenStream(
				&m_paStream,
				supportsCapture() ? &m_inputParameters : NULL,	// The input parameter
				&m_outputParameters,	// The outputparameter
				sampleRate(),
				samples,
				paNoFlag,		// Don't use any flags
				_process_callback, 	// our callback function
				this );
	}

	if( err != paNoError )
	{
		printf( "Couldn't open PortAudio: %s\n", Pa_GetErrorText( err ) );
		return;
	}

	printf( "Input device: '%s' backend: '%s'\n", Pa_GetDeviceInfo( inDevIdx )->name, Pa_GetHostApiInfo( Pa_GetDeviceInfo( inDevIdx )->hostApi )->name );
	printf( "Output device: '%s' backend: '%s'\n", Pa_GetDeviceInfo( outDevIdx )->name, Pa_GetHostApiInfo( Pa_GetDeviceInfo( outDevIdx )->hostApi )->name );

	m_stopSemaphore.acquire();

	// TODO: debug Mixer::pushInputFrames()
	//m_supportsCapture = true;

	_success_ful = true;
}
Example #23
0
void AudioAlsa::run()
{
	surroundSampleFrame * temp =
		new surroundSampleFrame[mixer()->framesPerPeriod()];
	int_sample_t * outbuf =
			new int_sample_t[mixer()->framesPerPeriod() *
								channels()];
	int_sample_t * pcmbuf = new int_sample_t[m_periodSize * channels()];

	int outbuf_size = mixer()->framesPerPeriod() * channels();
	int outbuf_pos = 0;
	int pcmbuf_size = m_periodSize * channels();

	bool quit = false;
	while( quit == false )
	{
		int_sample_t * ptr = pcmbuf;
		int len = pcmbuf_size;
		while( len )
		{
			if( outbuf_pos == 0 )
			{
				// frames depend on the sample rate
				const fpp_t frames = getNextBuffer( temp );
				if( !frames )
				{
					quit = true;
					memset( ptr, 0, len
						* sizeof( int_sample_t ) );
					break;
				}
				outbuf_size = frames * channels();

				convertToS16( temp, frames,
						mixer()->masterGain(),
						outbuf,
						m_convertEndian );
			}
			int min_len = qMin( len, outbuf_size - outbuf_pos );
			memcpy( ptr, outbuf + outbuf_pos,
					min_len * sizeof( int_sample_t ) );
			ptr += min_len;
			len -= min_len;
			outbuf_pos += min_len;
			outbuf_pos %= outbuf_size;
		}

		f_cnt_t frames = m_periodSize;
		ptr = pcmbuf;

		while( frames )
		{
			int err = snd_pcm_writei( m_handle, ptr, frames );

			if( err == -EAGAIN )
			{
				continue;
			}

			if( err < 0 )
			{
				if( handleError( err ) < 0 )
				{
					printf( "Write error: %s\n",
							snd_strerror( err ) );
				}
				break;	// skip this buffer
			}
			ptr += err * channels();
			frames -= err;
		}
	}

	delete[] temp;
	delete[] outbuf;
	delete[] pcmbuf;
}
Example #24
0
// Main loop
int main(int argc, char** argv)
{
	// ROS Initialization
	ros::init(argc, argv, "Roomba_Driver");		// creates ROS node
	ros::NodeHandle node;				// creates the node handle
	ros::Rate loop_rate(100); 			// testing rate (Hz)
	
	// ROS subscribers
	ros::Subscriber joy_sub;			// create subscriber to listen to joystick
	joy_sub = node.subscribe("joy",1,joy_callback); // this tells our node what to subscribe to, 1 is buffer size of 1
	ros::Subscriber track_sub = node.subscribe("UAV_Trackee_RelPos", 1, tracking_callback);
	// ROS publishers
/*	
	ros::Publisher pos_pub = node.advertise<geometry_msgs::Vector3>("position",1);
	ros::Publisher yaw_pub = node.advertise<std_msgs::Float32>("yaw",1);
	ros::Publisher u_pub = node.advertise<geometry_msgs::Vector3>("control_input",1);
*/
	// ROS Service client
	ros::ServiceClient client = node.serviceClient<irobot_create_2_1::Tank>("tank");

	// Initialize service
	irobot_create_2_1::Tank srv;

	// loop until time or ros not ok
	while(ros::ok())
	{
		ros::spinOnce();	// Receive callbacks	
		merge_new_msgs();   	// Merge joysticks
		
		if(joy_a) // check error in x
			{
			merge_new_msgs();
			output = mixer(tag_y,0.0);
			srv.request.left = output.x;;
			srv.request.right= output.y;
			srv.request.clear= 1;
			client.call(srv);
			
			ROS_INFO("Auto Roomba Track x: %f" ,output.x);
			ros::spinOnce();
			loop_rate.sleep();
			}
/*
		if(joy_b) // Stop when B is pressed
			start_flag = false;

		if(start_flag) // If A has been pressed, run main loop
				{
*/
else{
			output = mixer(joy_x, joy_y);
			
			// set srv values
			srv.request.left = output.x;
			srv.request.right= output.y;
			srv.request.clear= 1;
			// send out value to robot
			if(client.call(srv))
			{
				//ROS_INFO("Sending stuff");
				ROS_INFO("Roomba Joy %f %f",output.x,output.y);
				//ROS_INFO("service %d %d",srv.request.left,srv.request.right);
				if (srv.response.success)
					{//ROS_INFO("Response");
}
				else
					{ROS_INFO("No Response");}
			}
			else
				ROS_INFO("NOT Sending stuff");
	}

}//rosok

}//main