Example #1
0
void Parser::Resample()
{
    int got_frame;

    int idxFrame;
    int idxBuff;

    bool isExtAAC = false;
    if (cdc_ctx_in->codec_id == AV_CODEC_ID_AAC)
        isExtAAC = sampleFormatIn == (int)AVSampleFormat::AV_SAMPLE_FMT_FLTP;

    try
    {
        try
        {
            if (nbSamplesIn > 0)
            {
                if (isExtAAC)
                {
                    frame_in->nb_samples = 2048;
                    frame_in->channels = cdc_ctx_in->channels;
                }
                else
                {
                    frame_in->nb_samples = nbSamplesIn;
                    frame_in->channels = nbChannelsIn;
                }
                frame_in->format = sampleFormatIn;
                frame_in->sample_rate = sampleRateIn;
                frame_in->channel_layout = channelLayoutIn;

                if (av_frame_get_buffer(frame_in, 1) < 0)
                    throw ResampleException() << errno_code(MIR_ERR_BUFFER_ALLOC_IN);

                if (isExtAAC)
                    frame_in->nb_samples = nbSamplesIn;
            }
            else
                throw ResampleException() << errno_code(MIR_ERR_BUFFER_ALLOC_NULL);
        }
        catch(SignalException& err)
        {
            throw ExceptionClass("parser", "Resample", "Segmentation error");
        }
        catch(ResampleException& err)
        {
            throw;
        }

/**
        try
        {
            frame_out->nb_samples = cdc_ctx_out->frame_size;
            frame_out->format = cdc_ctx_out->sample_fmt;
            frame_out->sample_rate = sampleRate;
            frame_out->channel_layout = av_get_default_channel_layout(nbChannel);

            if (av_frame_get_buffer(frame_out, 1) < 0)
                throw ResampleException() << errno_code(MIR_ERR_BUFFER_ALLOC_OUT);
        }
        catch(ResampleException& err)
        {
            throw;
        }
/**/

        for (idxFrame = 0; idxFrame < (int)this->bufFrames.size(); idxFrame++)
        {
            try
            {
                vetAux = bufFrames[idxFrame];

                //!< carregando dados no frame de entrada
                try
                {
                    nbBuffers = av_sample_fmt_is_planar((AVSampleFormat)frame_in->format) ? frame_in->channels : 1;
                    if ((int)vetAux.size() != nbBuffers)
                        throw FifoException() << errno_code(MIR_ERR_FIFO_DATA1);

                    for (idxBuff = 0; idxBuff < (int)vetAux.size(); idxBuff++)
                    {
                        if ((int)vetAux[idxBuff].size() > frame_in->linesize[0])
                            throw FifoException() << errno_code(MIR_ERR_FIFO_DATA2);

                        try
                        {
                            memcpy(frame_in->data[idxBuff], vetAux[idxBuff].data(), frame_in->linesize[0]);
                        }
                        catch(SignalException& err)
                        {
                            throw ExceptionClass("parser", "Resample", err.what());
                        }
                    }

                    for (int idxBuff = 0; idxBuff < (int)vetAux.size(); idxBuff++)
                        if (vetAux[idxBuff].size() > 0)
                            vetAux[idxBuff].clear();
                    if (vetAux.size() > 0)
                        vetAux.clear();
                }
                catch (ExceptionClass& err)
                {
                    throw;
                }
                catch (FifoException& err)
                {
                    throw;
                }
                catch (...)
                {
                    throw FifoException() << errno_code(MIR_ERR_FIFO_DATA3);
                }

                //!< convertendo dados
                if (swr_convert(swr_ctx, (uint8_t**)&frame_out->data, frame_out->nb_samples,
                                 (const uint8_t**)&frame_in->data, frame_in->nb_samples) >= 0)
                {
                    got_frame = 0;
                    av_init_packet(&pkt_out);
                    pkt_out.data = NULL;
                    pkt_out.size = 0;

                    if (avcodec_encode_audio2(cdc_ctx_out, &pkt_out, frame_out, &got_frame) >= 0)
                        EndResample();
                    else
                    {
                        av_free_packet(&pkt_out);
                        throw ResampleException() << errno_code(MIR_ERR_ENCODE);
                    }

                    av_free_packet(&pkt_out);
                }
                else
                    throw ResampleException() << errno_code(MIR_ERR_RESAMPLE);
            }
            catch(ExceptionClass& err)
            {
                objLog->mr_printf(MR_LOG_ERROR, idRadio, "%s\n", err.what());
            }
            catch(FifoException& err)
            {
                char aux[200];

                switch(*boost::get_error_info<errno_code>(err))
                {
                    case MIR_ERR_FIFO_DATA1:
                        sprintf(aux, "Error (%d) : vetAux.size = %d    nbBuffers = %d\n", MIR_ERR_FIFO_DATA1,
                                (int)vetAux.size(), nbBuffers);
                        break;
                    case MIR_ERR_FIFO_DATA2:
/**
                        sprintf(aux, "Error (%d) : vetAux[idxBuff].size = %d    linesize = %d\n", MIR_ERR_FIFO_DATA2,
                                (int)vetAux[idxBuff].size(), frame_in->linesize[0]);
/**/
                        sprintf(aux, "Error (%d) : vetAux[idxBuff].size = %d    linesize = %d    channels = %d"
                                "    channelsLayout = %d    format = %d    nb_samples = %d\n",
                                MIR_ERR_FIFO_DATA2,
                                (int)vetAux[idxBuff].size(),
                                frame_in->linesize[0],
                                frame_in->channels,
                                frame_in->channel_layout,
                                frame_in->format,
                                frame_in->nb_samples);
/**/
                        break;
                    case MIR_ERR_FIFO_DATA3:
                        sprintf(aux, "Error (%d) : General Frame allocation error\n", MIR_ERR_FIFO_DATA3);
                        break;
                    default :
                        break;
                }

                objLog->mr_printf(MR_LOG_ERROR, idRadio, aux);

                for (int idxBuff = 0; idxBuff < (int)vetAux.size(); idxBuff++)
                    if (vetAux[idxBuff].size() > 0)
                        vetAux[idxBuff].clear();
                if (vetAux.size() > 0)
                    vetAux.clear();
            }
            catch(ResampleException& err)
            {
                objLog->mr_printf(MR_LOG_ERROR, idRadio, "Frame Resample Exception : %d\n", *boost::get_error_info<errno_code>(err));
            }
        }

        av_frame_unref(frame_in);
//        av_frame_unref(frame_out);

        for (int idxFrame = 0; idxFrame < (int)this->bufFrames.size(); idxFrame++)
        {
            for (int idxBuff = 0; idxBuff < (int)bufFrames[idxFrame].size(); idxBuff++)
                if (bufFrames[idxFrame][idxBuff].size() > 0)
                    bufFrames[idxFrame][idxBuff].clear();
            if (bufFrames[idxFrame].size() > 0)
                bufFrames[idxFrame].clear();
        }
        if (bufFrames.size() > 0)
            bufFrames.clear();
    }
    catch (SignalException& err)
    {
        if (frame_in)
        {
            av_frame_free(&frame_in);
            frame_in = NULL;
        }

        if (frame_out)
        {
            av_frame_free(&frame_out);
            frame_out = NULL;
        }

        for (int idxBuff = 0; idxBuff < (int)vetAux.size(); idxBuff++)
            if (vetAux[idxBuff].size() > 0)
                vetAux[idxBuff].clear();
        if (vetAux.size() > 0)
            vetAux.clear();

        for (int idxFrame = 0; idxFrame < (int)this->bufFrames.size(); idxFrame++)
        {
            for (int idxBuff = 0; idxBuff < (int)bufFrames[idxFrame].size(); idxBuff++)
                if (bufFrames[idxFrame][idxBuff].size() > 0)
                    bufFrames[idxFrame][idxBuff].clear();
            if (bufFrames[idxFrame].size() > 0)
                bufFrames[idxFrame].clear();
        }
        if (bufFrames.size() > 0)
            bufFrames.clear();

        throw;
    }
    catch(...)
    {
        if (frame_in)
        {
            av_frame_free(&frame_in);
            frame_in = NULL;
        }

        if (frame_out)
        {
            av_frame_free(&frame_out);
            frame_out = NULL;
        }

        for (int idxBuff = 0; idxBuff < (int)vetAux.size(); idxBuff++)
            if (vetAux[idxBuff].size() > 0)
                vetAux[idxBuff].clear();
        if (vetAux.size() > 0)
            vetAux.clear();

        for (int idxFrame = 0; idxFrame < (int)this->bufFrames.size(); idxFrame++)
        {
            for (int idxBuff = 0; idxBuff < (int)bufFrames[idxFrame].size(); idxBuff++)
                if (bufFrames[idxFrame][idxBuff].size() > 0)
                    bufFrames[idxFrame][idxBuff].clear();
            if (bufFrames[idxFrame].size() > 0)
                bufFrames[idxFrame].clear();
        }
        if (bufFrames.size() > 0)
            bufFrames.clear();

        throw;
    }
}
Example #2
0
/* Function for resampling  N input maps into 1 output map.
 * Assumes a map "clone.map" and N "input.map"s present. Checks on
 * options for percentage and maximum value. 
 * Determines type and characteristics of output map.
 * Returns nothing, exits with 1 in case of error.
 */
int main(int argc,		/* number of arguments */
	char *argv[])		/* list of arguments */
{
     	MAP 	*clone, *out, *tmp, **in;
     	char 	*outputName, *cloneName;	
     	int 	c, borderval;	
     	size_t  nrMaps,i;
	REAL8 	X0, Y0, cellSize, angleIn, angleOut;
	size_t 	nrRows, nrCols;
	CSF_PT 	projection;
	CSF_CR  cellRepr;
	CSF_VS  valueScale;
	double 	percent = 0, errFactor = 2.5, resampleN = 0.0;
	BOOL	aligned = TRUE;
	BOOL    keepInputMinMax = FALSE;
	REAL8	minAllInput=0, maxAllInput=0;
	BOOL	onlyReal4 = TRUE, contract = FALSE;
	BOOL	onlyUint1 = TRUE;

	if(InstallArgs(argc, argv,"axmp$r$c#b#e$RBCk", "resample", __DATE__))
		exit(1);

     	while((c = GetOpt()) != 0)
     	{
     	    switch(c)
     	    {
     	    	case 'b': opB = TRUE;
     	    		borderval = *((int *) OptArg);
     	    		break;
     	    	case 'B': opB = TRUE;
     	    		borderval = 0;
     	    		break;
     	    	case 'C': opMV = TRUE;
     	    		borderval = 0;
     	    		break;
     	    	case 'c': opMV = TRUE;
     	    		borderval = *((int *) OptArg);
     	    		break;
     	    	case 'a':contract = TRUE;
     	    		break;
     	    	case 'x':contract = FALSE;
     	    		break;
     	    	case 'm':opMax = 1;
     	    		break;
     	    	case 'p':opPer = 1;
     	    		percent = *((double*) OptArg);
     	    		if(percent < 0 || 100 < percent)
     	    		{
     	    			Error("illegal percentage");
     	    			exit(1);
     	    		}
     	    		break;
     	    	case 'R':opR = 1;
     	    		resampleN = 1;
     	    		break;
     	    	case 'r':opR = 1;
     	    		resampleN = *((double*) OptArg);
     	    		break;
     	    	case 'e':optionAcc = 1;
     	    		errFactor = *((double*) OptArg);
     	    		break;
     	    	case 'k': keepInputMinMax = TRUE;
     	    		break;
     	    }
     	}

	argv = ArgArguments(&argc);
	if (AppArgCountCheck(argc,3,-1,USAGE))
		exit(1);

	outputName = argv[argc-1];
  	nrMaps  = argc-2;

	/* Read the desired specifics out of the clone map 
	 * or use first input as clone map
	 */
	cloneName = NO_CLONE_NEEDED ? argv[1] : NULL;
	if ( (clone = AppOpenClone(&cloneName,cloneName)) == NULL)
		exit(1);

	/* Determine the valueScale out of 1st input map */
	tmp = Mopen(argv[1], M_READ);
	if(tmp == NULL)
		MperrorExit(argv[1], 1);

	/* all input maps have same value scale */
	valueScale = RgetValueScale(tmp);
	if(valueScale == VS_LDD && !opMV)
	{
		Error("can not do this type of resampling on map '%s' with type ldd", argv[1]);
		exit(1);
	}
	/* adjust old ones */
	if(valueScale == VS_CLASSIFIED)
		valueScale = VS_ORDINAL;
	if(valueScale == VS_CONTINUOUS)
		valueScale = VS_SCALAR;

	/* get location attributes of clone or of 1st input map */
	projection = MgetProjection(clone);
	nrRows = RgetNrRows(clone);
	nrCols = RgetNrCols(clone);
	X0 = RgetX0(clone);
	Y0 = RgetY0(clone);
	cellRepr = RgetCellRepr(clone);
	angleOut = RgetAngle(clone); 

	/* resample option -> cell size(inputmap) * factor 
	 * Number of rows and columns are divided by resample
	 * factor.
	 */
	if(opR == 1)
	{
		/* setting for unit */
		if(!appUnitTrue)
		{
			cellSize = resampleN;
			resampleN /= (double) RgetCellSize(tmp);
		}
		else
			cellSize = RgetCellSize(tmp) * resampleN;
		if(contract)
		{
			nrRows = floor((double) nrRows / 
					(double) resampleN);
			nrCols = floor((double) nrCols / 
					(double) resampleN);

			/* Prevent an illegal map */
			if(nrRows == 0)
				nrRows = 1;
			if(nrCols == 0)
				nrCols = 1;
		}
		else
		{
			nrRows = ceil((double) nrRows / 
					(double) resampleN);
			nrCols = ceil((double) nrCols / 
					(double) resampleN);
		}
	}
	else
		cellSize = RgetCellSize(clone);

	/* Allocate memory for the input map pointers */
	in = (MAP **)ChkMalloc(sizeof(MAP *) * nrMaps);
	if(in == NULL)
	{
		AppEnd();
		exit(1);
	}

	/* Read all input maps with desired cell representation */
	for(i = 0; i < nrMaps; i++)
	{
		REAL8	tmpMin, tmpMax;

		tmp = Mopen(argv[1 + i], M_READ);
		angleIn = RgetAngle(tmp);
		if(angleIn != 0)
			aligned = FALSE;
		if(tmp == NULL)
			MperrorExit(argv[1 + i], 1);

		if(!RvalueScaleIs(tmp, valueScale))
		{
			Error("%s has illegal data type: '%s'\n",
				argv[1 + i], RstrValueScale(valueScale));
			exit(1);
		}

		in[i] = tmp;

		/* Determine which cell representation should be used */
		onlyReal4 = RgetCellRepr(in[i]) == CR_REAL4;
		onlyUint1 = RgetCellRepr(in[i]) == CR_UINT1;


		RuseAs(in[i], CR_REAL8);
		RgetMinVal(tmp, &tmpMin);
		RgetMaxVal(tmp, &tmpMax);
		if (i==0)
		 {minAllInput = tmpMin; maxAllInput = tmpMax; }
		minAllInput = MIN(minAllInput,tmpMin);
		maxAllInput = MAX(maxAllInput,tmpMax);

		if(AppIsClassified(valueScale))
			RuseAs(in[i], CR_INT4);
		else
			RuseAs(in[i], CR_REAL8);
	}

	if(opB == 1 || opMV == 1)
	{
		if(CheckInputMaps(in, nrMaps, projection, angleIn, cellSize))
		{
			Error("");
			FreeMaps(in, nrMaps);
			exit(1);
		}

		if(opB == 1)
		{
			if(SmallestFittingRectangle(&X0, &Y0, &nrRows,
			  &nrCols, in, borderval, nrMaps,
			  cellSize, angleIn, projection, contract))
			{
				FreeMaps(in, nrMaps);
				AppEnd();
				exit(1);
			}
		}
		else
		{
		  	if(SmallestNonMVRect(&X0, &Y0, &nrRows, &nrCols, in,
		  	borderval, nrMaps, valueScale, cellSize,
		  	angleIn, projection, contract))
			{	
				FreeMaps(in, nrMaps);
				AppEnd();
				exit(1);
			}
		}
	}

	/* Create output map with suitable cell representation */ 
	/* NOTE ! Create map with smallest representation possible */
	out = Rcreate(outputName, nrRows, nrCols, 
	               AppIsClassified(valueScale) ?
		               (onlyUint1 ? CR_UINT1 : CR_INT4) :
		               (onlyReal4 ? CR_REAL4 : CR_REAL8),
		               valueScale, projection, X0, Y0, 
		               angleOut, cellSize);
	if(out == NULL)
	{
		FreeMaps(in, nrMaps);
		Error("can not create output map '%s': %s", 
		      argv[1], MstrError());
		exit(1);
	}
	RuseAs(out, AppIsClassified(valueScale) ? CR_INT4 : CR_REAL8);

	if(angleOut != 0)
		aligned = FALSE;


	/* determine raster size according wanted accuracy */
	if(opB != 1 && opMV != 1)
	{
		if(DetRasterSize(out, in, nrMaps, errFactor))
		{
			Error("Illegal cell size\n");
			exit(1);
		}
	}
	else
		rasterSize = 1;

	if(nrMaps > 1 && percent > 0)
		AppProgress("rasterSize: %d\n", rasterSize);
	else
		AppProgress("No raster used\n");

	/* Call function */
	if(AppIsClassified(valueScale))
	{	/* Call resample function for classified maps */

		if(SampleClass(out, in, percent, nrMaps, nrRows, nrCols,
		   aligned, angleOut))
		{	
			EndResample(in, nrMaps, out);
			exit(1);	/* Memory allocation failed */
		}	
	}		
	else
	{	/* Call resample function for continuous maps */
		if(SampleCont(out, in, percent, nrMaps, nrRows, nrCols,
		   aligned, angleOut))
		{	
			EndResample(in, nrMaps, out);
			exit(1);	/* Memory allocation failed */
		}	
	}		

	/* End of call */
	if (keepInputMinMax) {
		RuseAs(out, CR_REAL8);
		RputMinVal(out, &minAllInput);
		RputMaxVal(out, &maxAllInput);
	}
	EndResample(in, nrMaps, out);
	
	exit(0);  			/* Successful exit */
	return 0; 			/* Never reached */
} /* main */