コード例 #1
0
ファイル: wal.c プロジェクト: ekkotron/actordb_driver
int sqlite3WalReadFrame(Wal *pWal, u32 iRead, int nOut, u8 *pOut)
{
	if (readframe(pWal,iRead,nOut,pOut) == SQLITE_DEFAULT_PAGE_SIZE)
		return SQLITE_OK;
	else
		return SQLITE_ERROR;
}
コード例 #2
0
ファイル: ImageProc.c プロジェクト: hai046/simplewebcam
int readframeonce(void) {
	for (;;) {
		fd_set fds;
		struct timeval tv;
		int r;

		FD_ZERO(&fds);
		FD_SET(fd, &fds);

		tv.tv_sec = 2;
		tv.tv_usec = 0;

		r = select(fd + 1, &fds, NULL, NULL, &tv);

		if (-1 == r) {
			if (EINTR == errno)
				continue;

			return errnoexit("select");
		}

		if (0 == r) {
			LOGE("select timeout");
			return ERROR_LOCAL;

		}

		if (readframe() == 1)
			break;

	}

	return SUCCESS_LOCAL;

}
コード例 #3
0
MainWindow::MainWindow(QWidget *parent)
    : QMainWindow(parent),
      ui(new Ui::MainWindow)
{
    /*****生成主窗口UI*****/
    ui->setupUi(this);

    /*****声明全局变量*****/
    saveCount = 1;//Save calib images start with 1
    scanSN = -1;
    isConfigured = false;
    isProjectorOpened = true;

    /****生成计时器并连接*****/
    timer = new QTimer(this);
    connect(timer, SIGNAL(timeout()), this, SLOT(readframe()));

    /****声明相机****/
    usebc = false;
    DHC = new DaHengCamera(this);

    /****生成对焦辅助窗口****/
    fa = new FocusAssistant();
    showFocus = false;

    /*****生成OpenGL窗口并加载*****/
    displayModel = new GLWidget(ui->displayWidget);
    ui->displayLayout->addWidget(displayModel);

    /*****生成设置窗口并输出默认设置*****/
    setDialog = new Set(this);//Initialize the set dialog
    getSetInfo();

    /*****获取屏幕尺寸信息*****/
    getScreenGeometry();//Get mian screen and projector screen geometry
    QDesktopWidget* desktopWidget = QApplication::desktop();
    QRect projRect = desktopWidget->screenGeometry(1);//1 represent projector
    int xOffSet = (projRect.width() - scanWidth)/2 + screenWidth;
    int yOffSet = (projRect.height() - scanHeight)/2;

    /*****初始化投影窗口*****/
    pj = new Projector(NULL, scanWidth, scanHeight, projectorWidth, projectorHeight, xOffSet, yOffSet);//Initialize the projector
    pj->move(screenWidth,0);//make the window displayed by the projector
    pj->showFullScreen();

    /*****建立连接*****/
    createConnections();

    /*****初始化圆点探测*****/
    blob = new BlobDetector();
}
コード例 #4
0
int decode(void *userdata)
{
	struct decodedata *ddata;
	int isdecoded;
	uint8_t *rgbdata;
	int rgblinesize;
	int retval;

	ddata = userdata;

	isdecoded = 0;

	do {
		if ((retval = readframe(ddata->av->s, ddata->av->vcodecc,
			ddata->av->vstreamid, ddata->av->frame,
			&(isdecoded))) < 0)
			return (-1);

		if (retval > 0)
			return 0;
	} while (!isdecoded);

	if (frametorgb(ddata->av->frame, ddata->img->w, ddata->img->h,
		&rgbdata, &rgblinesize) < 0)
		return (-1);
	
	if (nd_pstrylock(0)) {
		rgbdatatoimg(rgbdata, rgblinesize, ddata->img);
		
		if (nd_psunlock(0) < 0) {
			fprintf(stderr, nd_geterrormessage());
			return (-1);
		}
	}

	free(rgbdata);

	if (pbnexttimestamp(ddata->pbs) < 0)
		return (-1);

	return 0;
}
コード例 #5
0
int main(int argc, char* argv[])
{
    //--- File IO ----
    FILE* inp;
    FILE* outp;
    char inname[500];
    char outname[500];

    /* Runtime statistics */
    double        rate;
    double        rateRCU;
    unsigned long totalbits = 0;
    unsigned long totalBitsRCU = 0;
    unsigned long totalsmpls =0;

    int32_t   bottleneck = 39;
    int16_t   frameSize = 30;           /* ms */
    int16_t   codingMode = 1;
    int16_t   shortdata[FRAMESAMPLES_SWB_10ms];
    int16_t   decoded[MAX_FRAMESAMPLES_SWB];
    //uint16_t  streamdata[1000];
    int16_t   speechType[1];
    int16_t   payloadLimit;
    int32_t   rateLimit;
    ISACStruct*   ISAC_main_inst;

    int16_t   stream_len = 0;
    int16_t   declen = 0;
    int16_t   err;
    int16_t   cur_framesmpls;
    int           endfile;
#ifdef WIN32
    double        length_file;
    double        runtime;
    char          outDrive[10];
    char          outPath[500];
    char          outPrefix[500];
    char          outSuffix[500];
    char          bitrateFileName[500];
    FILE*         bitrateFile;
    double        starttime;
    double        rateLB = 0;
    double        rateUB = 0;
#endif
    FILE*         histFile;
    FILE*         averageFile;
    int           sampFreqKHz;
    int           samplesIn10Ms;
    int16_t   maxStreamLen = 0;
    char          histFileName[500];
    char          averageFileName[500];
    unsigned int  hist[600];
    unsigned int  tmpSumStreamLen = 0;
    unsigned int  packetCntr = 0;
    unsigned int  lostPacketCntr = 0;
    uint8_t  payload[1200];
    uint8_t  payloadRCU[1200];
    uint16_t  packetLossPercent = 0;
    int16_t   rcuStreamLen = 0;
	int onlyEncode;
	int onlyDecode;


    BottleNeckModel packetData;
	packetData.arrival_time  = 0;
	packetData.sample_count  = 0;
	packetData.rtp_number    = 0;
    memset(hist, 0, sizeof(hist));

    /* handling wrong input arguments in the command line */
    if(argc < 5)
    {
		int size;
		WebRtcIsac_AssignSize(&size);

        printf("\n\nWrong number of arguments or flag values.\n\n");

        printf("Usage:\n\n");
        printf("%s infile outfile -bn bottelneck [options] \n\n", argv[0]);
        printf("with:\n");
        printf("-I................... indicates encoding in instantaneous mode.\n");
        printf("-bn bottleneck....... the value of the bottleneck in bit/sec, e.g. 39742,\n");
		printf("                      in instantaneous (channel-independent) mode.\n\n");
        printf("infile............... Normal speech input file\n\n");
        printf("outfile.............. Speech output file\n\n");
        printf("OPTIONS\n");
        printf("-------\n");
        printf("-fs sampFreq......... sampling frequency of codec 16 or 32 (default) kHz.\n");
        printf("-plim payloadLim..... payload limit in bytes,\n");
        printf("                      default is the maximum possible.\n");
        printf("-rlim rateLim........ rate limit in bits/sec, \n");
        printf("                      default is the maimum possible.\n");
        printf("-h file.............. record histogram and *append* to 'file'.\n");
        printf("-ave file............ record average rate of 3 sec intervales and *append* to 'file'.\n");
        printf("-ploss............... packet-loss percentage.\n");
		printf("-enc................. do only encoding and store the bit-stream\n");
		printf("-dec................. the input file is a bit-stream, decode it.\n");

        printf("\n");
        printf("Example usage:\n\n");
        printf("%s speechIn.pcm speechOut.pcm -B 40000 -fs 32 \n\n", argv[0]);

		printf("structure size %d bytes\n", size);

        exit(0);
    }



    /* Get Bottleneck value */
    bottleneck = readParamInt(argc, argv, "-bn", 50000);
    fprintf(stderr,"\nfixed bottleneck rate of %d bits/s\n\n", bottleneck);

    /* Get Input and Output files */
    sscanf(argv[1], "%s", inname);
    sscanf(argv[2], "%s", outname);
    codingMode = readSwitch(argc, argv, "-I");
    sampFreqKHz = (int16_t)readParamInt(argc, argv, "-fs", 32);
    if(readParamString(argc, argv, "-h", histFileName, 500) > 0)
    {
        histFile = fopen(histFileName, "a");
        if(histFile == NULL)
        {
            printf("cannot open hist file %s", histFileName);
            exit(0);
        }
    }
    else
    {
        // NO recording of hitstogram
        histFile = NULL;
    }


    packetLossPercent = readParamInt(argc, argv, "-ploss", 0);

    if(readParamString(argc, argv, "-ave", averageFileName, 500) > 0)
    {
        averageFile = fopen(averageFileName, "a");
        if(averageFile == NULL)
        {
            printf("cannot open file to write rate %s", averageFileName);
            exit(0);
        }
    }
    else
    {
        averageFile = NULL;
    }

	onlyEncode = readSwitch(argc, argv, "-enc");
	onlyDecode = readSwitch(argc, argv, "-dec");


    switch(sampFreqKHz)
    {
    case 16:
        {
            samplesIn10Ms = 160;
            break;
        }
    case 32:
        {
            samplesIn10Ms = 320;
            break;
        }
    default:
        printf("A sampling frequency of %d kHz is not supported,\
valid values are 8 and 16.\n", sampFreqKHz);
        exit(-1);
    }
    payloadLimit = (int16_t)readParamInt(argc, argv, "-plim", 400);
    rateLimit = readParamInt(argc, argv, "-rlim", 106800);

    if ((inp = fopen(inname,"rb")) == NULL) {
        printf("  iSAC: Cannot read file %s.\n", inname);
        exit(1);
    }
    if ((outp = fopen(outname,"wb")) == NULL) {
        printf("  iSAC: Cannot write file %s.\n", outname);
        exit(1);
    }

#ifdef WIN32
    _splitpath(outname, outDrive, outPath, outPrefix, outSuffix);
    _makepath(bitrateFileName, outDrive, outPath, "bitrate", ".txt");

    bitrateFile = fopen(bitrateFileName, "a");
    fprintf(bitrateFile, "%  %%s  \n", inname);
#endif

    printf("\n");
    printf("Input.................... %s\n", inname);
    printf("Output................... %s\n", outname);
    printf("Encoding Mode............ %s\n",
        (codingMode == 1)? "Channel-Independent":"Channel-Adaptive");
    printf("Bottleneck............... %d bits/sec\n", bottleneck);
    printf("Packet-loss Percentage... %d\n", packetLossPercent);
    printf("\n");

#ifdef WIN32
    starttime = clock()/(double)CLOCKS_PER_SEC; /* Runtime statistics */
#endif

    /* Initialize the ISAC and BN structs */
    err = WebRtcIsac_Create(&ISAC_main_inst);

    WebRtcIsac_SetEncSampRate(ISAC_main_inst, sampFreqKHz * 1000);
    WebRtcIsac_SetDecSampRate(ISAC_main_inst, sampFreqKHz >= 32 ? 32000 :
        16000);
    /* Error check */
    if (err < 0) {
        fprintf(stderr,"\n\n Error in create.\n\n");
        exit(EXIT_FAILURE);
    }

    framecnt = 0;
    endfile     = 0;

    /* Initialize encoder and decoder */
    if(WebRtcIsac_EncoderInit(ISAC_main_inst, codingMode) < 0)
    {
        printf("cannot initialize encoder\n");
        return -1;
    }
    if(WebRtcIsac_DecoderInit(ISAC_main_inst) < 0)
    {
        printf("cannot initialize decoder\n");
        return -1;
    }

    //{
    //    int32_t b1, b2;
    //    FILE* fileID = fopen("GetBNTest.txt", "w");
    //    b2 = 32100;
    //    while(b2 <= 52000)
    //    {
    //        WebRtcIsac_Control(ISAC_main_inst, b2, frameSize);
    //        WebRtcIsac_GetUplinkBw(ISAC_main_inst, &b1);
    //        fprintf(fileID, "%5d %5d\n", b2, b1);
    //        b2 += 10;
    //    }
    //}

    if(codingMode == 1)
    {
        if(WebRtcIsac_Control(ISAC_main_inst, bottleneck, frameSize) < 0)
        {
            printf("cannot set bottleneck\n");
            return -1;
        }
    }
    else
    {
        if(WebRtcIsac_ControlBwe(ISAC_main_inst, 15000, 30, 1) < 0)
        {
            printf("cannot configure BWE\n");
            return -1;
        }
    }

    if(WebRtcIsac_SetMaxPayloadSize(ISAC_main_inst, payloadLimit) < 0)
    {
        printf("cannot set maximum payload size %d.\n", payloadLimit);
        return -1;
    }

    if (rateLimit < 106800) {
        if(WebRtcIsac_SetMaxRate(ISAC_main_inst, rateLimit) < 0)
        {
            printf("cannot set the maximum rate %d.\n", rateLimit);
            return -1;
        }
    }

    //=====================================
//#ifdef HAVE_DEBUG_INFO
//    if(setupDebugStruct(&debugInfo) < 0)
//    {
//        exit(1);
//    }
//#endif

    while (endfile == 0)
    {
        fprintf(stderr,"  \rframe = %7li", framecnt);

        //============== Readind from the file and encoding =================
        cur_framesmpls = 0;
        stream_len = 0;


		if(onlyDecode)
		{
			uint8_t auxUW8;
                        size_t auxSizet;
			if(fread(&auxUW8, sizeof(uint8_t), 1, inp) < 1)
			{
				break;
			}
			stream_len = ((uint8_t)auxUW8) << 8;
			if(fread(&auxUW8, sizeof(uint8_t), 1, inp) < 1)
			{
				break;
			}
			stream_len |= (uint16_t)auxUW8;
                        auxSizet = (size_t)stream_len;
                        if(fread(payload, 1, auxSizet, inp) < auxSizet)
			{
				printf("last payload is corrupted\n");
				break;
			}
		}
		else
		{
			while(stream_len == 0)
			{
				// Read 10 ms speech block
				endfile = readframe(shortdata, inp, samplesIn10Ms);
				if(endfile)
				{
					break;
				}
				cur_framesmpls += samplesIn10Ms;

				//-------- iSAC encoding ---------
                                stream_len = WebRtcIsac_Encode(
                                        ISAC_main_inst,
                                        shortdata,
                                        payload);

				if(stream_len < 0)
				{
					// exit if returned with error
					//errType=WebRtcIsac_GetErrorCode(ISAC_main_inst);
					fprintf(stderr,"\nError in encoder\n");
					getchar();
					exit(EXIT_FAILURE);
				}


			}
			//===================================================================
			if(endfile)
			{
				break;
			}

                        rcuStreamLen = WebRtcIsac_GetRedPayload(
                            ISAC_main_inst, payloadRCU);

			get_arrival_time(cur_framesmpls, stream_len, bottleneck, &packetData,
				sampFreqKHz * 1000, sampFreqKHz * 1000);
			if(WebRtcIsac_UpdateBwEstimate(ISAC_main_inst,
                                                       payload,
                                                       stream_len,
                                                       packetData.rtp_number,
                                                       packetData.sample_count,
                                                       packetData.arrival_time)
                           < 0)
			{
				printf(" BWE Error at client\n");
				return -1;
			}
		}

        if(endfile)
        {
            break;
        }

        maxStreamLen = (stream_len > maxStreamLen)? stream_len:maxStreamLen;
        packetCntr++;

        hist[stream_len]++;
        if(averageFile != NULL)
        {
            tmpSumStreamLen += stream_len;
            if(packetCntr == 100)
            {
                // kbps
                fprintf(averageFile, "%8.3f ", (double)tmpSumStreamLen * 8.0 / (30.0 * packetCntr));
                packetCntr = 0;
                tmpSumStreamLen = 0;
            }
        }

		if(onlyEncode)
		{
                  uint8_t auxUW8;
                  auxUW8 = (uint8_t)(((stream_len & 0x7F00) >> 8) & 0xFF);
                  if (fwrite(&auxUW8, sizeof(uint8_t), 1, outp) != 1) {
                    return -1;
                  }

                  auxUW8 = (uint8_t)(stream_len & 0xFF);
                  if (fwrite(&auxUW8, sizeof(uint8_t), 1, outp) != 1) {
                    return -1;
                  }
                  if (fwrite(payload, 1, stream_len,
                             outp) != (size_t)stream_len) {
                    return -1;
                  }
		}
		else
		{

			//======================= iSAC decoding ===========================

			if((rand() % 100) < packetLossPercent)
			{
                                declen = WebRtcIsac_DecodeRcu(
                                    ISAC_main_inst,
                                    payloadRCU,
                                    rcuStreamLen,
                                    decoded,
                                    speechType);
				lostPacketCntr++;
			}
			else
			{
                                declen = WebRtcIsac_Decode(
                                    ISAC_main_inst,
                                    payload,
                                    stream_len,
                                    decoded,
                                    speechType);
                        }
                        if(declen <= 0)
			{
				//errType=WebRtcIsac_GetErrorCode(ISAC_main_inst);
				fprintf(stderr,"\nError in decoder.\n");
				getchar();
				exit(1);
			}

			// Write decoded speech frame to file
                        if (fwrite(decoded, sizeof(int16_t),
                                   declen, outp) != (size_t)declen) {
                          return -1;
                        }
			cur_framesmpls = declen;
		}
        // Update Statistics
        framecnt++;
        totalsmpls += cur_framesmpls;
        if(stream_len > 0)
        {
            totalbits += 8 * stream_len;
        }
        if(rcuStreamLen > 0)
        {
            totalBitsRCU += 8 * rcuStreamLen;
        }
    }
コード例 #6
0
ファイル: kenny.c プロジェクト: abael/WebRTC
int main(int argc, char* argv[])
{

  char inname[100], outname[100],  outbitsname[100], bottleneck_file[100];
  FILE *inp, *outp, *f_bn, *outbits;
  int endfile;

  int i, errtype, h = 0, k, packetLossPercent = 0;
  WebRtc_Word16 CodingMode;
  WebRtc_Word16 bottleneck;
  WebRtc_Word16 framesize = 30;           /* ms */
  int cur_framesmpls, err = 0, lostPackets = 0;

  /* Runtime statistics */
  double starttime, runtime, length_file;

  WebRtc_Word16 stream_len = 0;
  WebRtc_Word16 framecnt, declen = 0;
  WebRtc_Word16 shortdata[FRAMESAMPLES_10ms];
  WebRtc_Word16 decoded[MAX_FRAMESAMPLES];
  WebRtc_UWord16 streamdata[500];
  WebRtc_Word16 speechType[1];
  WebRtc_Word16 prevFrameSize = 1;
  WebRtc_Word16 rateBPS = 0;
  WebRtc_Word16 fixedFL = 0;
  WebRtc_Word16 payloadSize = 0;
  WebRtc_Word32 payloadRate = 0;
  int setControlBWE = 0;
  int readLoss;
  FILE  *plFile = NULL;

  char version_number[20];
  char tmpBit[5] = ".bit";

  double kbps;
  int totalbits =0;
  int totalsmpls =0;
#ifdef _DEBUG
  FILE *fy;
#endif
  WebRtc_Word16 testNum, testCE;

  FILE *fp_gns = NULL;
  int gns = 0;
  int cur_delay = 0;
  char gns_file[100];

  int nbTest = 0;
  WebRtc_Word16 lostFrame;
  float scale = (float)0.7;
  /* only one structure used for ISAC encoder */
  ISACFIX_MainStruct *ISAC_main_inst;

  /* For fault test 10, garbage data */
  FILE *seedfile;
  unsigned int random_seed = (unsigned int) time(NULL);//1196764538

  BottleNeckModel       BN_data;
  f_bn  = NULL;

#ifdef _DEBUG
  fy = fopen("bit_rate.dat", "w");
  fclose(fy);
  fy = fopen("bytes_frames.dat", "w");
  fclose(fy);
#endif

  readLoss = 0;
  packetLossPercent = 0;

  /* Handling wrong input arguments in the command line */
  if ((argc<3) || (argc>21))  {
    printf("\n\nWrong number of arguments or flag values.\n\n");

    printf("\n");
    WebRtcIsacfix_version(version_number);
    printf("iSAC version %s \n\n", version_number);

    printf("Usage:\n\n");
    printf("./kenny.exe [-F num][-I] bottleneck_value infile outfile \n\n");
    printf("with:\n");
    printf("[-I]             :if -I option is specified, the coder will use\n");
    printf("                  an instantaneous Bottleneck value. If not, it\n");
    printf("                  will be an adaptive Bottleneck value.\n\n");
    printf("bottleneck_value :the value of the bottleneck provided either\n");
    printf("                  as a fixed value (e.g. 25000) or\n");
    printf("                  read from a file (e.g. bottleneck.txt)\n\n");
    printf("[-INITRATE num]  :Set a new value for initial rate. Note! Only used"
           " in adaptive mode.\n\n");
    printf("[-FL num]        :Set (initial) frame length in msec. Valid length"
           " are 30 and 60 msec.\n\n");
    printf("[-FIXED_FL]      :Frame length will be fixed to initial value.\n\n");
    printf("[-MAX num]       :Set the limit for the payload size of iSAC"
           " in bytes. \n");
    printf("                  Minimum 100, maximum 400.\n\n");
    printf("[-MAXRATE num]   :Set the maxrate for iSAC in bits per second. \n");
    printf("                  Minimum 32000, maximum 53400.\n\n");
    printf("[-F num]         :if -F option is specified, the test function\n");
    printf("                  will run the iSAC API fault scenario specified"
           " by the\n");
    printf("                  supplied number.\n");
    printf("                  F 1 - Call encoder prior to init encoder call\n");
    printf("                  F 2 - Call decoder prior to init decoder call\n");
    printf("                  F 3 - Call decoder prior to encoder call\n");
    printf("                  F 4 - Call decoder with a too short coded"
           " sequence\n");
    printf("                  F 5 - Call decoder with a too long coded"
           " sequence\n");
    printf("                  F 6 - Call decoder with random bit stream\n");
    printf("                  F 7 - Call init encoder/decoder at random"
           " during a call\n");
    printf("                  F 8 - Call encoder/decoder without having"
           " allocated memory for \n");
    printf("                        encoder/decoder instance\n");
    printf("                  F 9 - Call decodeB without calling decodeA\n");
    printf("                  F 10 - Call decodeB with garbage data\n");
    printf("[-PL num]       : if -PL option is specified 0<num<100 will "
           "specify the\n");
    printf("                  percentage of packet loss\n\n");
    printf("[-G file]       : if -G option is specified the file given is"
           " a .gns file\n");
    printf("                  that represents a network profile\n\n");
    printf("[-NB num]       : if -NB option, use the narrowband interfaces\n");
    printf("                  num=1 => encode with narrowband encoder"
           " (infile is narrowband)\n");
    printf("                  num=2 => decode with narrowband decoder"
           " (outfile is narrowband)\n\n");
    printf("[-CE num]       : Test of APIs used by Conference Engine.\n");
    printf("                  CE 1 - createInternal, freeInternal,"
           " getNewBitstream \n");
    printf("                  CE 2 - transcode, getBWE \n");
    printf("                  CE 3 - getSendBWE, setSendBWE.  \n\n");
    printf("[-RTP_INIT num] : if -RTP_INIT option is specified num will be"
           " the initial\n");
    printf("                  value of the rtp sequence number.\n\n");
    printf("infile          : Normal speech input file\n\n");
    printf("outfile         : Speech output file\n\n");
    printf("Example usage   : \n\n");
    printf("./kenny.exe -I bottleneck.txt speechIn.pcm speechOut.pcm\n\n");
    exit(0);

  }

  /* Print version number */
  WebRtcIsacfix_version(version_number);
  printf("iSAC version %s \n\n", version_number);

  /* Loop over all command line arguments */
  CodingMode = 0;
  testNum = 0;
  testCE = 0;
  for (i = 1; i < argc-2;i++) {
    /* Instantaneous mode */
    if (!strcmp ("-I", argv[i])) {
      printf("\nInstantaneous BottleNeck\n");
      CodingMode = 1;
      i++;
    }

    /* Set (initial) bottleneck value */
    if (!strcmp ("-INITRATE", argv[i])) {
      rateBPS = atoi(argv[i + 1]);
      setControlBWE = 1;
      if ((rateBPS < 10000) || (rateBPS > 32000)) {
        printf("\n%d is not a initial rate. "
               "Valid values are in the range 10000 to 32000.\n", rateBPS);
        exit(0);
      }
      printf("\nNew initial rate: %d\n", rateBPS);
      i++;
    }

    /* Set (initial) framelength */
    if (!strcmp ("-FL", argv[i])) {
      framesize = atoi(argv[i + 1]);
      if ((framesize != 30) && (framesize != 60)) {
        printf("\n%d is not a valid frame length. "
               "Valid length are 30 and 60 msec.\n", framesize);
        exit(0);
      }
      printf("\nFrame Length: %d\n", framesize);
      i++;
    }

    /* Fixed frame length */
    if (!strcmp ("-FIXED_FL", argv[i])) {
      fixedFL = 1;
      setControlBWE = 1;
    }

    /* Set maximum allowed payload size in bytes */
    if (!strcmp ("-MAX", argv[i])) {
      payloadSize = atoi(argv[i + 1]);
      printf("Maximum Payload Size: %d\n", payloadSize);
      i++;
    }

    /* Set maximum rate in bytes */
    if (!strcmp ("-MAXRATE", argv[i])) {
      payloadRate = atoi(argv[i + 1]);
      printf("Maximum Rate in kbps: %d\n", payloadRate);
      i++;
    }

    /* Test of fault scenarious */
    if (!strcmp ("-F", argv[i])) {
      testNum = atoi(argv[i + 1]);
      printf("\nFault test: %d\n", testNum);
      if (testNum < 1 || testNum > 10) {
        printf("\n%d is not a valid Fault Scenario number."
               " Valid Fault Scenarios are numbered 1-10.\n", testNum);
        exit(0);
      }
      i++;
    }

    /* Packet loss test */
    if (!strcmp ("-PL", argv[i])) {
      if( isdigit( *argv[i+1] ) ) {
        packetLossPercent = atoi( argv[i+1] );
        if( (packetLossPercent < 0) | (packetLossPercent > 100) ) {
          printf( "\nInvalid packet loss perentage \n" );
          exit( 0 );
        }
        if( packetLossPercent > 0 ) {
          printf( "\nSimulating %d %% of independent packet loss\n",
                  packetLossPercent );
        } else {
          printf( "\nNo Packet Loss Is Simulated \n" );
        }
        readLoss = 0;
      } else {
        readLoss = 1;
        plFile = fopen( argv[i+1], "rb" );
        if( plFile == NULL ) {
          printf( "\n couldn't open the frameloss file: %s\n", argv[i+1] );
          exit( 0 );
        }
        printf( "\nSimulating packet loss through the given "
                "channel file: %s\n", argv[i+1] );
      }
      i++;
    }

    /* Random packetlosses */
    if (!strcmp ("-rnd", argv[i])) {
      srand(time(NULL) );
      printf( "\n Random pattern in lossed packets \n" );
    }

    /* Use gns file */
    if (!strcmp ("-G", argv[i])) {
      sscanf(argv[i + 1], "%s", gns_file);
      fp_gns = fopen(gns_file, "rb");
      if (fp_gns  == NULL) {
        printf("Cannot read file %s.\n", gns_file);
        exit(0);
      }
      gns = 1;
      i++;
    }

    /* Run Narrowband interfaces (either encoder or decoder) */
    if (!strcmp ("-NB", argv[i])) {
      nbTest = atoi(argv[i + 1]);
      i++;
    }

    /* Run Conference Engine APIs */
    if (!strcmp ("-CE", argv[i])) {
      testCE = atoi(argv[i + 1]);
      if (testCE==1 || testCE==2) {
        i++;
        scale = (float)atof( argv[i+1] );
      } else if (testCE < 1 || testCE > 3) {
        printf("\n%d is not a valid CE-test number, valid Fault "
               "Scenarios are numbered 1-3\n", testCE);
        exit(0);
      }
      i++;
    }

    /* Set initial RTP number */
    if (!strcmp ("-RTP_INIT", argv[i])) {
      i++;
    }
  }

  /* Get Bottleneck value                                                   */
  /* Gns files and bottleneck should not and can not be used simultaneously */
  bottleneck = atoi(argv[CodingMode+1]);
  if (bottleneck == 0 && gns == 0) {
    sscanf(argv[CodingMode+1], "%s", bottleneck_file);
    f_bn = fopen(bottleneck_file, "rb");
    if (f_bn  == NULL) {
      printf("No value provided for BottleNeck and cannot read file %s\n", bottleneck_file);
      exit(0);
    } else {
      int aux_var;
      printf("reading bottleneck rates from file %s\n\n",bottleneck_file);
      if (fscanf(f_bn, "%d", &aux_var) == EOF) {
        /* Set pointer to beginning of file */
        fseek(f_bn, 0L, SEEK_SET);
        if (fscanf(f_bn, "%d", &aux_var) == EOF) {
          exit(0);
        }
      }
      bottleneck = (WebRtc_Word16)aux_var;
      /* Bottleneck is a cosine function
       * Matlab code for writing the bottleneck file:
       * BottleNeck_10ms = 20e3 + 10e3 * cos((0:5999)/5999*2*pi);
       * fid = fopen('bottleneck.txt', 'wb');
       * fprintf(fid, '%d\n', BottleNeck_10ms); fclose(fid);
       */
    }
  } else {
    f_bn = NULL;
    printf("\nfixed bottleneck rate of %d bits/s\n\n", bottleneck);
  }

  if (CodingMode == 0) {
    printf("\nAdaptive BottleNeck\n");
  }

  /* Get Input and Output files */
  sscanf(argv[argc-2], "%s", inname);
  sscanf(argv[argc-1], "%s", outname);

  /* Add '.bit' to output bitstream file */
  while ((int)outname[h] != 0) {
    outbitsname[h] = outname[h];
    h++;
  }
  for (k=0; k<5; k++) {
    outbitsname[h] = tmpBit[k];
    h++;
  }
  if ((inp = fopen(inname,"rb")) == NULL) {
    printf("  iSAC: Cannot read file %s\n", inname);
    exit(1);
  }
  if ((outp = fopen(outname,"wb")) == NULL) {
    printf("  iSAC: Cannot write file %s\n", outname);
    exit(1);
  }

  if ((outbits = fopen(outbitsname,"wb")) == NULL) {
    printf("  iSAC: Cannot write file %s\n", outbitsname);
    exit(1);
  }
  printf("\nInput:%s\nOutput:%s\n\n", inname, outname);

  /* Error test number 10, garbage data */
  if (testNum == 10) {
    /* Test to run decoder with garbage data */
    srand(random_seed);

    if ( (seedfile = fopen(SEED_FILE, "a+t") ) == NULL ) {
      printf("Error: Could not open file %s\n", SEED_FILE);
    }
    else {
      fprintf(seedfile, "%u\n", random_seed);
      fclose(seedfile);
    }
  }

  /* Runtime statistics */
  starttime = clock()/(double)CLOCKS_PER_SEC;

  /* Initialize the ISAC and BN structs */
  if (testNum != 8)
  {
    if(1){
      err =WebRtcIsacfix_Create(&ISAC_main_inst);
    }else{
      /* Test the Assign functions */
      int sss;
      void *ppp;
      err =WebRtcIsacfix_AssignSize(&sss);
      ppp=malloc(sss);
      err =WebRtcIsacfix_Assign(&ISAC_main_inst,ppp);
    }
    /* Error check */
    if (err < 0) {
      printf("\n\n Error in create.\n\n");
    }
    if (testCE == 1) {
      err = WebRtcIsacfix_CreateInternal(ISAC_main_inst);
      /* Error check */
      if (err < 0) {
        printf("\n\n Error in createInternal.\n\n");
      }
    }
  }

  /* Init of bandwidth data */
  BN_data.send_time     = 0;
  BN_data.arrival_time  = 0;
  BN_data.sample_count  = 0;
  BN_data.rtp_number    = 0;

  /* Initialize encoder and decoder */
  framecnt= 0;
  endfile = 0;
  if (testNum != 1) {
    WebRtcIsacfix_EncoderInit(ISAC_main_inst, CodingMode);
  }
  if (testNum != 2) {
    WebRtcIsacfix_DecoderInit(ISAC_main_inst);
  }

  if (CodingMode == 1) {
    err = WebRtcIsacfix_Control(ISAC_main_inst, bottleneck, framesize);
    if (err < 0) {
      /* exit if returned with error */
      errtype=WebRtcIsacfix_GetErrorCode(ISAC_main_inst);
      printf("\n\n Error in control: %d.\n\n", errtype);
    }
  } else if(setControlBWE == 1) {
    err = WebRtcIsacfix_ControlBwe(ISAC_main_inst, rateBPS, framesize, fixedFL);
  }

  if (payloadSize != 0) {
    err = WebRtcIsacfix_SetMaxPayloadSize(ISAC_main_inst, payloadSize);
    if (err < 0) {
      /* exit if returned with error */
      errtype=WebRtcIsacfix_GetErrorCode(ISAC_main_inst);
      printf("\n\n Error in SetMaxPayloadSize: %d.\n\n", errtype);
      exit(EXIT_FAILURE);
    }
  }
  if (payloadRate != 0) {
    err = WebRtcIsacfix_SetMaxRate(ISAC_main_inst, payloadRate);
    if (err < 0) {
      /* exit if returned with error */
      errtype=WebRtcIsacfix_GetErrorCode(ISAC_main_inst);
      printf("\n\n Error in SetMaxRateInBytes: %d.\n\n", errtype);
      exit(EXIT_FAILURE);
    }
  }

  *speechType = 1;


  while (endfile == 0) {

    if(testNum == 7 && (rand()%2 == 0)) {
      err = WebRtcIsacfix_EncoderInit(ISAC_main_inst, CodingMode);
      /* Error check */
      if (err < 0) {
        errtype=WebRtcIsacfix_GetErrorCode(ISAC_main_inst);
        printf("\n\n Error in encoderinit: %d.\n\n", errtype);
      }

      err = WebRtcIsacfix_DecoderInit(ISAC_main_inst);
      /* Error check */
      if (err < 0) {
        errtype=WebRtcIsacfix_GetErrorCode(ISAC_main_inst);
        printf("\n\n Error in decoderinit: %d.\n\n", errtype);
      }
    }


    cur_framesmpls = 0;
    while (1) {
      /* Read 10 ms speech block */
      if (nbTest != 1) {
        endfile = readframe(shortdata, inp, FRAMESAMPLES_10ms);
      } else {
        endfile = readframe(shortdata, inp, (FRAMESAMPLES_10ms/2));
      }

      if (testNum == 7) {
        srand(time(NULL));
      }

      /* iSAC encoding */
      if (!(testNum == 3 && framecnt == 0)) {
        if (nbTest != 1) {
          short bwe;

          /* Encode */
          stream_len = WebRtcIsacfix_Encode(ISAC_main_inst,
                                            shortdata,
                                            (WebRtc_Word16*)streamdata);

          /* If packet is ready, and CE testing, call the different API functions
             from the internal API.                       */
          if (stream_len>0) {
            if (testCE == 1) {
              err = WebRtcIsacfix_ReadBwIndex((WebRtc_Word16*)streamdata, &bwe);
              stream_len = WebRtcIsacfix_GetNewBitStream(
                  ISAC_main_inst,
                  bwe,
                  scale,
                  (WebRtc_Word16*)streamdata);
            } else if (testCE == 2) {
              /* transcode function not supported */
            } else if (testCE == 3) {
              /* Only for Function testing. The functions should normally
                 not be used in this way                                      */

              err = WebRtcIsacfix_GetDownLinkBwIndex(ISAC_main_inst, &bwe);
              /* Error Check */
              if (err < 0) {
                errtype=WebRtcIsacfix_GetErrorCode(ISAC_main_inst);
                printf("\nError in getSendBWE: %d.\n", errtype);
              }

              err = WebRtcIsacfix_UpdateUplinkBw(ISAC_main_inst, bwe);
              /* Error Check */
              if (err < 0) {
                errtype=WebRtcIsacfix_GetErrorCode(ISAC_main_inst);
                printf("\nError in setBWE: %d.\n", errtype);
              }

            }
          }
        } else {
#ifdef WEBRTC_ISAC_FIX_NB_CALLS_ENABLED
          stream_len = WebRtcIsacfix_EncodeNb(ISAC_main_inst,
                                              shortdata,
                                              streamdata);
#else
          stream_len = -1;
#endif
        }
      }
      else
      {
        break;
      }

      if (stream_len < 0 || err < 0) {
        /* exit if returned with error */
        errtype=WebRtcIsacfix_GetErrorCode(ISAC_main_inst);
        printf("\nError in encoder: %d.\n", errtype);
      } else {
        if (fwrite(streamdata, sizeof(char),
                   stream_len, outbits) != (size_t)stream_len) {
          return -1;
        }
      }

      cur_framesmpls += FRAMESAMPLES_10ms;

      /* read next bottleneck rate */
      if (f_bn != NULL) {
        int aux_var;
        if (fscanf(f_bn, "%d", &aux_var) == EOF) {
          /* Set pointer to beginning of file */
          fseek(f_bn, 0L, SEEK_SET);
          if (fscanf(f_bn, "%d", &aux_var) == EOF) {
            exit(0);
          }
        }
        bottleneck = (WebRtc_Word16)aux_var;
        if (CodingMode == 1) {
          WebRtcIsacfix_Control(ISAC_main_inst, bottleneck, framesize);
        }
      }

      /* exit encoder loop if the encoder returned a bitstream */
      if (stream_len != 0) break;
    }

    /* make coded sequence to short be inreasing */
    /* the length the decoder expects */
    if (testNum == 4) {
      stream_len += 10;
    }

    /* make coded sequence to long be decreasing */
    /* the length the decoder expects */
    if (testNum == 5) {
      stream_len -= 10;
    }

    if (testNum == 6) {
      srand(time(NULL));
      for (i = 0; i < stream_len; i++ ) {
        streamdata[i] = rand();
      }
    }

    /* set pointer to beginning of file */
    if (fp_gns != NULL) {
      if (fscanf(fp_gns, "%d", &cur_delay) == EOF) {
        fseek(fp_gns, 0L, SEEK_SET);
        if (fscanf(fp_gns, "%d", &cur_delay) == EOF) {
          exit(0);
        }
      }
    }

    /* simulate packet handling through NetEq and the modem */
    if (!(testNum == 3 && framecnt == 0)) {
      if (gns == 0) {
        get_arrival_time(cur_framesmpls, stream_len, bottleneck,
                         &BN_data);
      } else {
        get_arrival_time2(cur_framesmpls, cur_delay, &BN_data);
      }
    }

    /* packet not dropped */
    if (cur_delay != -1) {

      /* Error test number 10, garbage data */
      if (testNum == 10) {
        for ( i = 0; i < stream_len; i++) {
          streamdata[i] = (short) (streamdata[i] + (short) rand());
        }
      }

      if (testNum != 9) {
        err = WebRtcIsacfix_UpdateBwEstimate(ISAC_main_inst,
                                             streamdata,
                                             stream_len,
                                             BN_data.rtp_number,
                                             BN_data.send_time,
                                             BN_data.arrival_time);

        if (err < 0) {
          /* exit if returned with error */
          errtype=WebRtcIsacfix_GetErrorCode(ISAC_main_inst);
          printf("\nError in decoder: %d.\n", errtype);
        }
      }
#ifdef _DEBUG
      fprintf(stderr,"  \rframe = %7d", framecnt);
#endif

      if( readLoss == 1 ) {
        if( fread( &lostFrame, sizeof(WebRtc_Word16), 1, plFile ) != 1 ) {
          rewind( plFile );
        }
        lostFrame = !lostFrame;
      } else {
        lostFrame = (rand()%100 < packetLossPercent);
      }



      /* iSAC decoding */
      if( lostFrame && framecnt >  0) {
        if (nbTest !=2) {
          declen = WebRtcIsacfix_DecodePlc(ISAC_main_inst,
                                           decoded, prevFrameSize );
        } else {
#ifdef WEBRTC_ISAC_FIX_NB_CALLS_ENABLED
          declen = WebRtcIsacfix_DecodePlcNb(ISAC_main_inst, decoded,
                                             prevFrameSize );
#else
          declen = -1;
#endif
        }
        lostPackets++;
      } else {
        if (nbTest !=2 ) {
          short FL;
          /* Call getFramelen, only used here for function test */
          err = WebRtcIsacfix_ReadFrameLen((WebRtc_Word16*)streamdata, &FL);
          declen = WebRtcIsacfix_Decode( ISAC_main_inst, streamdata, stream_len,
                                         decoded, speechType );
          /* Error check */
          if (err<0 || declen<0 || FL!=declen) {
            errtype=WebRtcIsacfix_GetErrorCode(ISAC_main_inst);
            printf("\nError in decode_B/or getFrameLen: %d.\n", errtype);
          }
          prevFrameSize = declen/480;

        } else {
#ifdef WEBRTC_ISAC_FIX_NB_CALLS_ENABLED
          declen = WebRtcIsacfix_DecodeNb( ISAC_main_inst, streamdata,
                                           stream_len, decoded, speechType );
#else
          declen = -1;
#endif
          prevFrameSize = declen/240;
        }
      }

      if (declen <= 0) {
        /* exit if returned with error */
        errtype=WebRtcIsacfix_GetErrorCode(ISAC_main_inst);
        printf("\nError in decoder: %d.\n", errtype);
      }

      /* Write decoded speech frame to file */
      if (fwrite(decoded, sizeof(WebRtc_Word16),
                 declen, outp) != (size_t)declen) {
        return -1;
      }
      //   fprintf( ratefile, "%f \n", stream_len / ( ((double)declen)/
      // ((double)FS) ) * 8 );
    } else {
      lostPackets++;
    }
    framecnt++;

    totalsmpls += declen;
    totalbits += 8 * stream_len;
    kbps = ((double) FS) / ((double) cur_framesmpls) * 8.0 *
        stream_len / 1000.0;// kbits/s

    /* Error test number 10, garbage data */
    if (testNum == 10) {
      if ( (seedfile = fopen(SEED_FILE, "a+t") ) == NULL ) {
        printf( "Error: Could not open file %s\n", SEED_FILE);
      }
      else {
        fprintf(seedfile, "ok\n\n");
        fclose(seedfile);
      }
    }

#ifdef _DEBUG

    fy = fopen("bit_rate.dat", "a");
    fprintf(fy, "Frame %i = %0.14f\n", framecnt, kbps);
    fclose(fy);

#endif /* _DEBUG */

  }
  printf("\nLost Frames %d ~ %4.1f%%\n", lostPackets,
         (double)lostPackets/(double)framecnt*100.0 );
  printf("\n\ntotal bits                          = %d bits", totalbits);
  printf("\nmeasured average bitrate              = %0.3f kbits/s",
         (double)totalbits *(FS/1000) / totalsmpls);
  printf("\n");

#ifdef _DEBUG
  /* fprintf(stderr,"\n\ntotal bits    = %d bits", totalbits);
     fprintf(stderr,"\nmeasured average bitrate  = %0.3f kbits/s",
     (double)totalbits *(FS/1000) / totalsmpls);
     fprintf(stderr,"\n");
  */
#endif /* _DEBUG */

  /* Runtime statistics */


  runtime = (double)(((double)clock()/(double)CLOCKS_PER_SEC)-starttime);
  length_file = ((double)framecnt*(double)declen/FS);
  printf("\n\nLength of speech file: %.1f s\n", length_file);
  printf("Time to run iSAC:      %.2f s (%.2f %% of realtime)\n\n",
         runtime, (100*runtime/length_file));
  printf("\n\n_______________________________________________\n");

  fclose(inp);
  fclose(outp);
  fclose(outbits);

  if ( testCE == 1) {
    WebRtcIsacfix_FreeInternal(ISAC_main_inst);
  }
  WebRtcIsacfix_Free(ISAC_main_inst);
  return 0;
}
コード例 #7
0
ファイル: text2sf.c プロジェクト: jxxcarlson/sf2sound
int main(int argc, char* argv[])
{
    PSF_PROPS props;
    long framesread;
    long totalread;
    /* init all dynamic resources to default states */
    int ifd = -1,ofd = -1;
    int i,error = 0;
    double gain = 1.0;
    PSF_CHPEAK* peaks = NULL;
    psf_format outformat =  PSF_FMT_UNKNOWN;
    FILE* fin = NULL;
    float* frame;

    printf("TEXT2SF: convert text audio data to soundfile\n");

    if(argc < ARG_NARGS) {
        printf("insufficient arguments.\n"
               "usage:\n\t"
               "text2sf infile outfile srate chans gain\n");
        return 1;
    }
    /* be good, and startup portsf */
    if(psf_init()) {
        printf("unable to start portsf\n");
        return 1;
    }

    fin = fopen(argv[ARG_INFILE],"r");
    /* we now have a resource, so we use goto hereafter on hitting any error */
    /* tell user if source file is already floats  */
    if(fin==NULL) {
        printf("cannot open infile %s\n",argv[ARG_INFILE]);
        return 1;
    }

    props.chans = atoi(argv[ARG_CHANS]);
    if(props.chans <=0) {
        printf("chans must be positive!\n");
        fclose(fin);
        return 1;
    }
    props.srate = atoi(argv[ARG_SR]);
    if(props.srate <=0) {
        printf("srate must be positive!\n");
        fclose(fin);
        return 1;
    }
    gain = atof(argv[ARG_GAIN]);
    if(gain <= 0.0) {
        printf("gain value must be positive!\n");
        fclose(fin);
        return 1;
    }
    frame = malloc(props.chans * sizeof(float));
    if(frame==NULL) {
        puts("No memoery!\n");
        fclose(fin);
        return 1;
    }
    /* fixed output to 16bit file; one alternative would be PSF_SAM_IEEE_FLOAT for 32bit float format */
    props.samptype = PSF_SAMP_16;
    props.format = PSF_STDWAVE;
    props.chformat = STDWAVE;
    /* check file extension of outfile name, so we use correct output file format*/
    outformat = psf_getFormatExt(argv[ARG_OUTFILE]);
    if(outformat == PSF_FMT_UNKNOWN) {
        printf("outfile name %s has unknown format.\n"
               "Use any of .wav, .aiff, .aif, .afc, .aifc\n",argv[ARG_OUTFILE]);
        error++;
        goto exit;
    }
    props.format = outformat;

    ofd = psf_sndCreate(argv[ARG_OUTFILE],&props,0,0,PSF_CREATE_RDWR);
    if(ofd < 0) {
        printf("Error: unable to create outfile %s\n",argv[ARG_OUTFILE]);
        error++;
        goto exit;
    }


    /* and allocate space for PEAK info */
    peaks  =  (PSF_CHPEAK*) malloc(props.chans * sizeof(PSF_CHPEAK));
    if(peaks == NULL) {
        puts("No memory!\n");
        error++;
        goto exit;
    }
    printf("copying....\n");

    /* single-frame loop to do copy: report any read/write errors */
    framesread = readframe(fin,frame,props.chans);
    totalread = 0;		/* count sample frames as they are copied */
    /* note: readframe retval of -1 signifies EOF */
    while (framesread == 1) {
        totalread++;
        /*	<--- do any processing here! ---------->*/
        for(i=0; i < props.chans; i++)
            frame[i] *= gain;
        if(psf_sndWriteFloatFrames(ofd,frame,1) != 1) {
            printf("Error writing to outfile\n");
            error++;
            break;
        }
        framesread = readframe(fin,frame,props.chans);
    }
    if(framesread == 0)	{
        printf("Error reading infile at line %ld. Outfile may be incomplete.\n",totalread);
        error++;
    }
    else
        printf("Done. %ld sample frames copied to %s\n",totalread,argv[ARG_OUTFILE]);

    /* report PEAK values to user */
    if(psf_sndReadPeaks(ofd,peaks,NULL) > 0) {
        long i;
        double peaktime;
        printf("PEAK information:\n");
        for(i=0; i < props.chans; i++) {
            peaktime = (double) peaks[i].pos / (double) props.srate;
            printf("CH %ld:\t%.4f at %.4f secs\n", i+1, peaks[i].val, peaktime);
        }
    }
    /* do all cleanup  */
exit:
    if(fin != NULL)
        fclose(fin);
    if(ofd >= 0)
        psf_sndClose(ofd);
    if(frame)
        free(frame);
    if(peaks)
        free(peaks);
    psf_finish();
    /* return error status to caller: may be useful in a script etc */
    return error;
}
コード例 #8
0
int main(int argc, char* argv[]) {
    char inname[50], outname[50], bottleneck_file[50], bitfilename[60],
         bitending[10] = "_bits.pcm";
    FILE* inp, *outp, *f_bn, *bitsp;
    int framecnt, endfile;

    int i, j, errtype, plc = 0;
    int16_t CodingMode;
    int16_t bottleneck;

    int framesize = 30; /* ms */
    // int framesize = 60; /* To invoke cisco complexity case at frame 2252 */

    int cur_framesmpls, err;

    /* Runtime statistics */
    double starttime;
    double runtime;
    double length_file;

    size_t stream_len = 0;
    int declen;

    int16_t shortdata[FRAMESAMPLES_10ms];
    int16_t decoded[MAX_FRAMESAMPLES];
    uint16_t streamdata[600];
    int16_t speechType[1];

    // int16_t* iSACstruct;

    char version_number[20];
    int mode = -1, tmp, nbTest = 0; /*,sss;*/

#if !defined(NDEBUG)
    FILE* fy;
    double kbps;
    size_t totalbits = 0;
    int totalsmpls = 0;
#endif

    /* only one structure used for ISAC encoder */
    ISAC_MainStruct* ISAC_main_inst;
    ISACFIX_MainStruct* ISACFIX_main_inst;

    BottleNeckModel BN_data;
    f_bn = NULL;

#if !defined(NDEBUG)
    fy = fopen("bit_rate.dat", "w");
    fclose(fy);
    fy = fopen("bytes_frames.dat", "w");
    fclose(fy);
#endif

    // histfile = fopen("histo.dat", "ab");
    // ratefile = fopen("rates.dat", "ab");

    /* handling wrong input arguments in the command line */
    if ((argc < 6) || (argc > 10)) {
        printf("\n\nWrong number of arguments or flag values.\n\n");

        printf("\n");
        WebRtcIsacfix_version(version_number);
        printf("iSAC version %s \n\n", version_number);

        printf("Usage:\n\n");
        printf("./kenny.exe [-I] bottleneck_value infile outfile \n\n");
        printf("with:\n");

        printf("[-I]            : If -I option is specified, the coder will use\n");
        printf("                  an instantaneous Bottleneck value. If not, it\n");
        printf("                  will be an adaptive Bottleneck value.\n\n");
        printf("bottleneck_value: The value of the bottleneck provided either\n");
        printf("                  as a fixed value (e.g. 25000) or\n");
        printf("                  read from a file (e.g. bottleneck.txt)\n\n");
        printf("[-m] mode       : Mode (encoder - decoder):\n");
        printf("                    0 - float - float\n");
        printf("                    1 - float - fix\n");
        printf("                    2 - fix - float\n");
        printf("                    3 - fix - fix\n\n");
        printf("[-PLC]          : Test PLC packetlosses\n\n");
        printf("[-NB] num       : Test NB interfaces:\n");
        printf("                    1 - encNB\n");
        printf("                    2 - decNB\n\n");
        printf("infile          : Normal speech input file\n\n");
        printf("outfile         : Speech output file\n\n");
        printf("Example usage:\n\n");
        printf("./kenny.exe -I bottleneck.txt -m 1 speechIn.pcm speechOut.pcm\n\n");
        exit(0);
    }

    printf("--------------------START---------------------\n\n");
    WebRtcIsac_version(version_number);
    printf("iSAC FLOAT version %s \n", version_number);
    WebRtcIsacfix_version(version_number);
    printf("iSAC FIX version   %s \n\n", version_number);

    CodingMode = 0;
    tmp = 1;
    for (i = 1; i < argc; i++) {
        if (!strcmp("-I", argv[i])) {
            printf("\nInstantaneous BottleNeck\n");
            CodingMode = 1;
            i++;
            tmp = 0;
        }

        if (!strcmp("-m", argv[i])) {
            mode = atoi(argv[i + 1]);
            i++;
        }

        if (!strcmp("-PLC", argv[i])) {
            plc = 1;
        }

        if (!strcmp("-NB", argv[i])) {
            nbTest = atoi(argv[i + 1]);
            i++;
        }
    }

    if (mode < 0) {
        printf("\nError! Mode must be set: -m 0 \n");
        exit(0);
    }

    if (CodingMode == 0) {
        printf("\nAdaptive BottleNeck\n");
    }

    /* Get Bottleneck value */
    bottleneck = atoi(argv[2 - tmp]);
    if (bottleneck == 0) {
        sscanf(argv[2 - tmp], "%s", bottleneck_file);
        f_bn = fopen(bottleneck_file, "rb");
        if (f_bn == NULL) {
            printf("No value provided for BottleNeck and cannot read file %s.\n",
                   bottleneck_file);
            exit(0);
        } else {
            printf("reading bottleneck rates from file %s\n\n", bottleneck_file);
            if (fscanf(f_bn, "%d", &bottleneck) == EOF) {
                /* Set pointer to beginning of file */
                fseek(f_bn, 0L, SEEK_SET);
                fscanf(f_bn, "%d", &bottleneck);
            }

            /* Bottleneck is a cosine function
             * Matlab code for writing the bottleneck file:
             * BottleNeck_10ms = 20e3 + 10e3 * cos((0:5999)/5999*2*pi);
             * fid = fopen('bottleneck.txt', 'wb');
             * fprintf(fid, '%d\n', BottleNeck_10ms); fclose(fid);
             */
        }
    } else {
        printf("\nfixed bottleneck rate of %d bits/s\n\n", bottleneck);
    }

    /* Get Input and Output files */
    sscanf(argv[argc - 2], "%s", inname);
    sscanf(argv[argc - 1], "%s", outname);

    if ((inp = fopen(inname, "rb")) == NULL) {
        printf("  iSAC: Cannot read file %s.\n", inname);
        exit(1);
    }
    if ((outp = fopen(outname, "wb")) == NULL) {
        printf("  iSAC: Cannot write file %s.\n", outname);
        exit(1);
    }
    printf("\nInput:%s\nOutput:%s\n", inname, outname);

    i = 0;
    while (outname[i] != '\0') {
        bitfilename[i] = outname[i];
        i++;
    }
    i -= 4;
    for (j = 0; j < 9; j++, i++)
        bitfilename[i] = bitending[j];
    bitfilename[i] = '\0';
    if ((bitsp = fopen(bitfilename, "wb")) == NULL) {
        printf("  iSAC: Cannot read file %s.\n", bitfilename);
        exit(1);
    }
    printf("Bitstream:%s\n\n", bitfilename);

    starttime = clock() / (double)CLOCKS_PER_SEC; /* Runtime statistics */

    /* Initialize the ISAC and BN structs */
    WebRtcIsac_create(&ISAC_main_inst);
    WebRtcIsacfix_Create(&ISACFIX_main_inst);

    BN_data.send_time = 0;
    BN_data.arrival_time = 0;
    BN_data.sample_count = 0;
    BN_data.rtp_number = 0;

    /* Initialize encoder and decoder */
    framecnt = 0;
    endfile = 0;

    if (mode == 0) { /* Encode using FLOAT, decode using FLOAT */

        printf("Coding mode: Encode using FLOAT, decode using FLOAT \n\n");

        /* Init iSAC FLOAT */
        WebRtcIsac_EncoderInit(ISAC_main_inst, CodingMode);
        WebRtcIsac_DecoderInit(ISAC_main_inst);
        if (CodingMode == 1) {
            err = WebRtcIsac_Control(ISAC_main_inst, bottleneck, framesize);
            if (err < 0) {
                /* exit if returned with error */
                errtype = WebRtcIsac_GetErrorCode(ISAC_main_inst);
                printf("\n\n Error in initialization: %d.\n\n", errtype);
                // exit(EXIT_FAILURE);
            }
        }

    } else if (mode == 1) { /* Encode using FLOAT, decode using FIX */

        printf("Coding mode: Encode using FLOAT, decode using FIX \n\n");

        /* Init iSAC FLOAT */
        WebRtcIsac_EncoderInit(ISAC_main_inst, CodingMode);
        WebRtcIsac_DecoderInit(ISAC_main_inst);
        if (CodingMode == 1) {
            err = WebRtcIsac_Control(ISAC_main_inst, bottleneck, framesize);
            if (err < 0) {
                /* exit if returned with error */
                errtype = WebRtcIsac_GetErrorCode(ISAC_main_inst);
                printf("\n\n Error in initialization: %d.\n\n", errtype);
                // exit(EXIT_FAILURE);
            }
        }

        /* Init iSAC FIX */
        WebRtcIsacfix_EncoderInit(ISACFIX_main_inst, CodingMode);
        WebRtcIsacfix_DecoderInit(ISACFIX_main_inst);
        if (CodingMode == 1) {
            err = WebRtcIsacfix_Control(ISACFIX_main_inst, bottleneck, framesize);
            if (err < 0) {
                /* exit if returned with error */
                errtype = WebRtcIsacfix_GetErrorCode(ISACFIX_main_inst);
                printf("\n\n Error in initialization: %d.\n\n", errtype);
                // exit(EXIT_FAILURE);
            }
        }
    } else if (mode == 2) { /* Encode using FIX, decode using FLOAT */

        printf("Coding mode: Encode using FIX, decode using FLOAT \n\n");

        /* Init iSAC FLOAT */
        WebRtcIsac_EncoderInit(ISAC_main_inst, CodingMode);
        WebRtcIsac_DecoderInit(ISAC_main_inst);
        if (CodingMode == 1) {
            err = WebRtcIsac_Control(ISAC_main_inst, bottleneck, framesize);
            if (err < 0) {
                /* exit if returned with error */
                errtype = WebRtcIsac_GetErrorCode(ISAC_main_inst);
                printf("\n\n Error in initialization: %d.\n\n", errtype);
                // exit(EXIT_FAILURE);
            }
        }

        /* Init iSAC FIX */
        WebRtcIsacfix_EncoderInit(ISACFIX_main_inst, CodingMode);
        WebRtcIsacfix_DecoderInit(ISACFIX_main_inst);
        if (CodingMode == 1) {
            err = WebRtcIsacfix_Control(ISACFIX_main_inst, bottleneck, framesize);
            if (err < 0) {
                /* exit if returned with error */
                errtype = WebRtcIsacfix_GetErrorCode(ISACFIX_main_inst);
                printf("\n\n Error in initialization: %d.\n\n", errtype);
                // exit(EXIT_FAILURE);
            }
        }
    } else if (mode == 3) {
        printf("Coding mode: Encode using FIX, decode using FIX \n\n");

        WebRtcIsacfix_EncoderInit(ISACFIX_main_inst, CodingMode);
        WebRtcIsacfix_DecoderInit(ISACFIX_main_inst);
        if (CodingMode == 1) {
            err = WebRtcIsacfix_Control(ISACFIX_main_inst, bottleneck, framesize);
            if (err < 0) {
                /* exit if returned with error */
                errtype = WebRtcIsacfix_GetErrorCode(ISACFIX_main_inst);
                printf("\n\n Error in initialization: %d.\n\n", errtype);
                // exit(EXIT_FAILURE);
            }
        }

    } else
        printf("Mode must be value between 0 and 3\n");
    *speechType = 1;

//#define BI_TEST 1
#ifdef BI_TEST
    err = WebRtcIsacfix_SetMaxPayloadSize(ISACFIX_main_inst, 300);
    if (err < 0) {
        /* exit if returned with error */
        errtype = WebRtcIsacfix_GetErrorCode(ISACFIX_main_inst);
        printf("\n\n Error in setMaxPayloadSize: %d.\n\n", errtype);
        fclose(inp);
        fclose(outp);
        fclose(bitsp);
        return (EXIT_FAILURE);
    }
#endif

    while (endfile == 0) {
        cur_framesmpls = 0;
        while (1) {
            int stream_len_int;

            /* Read 10 ms speech block */
            if (nbTest != 1)
                endfile = readframe(shortdata, inp, FRAMESAMPLES_10ms);
            else
                endfile = readframe(shortdata, inp, (FRAMESAMPLES_10ms / 2));

            /* iSAC encoding */

            if (mode == 0 || mode == 1) {
                stream_len_int =
                    WebRtcIsac_Encode(ISAC_main_inst, shortdata, (uint8_t*)streamdata);
                if (stream_len_int < 0) {
                    /* exit if returned with error */
                    errtype = WebRtcIsac_GetErrorCode(ISAC_main_inst);
                    printf("\n\nError in encoder: %d.\n\n", errtype);
                    // exit(EXIT_FAILURE);
                }
            } else if (mode == 2 || mode == 3) {
                /* iSAC encoding */
                if (nbTest != 1) {
                    stream_len_int = WebRtcIsacfix_Encode(ISACFIX_main_inst, shortdata,
                                                          (uint8_t*)streamdata);
                } else {
                    stream_len_int =
                        WebRtcIsacfix_EncodeNb(ISACFIX_main_inst, shortdata, streamdata);
                }

                if (stream_len_int < 0) {
                    /* exit if returned with error */
                    errtype = WebRtcIsacfix_GetErrorCode(ISACFIX_main_inst);
                    printf("\n\nError in encoder: %d.\n\n", errtype);
                    // exit(EXIT_FAILURE);
                }
            }
            stream_len = (size_t)stream_len_int;

            cur_framesmpls += FRAMESAMPLES_10ms;

            /* read next bottleneck rate */
            if (f_bn != NULL) {
                if (fscanf(f_bn, "%d", &bottleneck) == EOF) {
                    /* Set pointer to beginning of file */
                    fseek(f_bn, 0L, SEEK_SET);
                    fscanf(f_bn, "%d", &bottleneck);
                }
                if (CodingMode == 1) {
                    if (mode == 0 || mode == 1)
                        WebRtcIsac_Control(ISAC_main_inst, bottleneck, framesize);
                    else if (mode == 2 || mode == 3)
                        WebRtcIsacfix_Control(ISACFIX_main_inst, bottleneck, framesize);
                }
            }

            /* exit encoder loop if the encoder returned a bitstream */
            if (stream_len != 0)
                break;
        }

        fwrite(streamdata, 1, stream_len, bitsp); /* NOTE! Writes bytes to file */

        /* simulate packet handling through NetEq and the modem */
        get_arrival_time(cur_framesmpls, stream_len, bottleneck, &BN_data);
        //*****************************
        if (1) {
            if (mode == 0) {
                err = WebRtcIsac_UpdateBwEstimate(ISAC_main_inst, streamdata,
                                                  stream_len, BN_data.rtp_number,
                                                  BN_data.arrival_time);

                if (err < 0) {
                    /* exit if returned with error */
                    errtype = WebRtcIsac_GetErrorCode(ISAC_main_inst);
                    printf("\n\nError in decoder: %d.\n\n", errtype);
                    // exit(EXIT_FAILURE);
                }
                /* iSAC decoding */
                declen = WebRtcIsac_Decode(ISAC_main_inst, streamdata, stream_len,
                                           decoded, speechType);
                if (declen <= 0) {
                    /* exit if returned with error */
                    errtype = WebRtcIsac_GetErrorCode(ISAC_main_inst);
                    printf("\n\nError in decoder: %d.\n\n", errtype);
                    // exit(EXIT_FAILURE);
                }
            } else if (mode == 1) {
                err = WebRtcIsac_UpdateBwEstimate(ISAC_main_inst, streamdata,
                                                  stream_len, BN_data.rtp_number,
                                                  BN_data.arrival_time);
                err = WebRtcIsacfix_UpdateBwEstimate1(ISACFIX_main_inst, streamdata,
                                                      stream_len, BN_data.rtp_number,
                                                      BN_data.arrival_time);
                if (err < 0) {
                    /* exit if returned with error */
                    errtype = WebRtcIsacfix_GetErrorCode(ISACFIX_main_inst);
                    printf("\n\nError in decoder: %d.\n\n", errtype);
                    // exit(EXIT_FAILURE);
                }

                declen = WebRtcIsac_Decode(ISAC_main_inst, streamdata, stream_len,
                                           decoded, speechType);

                /* iSAC decoding */
                if (plc && (framecnt + 1) % 10 == 0) {
                    if (nbTest != 2) {
                        declen =
                            (int)WebRtcIsacfix_DecodePlc(ISACFIX_main_inst, decoded, 1);
                    } else {
                        declen =
                            (int)WebRtcIsacfix_DecodePlcNb(ISACFIX_main_inst, decoded, 1);
                    }
                } else {
                    if (nbTest != 2)
                        declen = WebRtcIsacfix_Decode(ISACFIX_main_inst, streamdata,
                                                      stream_len, decoded, speechType);
                    else
                        declen = WebRtcIsacfix_DecodeNb(ISACFIX_main_inst, streamdata,
                                                        stream_len, decoded, speechType);
                }

                if (declen <= 0) {
                    /* exit if returned with error */
                    errtype = WebRtcIsacfix_GetErrorCode(ISACFIX_main_inst);
                    printf("\n\nError in decoder: %d.\n\n", errtype);
                    // exit(EXIT_FAILURE);
                }
            } else if (mode == 2) {
                err = WebRtcIsacfix_UpdateBwEstimate1(ISACFIX_main_inst, streamdata,
                                                      stream_len, BN_data.rtp_number,
                                                      BN_data.arrival_time);

                err = WebRtcIsac_UpdateBwEstimate(ISAC_main_inst, streamdata,
                                                  stream_len, BN_data.rtp_number,
                                                  BN_data.arrival_time);

                if (err < 0) {
                    /* exit if returned with error */
                    errtype = WebRtcIsac_GetErrorCode(ISAC_main_inst);
                    printf("\n\nError in decoder: %d.\n\n", errtype);
                    // exit(EXIT_FAILURE);
                }
                /* iSAC decoding */
                declen = WebRtcIsac_Decode(ISAC_main_inst, streamdata, stream_len,
                                           decoded, speechType);
                if (declen <= 0) {
                    /* exit if returned with error */
                    errtype = WebRtcIsac_GetErrorCode(ISAC_main_inst);
                    printf("\n\nError in decoder: %d.\n\n", errtype);
                    // exit(EXIT_FAILURE);
                }
            } else if (mode == 3) {
                err = WebRtcIsacfix_UpdateBwEstimate(
                          ISACFIX_main_inst, streamdata, stream_len, BN_data.rtp_number,
                          BN_data.send_time, BN_data.arrival_time);

                if (err < 0) {
                    /* exit if returned with error */
                    errtype = WebRtcIsacfix_GetErrorCode(ISACFIX_main_inst);
                    printf("\n\nError in decoder: %d.\n\n", errtype);
                    // exit(EXIT_FAILURE);
                }
                /* iSAC decoding */

                if (plc && (framecnt + 1) % 10 == 0) {
                    if (nbTest != 2) {
                        declen =
                            (int)WebRtcIsacfix_DecodePlc(ISACFIX_main_inst, decoded, 1);
                    } else {
                        declen =
                            (int)WebRtcIsacfix_DecodePlcNb(ISACFIX_main_inst, decoded, 1);
                    }
                } else {
                    if (nbTest != 2) {
                        declen = WebRtcIsacfix_Decode(ISACFIX_main_inst, streamdata,
                                                      stream_len, decoded, speechType);
                    } else {
                        declen = WebRtcIsacfix_DecodeNb(ISACFIX_main_inst, streamdata,
                                                        stream_len, decoded, speechType);
                    }
                }
                if (declen <= 0) {
                    /* exit if returned with error */
                    errtype = WebRtcIsacfix_GetErrorCode(ISACFIX_main_inst);
                    printf("\n\nError in decoder: %d.\n\n", errtype);
                    // exit(EXIT_FAILURE);
                }
            }

            /* Write decoded speech frame to file */
            fwrite(decoded, sizeof(int16_t), declen, outp);
        }

        fprintf(stderr, "  \rframe = %d", framecnt);
        framecnt++;

#if !defined(NDEBUG)

        totalsmpls += declen;
        totalbits += 8 * stream_len;
        kbps = (double)FS / (double)cur_framesmpls * 8.0 * stream_len / 1000.0;
        fy = fopen("bit_rate.dat", "a");
        fprintf(fy, "Frame %i = %0.14f\n", framecnt, kbps);
        fclose(fy);

#endif
    }

#if !defined(NDEBUG)
    printf("\n\ntotal bits               = %" PRIuS " bits", totalbits);
    printf("\nmeasured average bitrate = %0.3f kbits/s",
           (double)totalbits * (FS / 1000) / totalsmpls);
    printf("\n");
#endif

    /* Runtime statistics */
    runtime = (double)(clock() / (double)CLOCKS_PER_SEC - starttime);
    length_file = ((double)framecnt * (double)declen / FS);
    printf("\n\nLength of speech file: %.1f s\n", length_file);
    printf("Time to run iSAC:      %.2f s (%.2f %% of realtime)\n\n", runtime,
           (100 * runtime / length_file));
    printf("---------------------END----------------------\n");

    fclose(inp);
    fclose(outp);

    WebRtcIsac_Free(ISAC_main_inst);
    WebRtcIsacfix_Free(ISACFIX_main_inst);

    // fclose(histfile);
    // fclose(ratefile);

    return 0;
}
コード例 #9
0
ファイル: putseq.c プロジェクト: SirAbedi/streamit
void putseq()
{
  /* this routine assumes (N % M) == 0 */
  int i, j, k, f, f0, n, np, nb, sxf, syf, sxb, syb;
  int ipflag;
  FILE *fd;
  char name[256];
  unsigned char *neworg[3], *newref[3];
  static char ipb[5] = {' ','I','P','B','D'};

  rc_init_seq(); /* initialize rate control */

  /* sequence header, sequence extension and sequence display extension */
  putseqhdr();
  if (!mpeg1)
  {
    putseqext();
    putseqdispext();
  }

  /* optionally output some text data (description, copyright or whatever) */
  if (strlen(id_string) > 1)
    putuserdata(id_string);

  /* loop through all frames in encoding/decoding order */
  for (i=0; i<nframes; i++)
  {
    if (!quiet)
    {
      fprintf(stderr,"Encoding frame %d ",i);
      fflush(stderr);
    }

    /* f0: lowest frame number in current GOP
     *
     * first GOP contains N-(M-1) frames,
     * all other GOPs contain N frames
     */
    f0 = N*((i+(M-1))/N) - (M-1);

    if (f0<0)
      f0=0;

    if (i==0 || (i-1)%M==0)
    {
      /* I or P frame */
      for (j=0; j<3; j++)
      {
        /* shuffle reference frames */
        neworg[j] = oldorgframe[j];
        newref[j] = oldrefframe[j];
        oldorgframe[j] = neworgframe[j];
        oldrefframe[j] = newrefframe[j];
        neworgframe[j] = neworg[j];
        newrefframe[j] = newref[j];
      }

      /* f: frame number in display order */
      f = (i==0) ? 0 : i+M-1;
      if (f>=nframes)
        f = nframes - 1;

      if (i==f0) /* first displayed frame in GOP is I */
      {
        /* I frame */
        pict_type = I_TYPE;
        forw_hor_f_code = forw_vert_f_code = 15;
        back_hor_f_code = back_vert_f_code = 15;

        /* n: number of frames in current GOP
         *
         * first GOP contains (M-1) less (B) frames
         */
        n = (i==0) ? N-(M-1) : N;

        /* last GOP may contain less frames */
        if (n > nframes-f0)
          n = nframes-f0;

        /* number of P frames */
        if (i==0)
          np = (n + 2*(M-1))/M - 1; /* first GOP */
        else
          np = (n + (M-1))/M - 1;

        /* number of B frames */
        nb = n - np - 1;

        rc_init_GOP(np,nb);

        putgophdr(f0,i==0); /* set closed_GOP in first GOP only */
      }
      else
      {
        /* P frame */
        pict_type = P_TYPE;
        forw_hor_f_code = motion_data[0].forw_hor_f_code;
        forw_vert_f_code = motion_data[0].forw_vert_f_code;
        back_hor_f_code = back_vert_f_code = 15;
        sxf = motion_data[0].sxf;
        syf = motion_data[0].syf;
      }
    }
    else
    {
      /* B frame */
      for (j=0; j<3; j++)
      {
        neworg[j] = auxorgframe[j];
        newref[j] = auxframe[j];
      }

      /* f: frame number in display order */
      f = i - 1;
      pict_type = B_TYPE;
      n = (i-2)%M + 1; /* first B: n=1, second B: n=2, ... */
      forw_hor_f_code = motion_data[n].forw_hor_f_code;
      forw_vert_f_code = motion_data[n].forw_vert_f_code;
      back_hor_f_code = motion_data[n].back_hor_f_code;
      back_vert_f_code = motion_data[n].back_vert_f_code;
      sxf = motion_data[n].sxf;
      syf = motion_data[n].syf;
      sxb = motion_data[n].sxb;
      syb = motion_data[n].syb;
    }

    temp_ref = f - f0;
    frame_pred_dct = frame_pred_dct_tab[pict_type-1];
    q_scale_type = qscale_tab[pict_type-1];
    intravlc = intravlc_tab[pict_type-1];
    altscan = altscan_tab[pict_type-1];

    fprintf(statfile,"\nFrame %d (#%d in display order):\n",i,f);
    fprintf(statfile," picture_type=%c\n",ipb[pict_type]);
    fprintf(statfile," temporal_reference=%d\n",temp_ref);
    fprintf(statfile," frame_pred_frame_dct=%d\n",frame_pred_dct);
    fprintf(statfile," q_scale_type=%d\n",q_scale_type);
    fprintf(statfile," intra_vlc_format=%d\n",intravlc);
    fprintf(statfile," alternate_scan=%d\n",altscan);

    if (pict_type!=I_TYPE)
    {
      fprintf(statfile," forward search window: %d...%d / %d...%d\n",
        -sxf,sxf,-syf,syf);
      fprintf(statfile," forward vector range: %d...%d.5 / %d...%d.5\n",
        -(4<<forw_hor_f_code),(4<<forw_hor_f_code)-1,
        -(4<<forw_vert_f_code),(4<<forw_vert_f_code)-1);
    }

    if (pict_type==B_TYPE)
    {
      fprintf(statfile," backward search window: %d...%d / %d...%d\n",
        -sxb,sxb,-syb,syb);
      fprintf(statfile," backward vector range: %d...%d.5 / %d...%d.5\n",
        -(4<<back_hor_f_code),(4<<back_hor_f_code)-1,
        -(4<<back_vert_f_code),(4<<back_vert_f_code)-1);
    }

    sprintf(name,tplorg,f+frame0);
    readframe(name,neworg);

    if (fieldpic)
    {
      if (!quiet)
      {
        fprintf(stderr,"\nfirst field  (%s) ",topfirst ? "top" : "bot");
        fflush(stderr);
      }

      pict_struct = topfirst ? TOP_FIELD : BOTTOM_FIELD;

#ifndef SKIP_PREDICTION
      motion_estimation(oldorgframe[0],neworgframe[0],
                        oldrefframe[0],newrefframe[0],
                        neworg[0],newref[0],
                        sxf,syf,sxb,syb,mbinfo,0,0);

      predict(oldrefframe,newrefframe,predframe,0,mbinfo);
#endif
#ifndef SKIP_BLOCK_ENCODE
      dct_type_estimation(predframe[0],neworg[0],mbinfo);
      transform(predframe,neworg,mbinfo,blocks);
#endif

      putpict(neworg[0]);

#ifndef SKIP_BLOCK_DECODE
      for (k=0; k<mb_height2*mb_width; k++)
      {
        if (mbinfo[k].mb_type & MB_INTRA)
          for (j=0; j<block_count; j++)
            iquant_intra(blocks[k*block_count+j],blocks[k*block_count+j],
                         dc_prec,intra_q,mbinfo[k].mquant);
        else
          for (j=0;j<block_count;j++)
            iquant_non_intra(blocks[k*block_count+j],blocks[k*block_count+j],
                             inter_q,mbinfo[k].mquant);
      }

      itransform(predframe,newref,mbinfo,blocks);
#endif
      calcSNR(neworg,newref);
      stats();

      if (!quiet)
      {
        fprintf(stderr,"second field (%s) ",topfirst ? "bot" : "top");
        fflush(stderr);
      }

      pict_struct = topfirst ? BOTTOM_FIELD : TOP_FIELD;

      ipflag = (pict_type==I_TYPE);
      if (ipflag)
      {
        /* first field = I, second field = P */
        pict_type = P_TYPE;
        forw_hor_f_code = motion_data[0].forw_hor_f_code;
        forw_vert_f_code = motion_data[0].forw_vert_f_code;
        back_hor_f_code = back_vert_f_code = 15;
        sxf = motion_data[0].sxf;
        syf = motion_data[0].syf;
      }

#ifndef SKIP_PREDICTION
      motion_estimation(oldorgframe[0],neworgframe[0],
                        oldrefframe[0],newrefframe[0],
                        neworg[0],newref[0],
                        sxf,syf,sxb,syb,mbinfo,1,ipflag);

      predict(oldrefframe,newrefframe,predframe,1,mbinfo);
#endif
#ifndef SKIP_BLOCK_ENCOED
      dct_type_estimation(predframe[0],neworg[0],mbinfo);
      transform(predframe,neworg,mbinfo,blocks);
#endif

      putpict(neworg[0]);

#ifndef SKIP_BLOCK_DECODE
      for (k=0; k<mb_height2*mb_width; k++)
      {
        if (mbinfo[k].mb_type & MB_INTRA)
          for (j=0; j<block_count; j++)
            iquant_intra(blocks[k*block_count+j],blocks[k*block_count+j],
                         dc_prec,intra_q,mbinfo[k].mquant);
        else
          for (j=0;j<block_count;j++)
            iquant_non_intra(blocks[k*block_count+j],blocks[k*block_count+j],
                             inter_q,mbinfo[k].mquant);
      }

      itransform(predframe,newref,mbinfo,blocks);
#endif
      calcSNR(neworg,newref);
      stats();
    }
    else
    {
      pict_struct = FRAME_PICTURE;

      /* do motion_estimation
       *
       * uses source frames (...orgframe) for full pel search
       * and reconstructed frames (...refframe) for half pel search
       */

#ifndef SKIP_PREDICTION
      motion_estimation(oldorgframe[0],neworgframe[0],
                        oldrefframe[0],newrefframe[0],
                        neworg[0],newref[0],
                        sxf,syf,sxb,syb,mbinfo,0,0);

      predict(oldrefframe,newrefframe,predframe,0,mbinfo);
#endif
#ifndef SKIP_BLOCK_ENCODE
      dct_type_estimation(predframe[0],neworg[0],mbinfo);
      transform(predframe,neworg,mbinfo,blocks);
#endif
      putpict(neworg[0]);

#ifndef SKIP_BLOCK_DECODE
      for (k=0; k<mb_height*mb_width; k++)
      {
        if (mbinfo[k].mb_type & MB_INTRA)
          for (j=0; j<block_count; j++)
            iquant_intra(blocks[k*block_count+j],blocks[k*block_count+j],
                         dc_prec,intra_q,mbinfo[k].mquant);
        else
          for (j=0;j<block_count;j++)
            iquant_non_intra(blocks[k*block_count+j],blocks[k*block_count+j],
                             inter_q,mbinfo[k].mquant);
      }

      itransform(predframe,newref,mbinfo,blocks);
#endif
      calcSNR(neworg,newref);
      stats();
    }

    sprintf(name,tplref,f+frame0);
    writeframe(name,newref);

  }

  putseqend();
}