void LogLineBox::PrintTime()
{
  QString str;
  
  if(line_logline==NULL) {
    return;
  }
  switch(line_logline->timeType()) {
      case RDLogLine::Hard:
	line_time_label->setFont(line_bold_font);
	str=QString(tr("T"));
	line_time_label->setText(QString().sprintf("%s%s",(const char *)str,
		     (const char *)TimeString(line_logline->
					      startTime(RDLogLine::Logged))));
	line_time_label->setPalette(line_hard_palette);
	break;

      default:
	line_time_label->setFont(line_font);
	if(!line_logline->startTime(RDLogLine::Logged).isNull()) {
	  line_time_label->
	    setText(QString().sprintf("%s",
				      (const char *)TimeString(line_logline->
					   startTime(RDLogLine::Logged))));
	}
	else {
	  line_time_label->setText("");
	}
	line_time_label->setPalette(line_time_palette);
	break;
  }
}
Exemple #2
0
// Cpptraj::Interactive()
int Cpptraj::Interactive() {
  ReadLine inputLine;
  // By default when interactive do not exit on errors
  State_.SetNoExitOnError();
  // Open log file. If no name has been set, use default.
  CpptrajFile logfile_;
  if (logfilename_.empty())
    logfilename_.SetFileName("cpptraj.log");
  if (File::Exists(logfilename_)) {
    // Load previous history.
    if (logfile_.OpenRead(logfilename_)==0) {
      mprintf("\tLoading previous history from log '%s'\n", logfile_.Filename().full());
      std::string previousLine = logfile_.GetLine();
      while (!previousLine.empty()) {
        if (previousLine[0] != '#') {
          // Remove any newline chars.
          std::size_t found = previousLine.find_first_of("\r\n");
          if (found != std::string::npos)
            previousLine[found] = '\0';
          inputLine.AddHistory( previousLine.c_str() );
        }
        previousLine = logfile_.GetLine();
      }
      logfile_.CloseFile();
    }
  }
  logfile_.OpenAppend(logfilename_);
  if (logfile_.IsOpen())
    logfile_.Printf("# %s\n", TimeString().c_str());
  Command::RetType readLoop = Command::C_OK;
  while ( readLoop != Command::C_QUIT ) {
    if (inputLine.GetInput()) {
      // EOF (Ctrl-D) specified. If state is not empty, ask before exiting.
      if (!State_.EmptyState()) {
        if (inputLine.YesNoPrompt("EOF (Ctrl-D) specified but there are actions/"
                                  "analyses/trajectories queued. Really quit? [y/n]> "))
          break;
      } else
        break;
    }
    if (!inputLine.empty()) {
      readLoop = Command::Dispatch( State_, *inputLine );
      if (logfile_.IsOpen() && readLoop != Command::C_ERR) {
        logfile_.Printf("%s\n", inputLine.c_str());
        logfile_.Flush();
      }
    }
    // If state is not empty, ask before exiting.
    if (readLoop == Command::C_QUIT && !State_.EmptyState()) {
      if (inputLine.YesNoPrompt("There are actions/analyses/trajectories queued. "
                                "Really quit? [y/n]> "))
        break;
      else
        readLoop = Command::C_OK;
    }
  }
  logfile_.CloseFile();
  if (readLoop == Command::C_ERR) return 1;
  return 0;
}
QString cProgressText::getText(double progress)
{
	QString text;

	double progressLim = progress;
	if (progress < 0.0) progressLim = 1.0;
	if (progress > 1.0) progressLim = 1.0;

	qint64 time = timer.elapsed();

	if ((time > lastTimeForETA * 1.1L || time - lastTimeForETA > 60000)
			&& progress > lastProgressForETA)
	{
		bool filter = true;
		double renderingSpeedNew = (progress - lastProgressForETA) / (time - lastTimeForETA);
		if (renderingSpeed > 0 && filter) renderingSpeed = renderingSpeed
				+ (renderingSpeedNew - renderingSpeed) * 0.1;
		else renderingSpeed = renderingSpeedNew;

		lastProgressForETA = progress;
		lastTimeForETA = time;
	}

	qint64 timeToEnd;
	if (progressLim > 0.0 && renderingSpeed > 0)
	{
		timeToEnd = (1.0 - progressLim) / renderingSpeed;
	}
	else timeToEnd = -1;

	if (progressLim < 1.0)
	{
		text =
				QObject::tr("Done %1%, elapsed: %2, estimated to end: %3").arg(QString::number(progressLim
																																													 * 100.0,
																																											 'f',
																																											 2)).arg(TimeString(time)).arg(TimeString(timeToEnd));
	}
	else
	{
		text = QObject::tr("100% Done, total time: %3").arg(TimeString(time));
	}

	return text;
}
void ListLog::UpdateTimes(int removed_line,int num_lines)
{
    QTime time;
    QTime end_time;
    int line;
    RDLogLine *logline;

    RDListViewItem *next=(RDListViewItem *)list_log_list->firstChild();
    for(int i=0; i<(list_log_list->childCount()-1); i++) {
        if((line=next->text(15).toInt())>=removed_line) {
            line+=num_lines;
        }
        if((logline=list_log->logLine(line))!=NULL) {
            switch((RDLogLine::Status)next->text(16).toInt()) {
            case RDLogLine::Scheduled:
            case RDLogLine::Paused:
                switch(logline->timeType()) {
                case RDLogLine::Hard:
                    next->setText(1,QString(tr("T"))+
                                  TimeString(logline->startTime(RDLogLine::Logged)));
                    break;

                default:
                    if(!logline->startTime(RDLogLine::Predicted).isNull()) {
                        next->setText(1,
                                      TimeString(logline->startTime(RDLogLine::Predicted)));
                    }
                    else {
                        next->setText(1,"");
                    }
                    break;
                }
                break;

            default:
                next->setText(1,TimeString(logline->startTime(RDLogLine::Actual)));
                break;
            }
            next=(RDListViewItem *)next->nextSibling();
        }
    }
    UpdateHourSelector();
}
Exemple #5
0
void currentRadarFaultStatus::dumpStatus(char *dumpfilename)
{
  lock->get_lock();
  if (!dumpfilename)
    dumpfilename = defaultRadarFaultDumpName;
  
  //add .dat to dump file name for machine (mc) readable version
  strcpy(McRadarFaultDumpNameNew,dumpfilename);
  strcat(McRadarFaultDumpNameNew,".dat.new");
  strcpy(McRadarFaultDumpName,dumpfilename);
  strcat(McRadarFaultDumpName,".dat");
  
  FILE *dumpfile = fopen(dumpfilename, "w");
  if (!dumpfile)
    {
      cout << "currentRadarFaultStatus::dumpStatus FAILED to open file - "
	   << dumpfilename << endl;
      return;
    }
  FILE *mcdumpfile = fopen(McRadarFaultDumpNameNew, "w");
  if (!mcdumpfile)
    {
      cout << "currentRadarFaultStatus::dumpStatus FAILED to open machine readable file - "
	   << McRadarFaultDumpNameNew << endl;
      fclose(dumpfile);
      return;
    }
  char timestr[128];
  fprintf(dumpfile, "Radar Fault Status as at %s\n",
	  TimeString(time(NULL), timestr, true, true));
  fprintf(mcdumpfile,"radar,fault_no,fault_string,lateness,last_update,name,lat,long\n");
  
  
  map<int, radarFaultStatus>::iterator iter = faultStatus.begin();
  map<int, radarFaultStatus>::iterator iterend = faultStatus.end();
  while (iter != iterend)
    {
      iter->second.dumpStatus(time(NULL), dumpfile,mcdumpfile);
      iter++;
    }
  fclose(dumpfile);
  fclose(mcdumpfile);
  //rename so FAM wont trigger on start of file write
  if (rename(McRadarFaultDumpNameNew,McRadarFaultDumpName) == -1)
    {
      cerr << "\ncurrentRadarFaultStatus::dumpStatus: " << 
	"ERROR  Cannot rename machine readable output file from " << McRadarFaultDumpNameNew << " to " <<
	McRadarFaultDumpName << "\n";
      perror("currentRadarFaultStatus::dumpStatus");
    }
  lock->rel_lock();
}
String CommandDrawHeightmap::SaveHeightmap(Heightmap* heightmap, String suffix)
{
	String documentsPath = FileSystem::Instance()->SystemPathForFrameworkPath("~doc:");
	String folderPathname = documentsPath + "History";
	FileSystem::Instance()->CreateDirectory(folderPathname);
	folderPathname = folderPathname + "/Heightmap";
	FileSystem::Instance()->CreateDirectory(folderPathname);

	String filename = folderPathname + "/" + TimeString() + suffix + Heightmap::FileExtension();
	heightmap->Save(filename);

	return filename;
}
Exemple #7
0
FilePath HeightmapModificationCommand::SaveHeightmap(Heightmap* heightmap)
{
    FilePath documentsPath("~doc:/");

    FilePath folderPathname("~doc:/History/");
    FileSystem::Instance()->CreateDirectory(folderPathname);

    folderPathname = folderPathname + "Heightmap/";
    FileSystem::Instance()->CreateDirectory(folderPathname);

    FileList* fileList = new FileList(folderPathname);

    bool validFileName = false;
    String filename;
    String time = TimeString();
    uint32 num = 0;
    do
    {
        filename = time;
        if (num)
        {
            filename += Format(" (%d)", num);
        }
        filename += Heightmap::FileExtension();

        int32 i = 0;
        for (; i < fileList->GetCount(); ++i)
        {
            if (fileList->GetFilename(i) == filename)
            {
                ++num;
                break;
            }
        }
        if (i >= fileList->GetCount())
            validFileName = true;
    } while (!validFileName);

    FilePath saveFileName = folderPathname + filename;
    heightmap->Save(saveFileName);

    SafeRelease(fileList);

    return saveFileName;
}
Exemple #8
0
void cSkinClassicDisplayMenu::SetRecording(const cRecording *Recording)
{
  if (!Recording)
     return;
  const cRecordingInfo *Info = Recording->Info();
  const cFont *font = cFont::GetFont(fontOsd);
  int y = y2;
  cTextScroller ts;
  char t[32];
  snprintf(t, sizeof(t), "%s  %s", *DateString(Recording->start), *TimeString(Recording->start));
  ts.Set(osd, x1, y, x2 - x1, y3 - y, t, font, Theme.Color(clrMenuEventTime), Theme.Color(clrBackground));
  y += ts.Height();
  if (Info->GetEvent()->ParentalRating()) {
     cString buffer = cString::sprintf(" %s ", *Info->GetEvent()->GetParentalRatingString());
     const cFont *font = cFont::GetFont(fontSml);
     int w = font->Width(buffer);
     osd->DrawText(x3 - w, y, buffer, Theme.Color(clrMenuEventVpsFg), Theme.Color(clrMenuEventVpsBg), font, w);
     }
  y += font->Height();
  const char *Title = Info->Title();
  if (isempty(Title))
     Title = Recording->Name();
  ts.Set(osd, x1, y, x2 - x1, y3 - y, Title, font, Theme.Color(clrMenuEventTitle), Theme.Color(clrBackground));
  y += ts.Height();
  if (!isempty(Info->ShortText())) {
     const cFont *font = cFont::GetFont(fontSml);
     ts.Set(osd, x1, y, x2 - x1, y3 - y, Info->ShortText(), font, Theme.Color(clrMenuEventShortText), Theme.Color(clrBackground));
     y += ts.Height();
     }
  for (int i = 0; Info->GetEvent()->Contents(i); i++) {
      const char *s = Info->GetEvent()->ContentToString(Info->GetEvent()->Contents(i));
      if (!isempty(s)) {
         const cFont *font = cFont::GetFont(fontSml);
         ts.Set(osd, x1, y, x2 - x1, y3 - y, s, font, Theme.Color(clrMenuEventShortText), Theme.Color(clrBackground));
         y += ts.Height();
         }
      }
  y += font->Height();
  if (!isempty(Info->Description())) {
     textScroller.Set(osd, x1, y, x2 - x1, y3 - y, Info->Description(), font, Theme.Color(clrMenuEventDescription), Theme.Color(clrBackground));
     SetTextScrollbar();
     }
}
cString cPluginSvdrpdemo::SVDRPCommand(const char *Command, const char *Option, int &ReplyCode)
{
  if (strcasecmp(Command, "DATE") == 0) {
     // we use the default reply code here
     return DateString(time(NULL));
     }
  else if (strcasecmp(Command, "TIME") == 0) {
     ReplyCode = 901;
     if (*Option) {
        if (strcasecmp(Option, "RAW") == 0)
           return cString::sprintf("%ld\nThis is the number of seconds since the epoch\nand a demo of a multi-line reply", time(NULL));
        else {
           ReplyCode = 504;
           return cString::sprintf("Unknown option: \"%s\"", Option);
           }
        }
     return TimeString(time(NULL));
     }
  return NULL;
}
Exemple #10
0
void Cpptraj::Intro() {
  mprintf("\nCPPTRAJ: Trajectory Analysis. %s"
# ifdef MPI
          " MPI"
# endif
# ifdef _OPENMP
          " OpenMP"
# endif
          "\n    ___  ___  ___  ___\n     | \\/ | \\/ | \\/ | \n    _|_/\\_|_/\\_|_/\\_|_\n\n",
          CPPTRAJ_VERSION_STRING);
# ifdef MPI
  mprintf("| Running on %i threads\n",CpptrajState::WorldSize());
# endif
  mprintf("| Date/time: %s\n", TimeString().c_str());
  double available_mem = AvailableMemory_MB();
  // If < 0 could not be calculated correctly.
  if (available_mem > 0.0)
    mprintf(  "| Available memory: %g MB\n", AvailableMemory_MB());
  mprintf("\n");
}
Exemple #11
0
void cSkinCursesDisplayMenu::SetRecording(const cRecording *Recording)
{
  if (!Recording)
     return;
  const cRecordingInfo *Info = Recording->Info();
  int y = 2;
  cTextScroller ts;
  char t[32];
  snprintf(t, sizeof(t), "%s  %s", *DateString(Recording->Start()), *TimeString(Recording->Start()));
  ts.Set(osd, 0, y, ScOsdWidth, ScOsdHeight - y - 2, t, &Font, clrYellow, clrBackground);
  y += ts.Height();
  if (Info->GetEvent()->ParentalRating()) {
     cString buffer = cString::sprintf(" %s ", *Info->GetEvent()->GetParentalRatingString());
     osd->DrawText(ScOsdWidth - Utf8StrLen(buffer), y, buffer, clrBlack, clrYellow, &Font);
     }
  y += 1;
  const char *Title = Info->Title();
  if (isempty(Title))
     Title = Recording->Name();
  ts.Set(osd, 0, y, ScOsdWidth, ScOsdHeight - y - 2, Title, &Font, clrCyan, clrBackground);
  y += ts.Height();
  if (!isempty(Info->ShortText())) {
     ts.Set(osd, 0, y, ScOsdWidth, ScOsdHeight - y - 2, Info->ShortText(), &Font, clrYellow, clrBackground);
     y += ts.Height();
     }
  for (int i = 0; Info->GetEvent()->Contents(i); i++) {
      const char *s = Info->GetEvent()->ContentToString(Info->GetEvent()->Contents(i));
      if (!isempty(s)) {
         ts.Set(osd, 0, y, ScOsdWidth, ScOsdHeight - y - 2, s, &Font, clrYellow, clrBackground);
         y += 1;
         }
      }
  y += 1;
  if (!isempty(Info->Description())) {
     textScroller.Set(osd, 0, y, ScOsdWidth - 2, ScOsdHeight - y - 2, Info->Description(), &Font, clrCyan, clrBackground);
     SetTextScrollbar();
     }
}
void cSkinSTTNGDisplayMenu::SetRecording(const cRecording *Recording)
{
  if (!Recording)
     return;
  const cRecordingInfo *Info = Recording->Info();
  const cFont *font = cFont::GetFont(fontOsd);
  int xl = x3 + 5;
  int y = y3;
  cTextScroller ts;
  char t[32];
  snprintf(t, sizeof(t), "%s  %s", *DateString(Recording->start), *TimeString(Recording->start));
  ts.Set(osd, xl, y, x4 - xl, y4 - y, t, font, Theme.Color(clrMenuEventTime), Theme.Color(clrBackground));
  y += ts.Height();
  y += font->Height();
  const char *Title = Info->Title();
  if (isempty(Title))
     Title = Recording->Name();
  ts.Set(osd, xl, y, x4 - xl, y4 - y, Title, font, Theme.Color(clrMenuEventTitle), Theme.Color(clrBackground));
  y += ts.Height();
  if (!isempty(Info->ShortText())) {
     const cFont *font = cFont::GetFont(fontSml);
     ts.Set(osd, xl, y, x4 - xl, y4 - y, Info->ShortText(), font, Theme.Color(clrMenuEventShortText), Theme.Color(clrBackground));
     y += ts.Height();
     }
  y += font->Height();
  if (!isempty(Info->Description())) {
     int yt = y;
     int yb = y4 - Roundness;
     textScroller.Set(osd, xl, yt, x4 - xl, yb - yt, Info->Description(), font, Theme.Color(clrMenuEventDescription), Theme.Color(clrBackground));
     yb = yt + textScroller.Height();
     osd->DrawEllipse  (x1, yt - Roundness, x2, yt,             frameColor, -3);
     osd->DrawRectangle(x1, yt,             x2, yb,             frameColor);
     osd->DrawEllipse  (x1, yb,             x2, yb + Roundness, frameColor, -2);
     SetScrollbar();
     }
}
int OmConvertRunWav(omconvert_settings_t *settings, calc_t *calc)
{
	int retVal = EXIT_OK;
	int i;
	FILE *fp;
	WavInfo wavInfo = { 0 };
	char infoArtist[WAV_META_LENGTH] = { 0 };
	char infoName[WAV_META_LENGTH] = { 0 };
	char infoComment[WAV_META_LENGTH] = { 0 };
	char infoDate[WAV_META_LENGTH] = { 0 };
	double scale[10] = { 8.0 / 32768.0, 8.0 / 32768.0, 8.0 / 32768.0 };

	// Check config.
	if (settings->outFilename != NULL) { fprintf(stderr, "ERROR: Cannot output to WAV when input is WAV.\n"); return EXIT_CONFIG; }
	if (settings->infoFilename != NULL) { fprintf(stderr, "ERROR: Cannot output to info file when input is WAV.\n"); return EXIT_CONFIG; }

	fp = fopen(settings->filename, "rb");
	if (fp == NULL) { fprintf(stderr, "ERROR: Cannot open WAV file.\n"); return EXIT_NOINPUT; }

	wavInfo.infoArtist = infoArtist;
	wavInfo.infoName = infoName;
	wavInfo.infoComment = infoComment;
	wavInfo.infoDate = infoDate;

	if (!WavRead(&wavInfo, fp)) { fprintf(stderr, "ERROR: Problem reading WAV file format.\n"); fclose(fp); return EXIT_DATAERR; }
	if (wavInfo.bytesPerChannel != 2) { fprintf(stderr, "ERROR: WAV file format not supported (%d bytes/channel, expected 2).\n", wavInfo.bytesPerChannel); fclose(fp); return EXIT_DATAERR; }
	if (wavInfo.chans < 3 || wavInfo.chans > 16) { fprintf(stderr, "ERROR: WAV file format not supported (%d channels, expected at least 3 and no more than 16).\n", wavInfo.chans); fclose(fp); return EXIT_DATAERR; }
	if (wavInfo.freq < 1 || wavInfo.freq > 48000) { fprintf(stderr, "ERROR: WAV file format not supported (%d frequency).\n", wavInfo.freq); fclose(fp); return EXIT_DATAERR; }

	// Extract metadata
	char *line;
	#define MAX_FIELDS 32
	//char *artistLines[MAX_FIELDS]; int numArtistLines = 0;
	//for (line = strtok(wavInfo.infoArtist, "\n"); line != NULL; line = strtok(NULL, "\n")) { if (numArtistLines < MAX_FIELDS) { artistLines[numArtistLines++] = line; } }
	//char *nameLines[MAX_FIELDS]; int numNameLines = 0;
	//for (line = strtok(wavInfo.infoName, "\n"); line != NULL; line = strtok(NULL, "\n")) { if (numNameLines < MAX_FIELDS) { nameLines[numNameLines++] = line; } }
	char *commentLines[MAX_FIELDS]; int numCommentLines = 0;
	for (line = strtok(wavInfo.infoComment, "\n"); line != NULL; line = strtok(NULL, "\n")) { if (numCommentLines < MAX_FIELDS) { commentLines[numCommentLines++] = line; } }

	// Parse headers
	bool parsedTime = false;
	bool parsedScale[10] = { 0 };
	double startTime = 0;
	for (i = 0; i < numCommentLines; i++)
	{
		if (strncmp(commentLines[i], "Time:", 5) == 0) 
		{
			startTime = ParseTime(commentLines[i] + 5);
			fprintf(stderr, "Time: %s\n", TimeString(startTime));
			if (startTime > 0) { parsedTime = true; }
		}
		else if (strncmp(commentLines[i], "Scale-", 6) == 0 && (commentLines[i][6] >= '1' && commentLines[i][6] <= '9') && commentLines[i][7] == ':')
		{
			int chan = commentLines[i][6] - '1';
			double val = atof(commentLines[i] + 8);
			scale[chan] = val / 32768.0;
			fprintf(stderr, "Scale-%d: %f (scale[%d] = %f)\n", chan + 1, val, chan, scale[chan]);
			if (scale[chan] > 0) { parsedScale[chan] = true; }
		}
	}

	// Check we parsed the headers we need
	if (!parsedTime) { fprintf(stderr, "WARNING: Didn't successfully parse a 'Time' header (using zero).\n"); }
	for (i = 0; i < 3; i++)
	{
		if (!parsedScale[i]) { fprintf(stderr, "WARNING: Didn't successfully parse a 'Scale-%d' header (using defaults).\n", i + 1); }
	}

	int bufferSamples = wavInfo.freq * 60 * 60;	// 1 hour buffer
	short *buffer = malloc(sizeof(short) * wavInfo.chans * bufferSamples);
	if (buffer == NULL) { fprintf(stderr, "ERROR: Problem allocating buffer for WAV file (%d samples).\n", bufferSamples); fclose(fp); return EXIT_SOFTWARE; }

	// Init. CSV/SVM/WTV/PAEE
	int outputOk = CalcInit(calc, wavInfo.freq, startTime);
	if (!outputOk)
	{
		fprintf(stderr, "ERROR: No outputs.\n");
		retVal = EXIT_CONFIG;
	}
	else
	{
		fprintf(stderr, "Working...\n");
		unsigned long samplesOffset = 0;
		unsigned long samplesRemaining = wavInfo.numSamples;
		while (!feof(fp))
		{
			long offset = wavInfo.offset + ((sizeof(short) * wavInfo.chans) * samplesOffset);
			unsigned long samplesToRead = bufferSamples;
			if (samplesToRead > samplesRemaining) { samplesToRead = samplesRemaining; }
			if (samplesToRead <= 0) { break; }
			fseek(fp, offset, SEEK_SET);
			unsigned long samplesRead = fread(buffer, sizeof(short) * wavInfo.chans, samplesToRead, fp);
			if (samplesRead <= 0) { break; }
			samplesOffset += samplesRead;
			samplesRemaining -= samplesRead;

			double values[3];
			for (i = 0; i < (int)samplesRead; i++)
			{
				const short *v = buffer + i * wavInfo.chans;

				// Auxilliary channel is last channel
				bool valid = true;
				if (wavInfo.chans > 3)
				{
					uint16_t aux = v[wavInfo.chans - 1];
					if (aux & WAV_AUX_UNAVAILABLE) { valid = false; }
				}

				// Scaling from metadata
				values[0] = v[0] * scale[0];
				values[1] = v[1] * scale[1];
				values[2] = v[2] * scale[2];
				if (!CalcAddValue(calc, values, 0.0, valid))
				{
					fprintf(stderr, "ERROR: Problem writing calculations.\n");
					retVal = EXIT_IOERR;
					break;
				}
			}
		}
	}

	free(buffer);
	fclose(fp);

	CalcClose(calc);

	return retVal;
}
int OmConvertFindArrangement(om_convert_arrangement_t *arrangement, omconvert_settings_t *settings, omdata_t *omdata, omdata_session_t *session, om_convert_channel_t *channelPriority)
{
	memset(arrangement, 0, sizeof(om_convert_arrangement_t));
	arrangement->data = omdata;
	arrangement->session = session;
	arrangement->numChannels = 0;
	arrangement->numStreamIndexes = 0;
	arrangement->defaultRate = 1;

	// TODO: If the session contains an 'all axis' (synchronous) source, use that for timing for those regions (however, need to patch any holes and before/after values)

	// Determine the stream ordering
	arrangement->defaultRate = 1;
	int cpi;
	for (cpi = 0; channelPriority[cpi].stream != 0; cpi++)
	{
		int streamIndex = channelPriority[cpi].stream;
		int subchannel = channelPriority[cpi].subchannel;

		if (streamIndex < 0 || streamIndex >= OMDATA_MAX_STREAM) { fprintf(stderr, "WARNING: Ignoring stream index %d (0x%02x = %c).\n", subchannel, subchannel, subchannel); continue; }
		if (subchannel < 0 || subchannel > 9) { fprintf(stderr, "WARNING: Ignoring invalid sub-channel index %d.\n", subchannel); continue; }

		// Check each session
		omdata_stream_t *stream = &arrangement->session->stream[streamIndex];
		if (!stream->inUse) { continue; }
		if (!stream->segmentFirst || !stream->segmentLast) { continue; }

		// Check each segment for the maximum number of sub-channels
		omdata_segment_t *seg;
		int numSubChannels = 0;
		for (seg = stream->segmentFirst; seg != NULL; seg = seg->segmentNext)
		{
			if (seg->channels > arrangement->numChannels) { numSubChannels = seg->channels; }
			if (seg->sampleRate > arrangement->defaultRate) { arrangement->defaultRate = seg->sampleRate; }
		}

		// Check we have the subchannel
		if (subchannel >= numSubChannels) { continue; }

		// Assign channel
		if (arrangement->numChannels < OMDATA_MAX_CHANNELS)
		{
			arrangement->channelAssignment[arrangement->numChannels].stream = streamIndex;
			arrangement->channelAssignment[arrangement->numChannels].subchannel = subchannel;

			// Track which streams need updating
			bool found = false;
			int j;
			for (j = 0; j < arrangement->numStreamIndexes; j++)
			{
				if (arrangement->streamIndexes[j] == streamIndex) { found = true; break; }
			}
			if (!found && arrangement->numStreamIndexes < OMDATA_MAX_CHANNELS)
			{
				arrangement->streamIndexes[arrangement->numStreamIndexes] = streamIndex;
				arrangement->numStreamIndexes++;
			}


			fprintf(stderr, "DEBUG: Output channel %d is stream '%c' channel %d...\n", arrangement->numChannels, streamIndex, subchannel);

			arrangement->numChannels++;
		}

	}

	arrangement->startTime = session->startTime;
	arrangement->endTime = session->endTime;

	// Clamp to record time if close
	double limit = 15.000;
	if (omdata->metadata.recordingStart < omdata->metadata.recordingStop && (omdata->metadata.recordingStop - omdata->metadata.recordingStart) > 2 * limit)
	{
		if (fabs(arrangement->startTime - omdata->metadata.recordingStart) < limit) { arrangement->startTime = omdata->metadata.recordingStart; fprintf(stderr, "Clamping session to recording start time (%s)...\n", TimeString(omdata->metadata.recordingStart)); }
		if (fabs(arrangement->endTime - omdata->metadata.recordingStop) < limit) { arrangement->endTime = omdata->metadata.recordingStop; fprintf(stderr, "Clamping session to recording stop time (%s)...\n", TimeString(omdata->metadata.recordingStop)); }
	}

	arrangement->duration = arrangement->endTime - arrangement->startTime;

	return 0;
}
void ListLog::RefreshItem(RDListViewItem *l,int line)
{
    int lines[TRANSPORT_QUANTITY];
    bool is_next=false;

    RDLogLine *log_line=list_log->logLine(line);
    if(log_line==NULL) {
        return;
    }
    switch(log_line->timeType()) {
    case RDLogLine::Hard:
        l->setText(1,QString("T")+
                   TimeString(log_line->startTime(RDLogLine::Logged)));
        l->setText(8,QString("T")+
                   TimeString(log_line->startTime(RDLogLine::Logged)));
        for(int i=0; i<list_log_list->columns(); i++) {
            l->setTextColor(i,LOG_HARDTIME_TEXT_COLOR,QFont::Bold);
        }
        l->setText(14,"N");
        break;
    default:
        if(!log_line->startTime(RDLogLine::Logged).isNull()) {
            l->setText(8,TimeString(log_line->startTime(RDLogLine::Logged)));
        }
        else {
            l->setText(8,"");
        }
        for(int i=0; i<list_log_list->columns(); i++) {
            l->setTextColor(i,LOG_RELATIVE_TEXT_COLOR,QFont::Normal);
        }
        l->setText(14,"");
        break;
    }
    switch(log_line->transType()) {
    case RDLogLine::Play:
        l->setText(3,tr("PLAY"));
        l->setTextColor(3,l->textColor(2),QFont::Normal);
        break;
    case RDLogLine::Stop:
        l->setText(3,tr("STOP"));
        l->setTextColor(3,l->textColor(2),QFont::Normal);
        break;
    case RDLogLine::Segue:
        l->setText(3,tr("SEGUE"));
        if(log_line->hasCustomTransition()) {
            l->setTextColor(3,RD_CUSTOM_TRANSITION_COLOR,QFont::Bold);
        }
        else {
            if(log_line->timeType()==RDLogLine::Hard) {
                l->setTextColor(3,l->textColor(2),QFont::Bold);
            }
            else {
                l->setTextColor(3,l->textColor(2),QFont::Normal);
            }
        }
        break;

    default:
        break;
    }
    switch(log_line->type()) {
    case RDLogLine::Cart:
        switch(log_line->source()) {
        case RDLogLine::Tracker:
            l->setPixmap(0,*list_track_cart_map);
            break;

        default:
            l->setPixmap(0,*list_playout_map);
            break;
        }
        l->setText(2,RDGetTimeLength(log_line->effectiveLength(),false,false));
        l->setText(4,QString().
                   sprintf("%06u",log_line->cartNumber()));
        if((log_line->source()!=RDLogLine::Tracker)||
                log_line->originUser().isEmpty()||
                (!log_line->originDateTime().isValid())) {
            l->setText(5,log_line->title());
        }
        else {
            l->setText(5,QString().
                       sprintf("%s -- %s %s",
                               (const char *)log_line->title(),
                               (const char *)log_line->originUser(),
                               (const char *)log_line->originDateTime().
                               toString("M/d hh:mm")));
        }
        l->setText(6,log_line->artist());
        l->setText(7,log_line->groupName());
        l->setTextColor(7,log_line->groupColor(),QFont::Bold);
        l->setText(9,log_line->album());
        l->setText(10,log_line->label());
        l->setText(11,log_line->client());
        l->setText(12,log_line->agency());
        break;

    case RDLogLine::Macro:
        l->setPixmap(0,*list_macro_map);
        l->setText(2,RDGetTimeLength(log_line->forcedLength(),false,false));
        l->setText(4,QString().
                   sprintf("%06u",log_line->cartNumber()));
        l->setText(5,log_line->title());
        l->setText(6,log_line->artist());
        l->setText(7,log_line->groupName());
        l->setTextColor(7,log_line->groupColor(),QFont::Bold);
        l->setText(9,log_line->album());
        l->setText(10,log_line->label());
        l->setText(11,log_line->client());
        l->setText(12,log_line->agency());
        break;

    case RDLogLine::Marker:
        l->setPixmap(0,*list_notemarker_map);
        l->setText(2,"00:00");
        l->setText(4,tr("MARKER"));
        l->setText(5,RDTruncateAfterWord(log_line->markerComment(),5,true));
        l->setText(13,log_line->markerLabel());
        break;

    case RDLogLine::Track:
        l->setPixmap(0,*list_mic16_map);
        l->setText(2,"00:00");
        l->setText(4,tr("TRACK"));
        l->setText(5,RDTruncateAfterWord(log_line->markerComment(),5,true));
        break;

    case RDLogLine::MusicLink:
        l->setPixmap(0,*list_music_map);
        l->setText(2,"00:00");
        l->setText(4,tr("LINK"));
        l->setText(5,tr("[music import]"));
        break;

    case RDLogLine::TrafficLink:
        l->setPixmap(0,*list_traffic_map);
        l->setText(2,"00:00");
        l->setText(4,tr("LINK"));
        l->setText(5,tr("[traffic import]"));
        break;

    case RDLogLine::Chain:
        l->setPixmap(0,*list_chain_map);
        l->setText(2,"");
        l->setText(4,tr("CHAIN TO"));
        l->setText(5,log_line->markerLabel());
        l->setText(6,RDTruncateAfterWord(log_line->markerComment(),5,true));
        break;

    default:
        break;
    }
    l->setText(14,QString().sprintf("%d",log_line->id()));
    l->setText(15,QString().sprintf("%d",line));
    l->setText(16,QString().sprintf("%d",log_line->status()));
    SetPlaybuttonMode(ListLog::ButtonDisabled);
    list_modify_button->setDisabled(true);
    switch(log_line->state()) {
    case RDLogLine::NoCart:
        if(log_line->type()==RDLogLine::Cart) {
            l->setPixmap(0,NULL);
            l->setText(8,"");
            l->setText(3,"");
            l->setText(5,tr("[CART NOT FOUND]"));
        }
        break;

    case RDLogLine::NoCut:
        if(log_line->type()==RDLogLine::Cart) {
            l->setText(6,tr("[NO VALID CUT AVAILABLE]"));
        }
        break;

    default:
        if((log_line->type()==RDLogLine::Cart)&&
                (log_line->effectiveLength()==0)) {
            l->setText(6,tr("[NO AUDIO AVAILABLE]"));
        }
        break;
    }
    list_log->transportEvents(lines);
    for(int i=0; i<TRANSPORT_QUANTITY; i++) {
        if(line==lines[i]) {
            is_next=true;
        }
    }
    UpdateColor(line,is_next);
}
Exemple #16
0
void radarFaultStatus::dumpStatus(time_t dumptime,
				  FILE *dumpfile, 
				  FILE *mcdumpfile, 
				  bool faulty_only,
				  bool show_last)
{
  char timestr[128], timestr2[128], timestr3[128];
  char latestrbuff[128];
  char faultStr[128];
  
  if (!dumpfile || !mcdumpfile ||
      (faulty_only && (faultNo == 0))) // skip non faulty
    return;

  if (faultNo) {
    fprintf(dumpfile, "%8s(%2d) **FAULT %d %s\n"
	    "     ==>Since %s Updated %s %s\n",
	    stn_name(radar), radar, faultNo, lastFaultStr.c_str(),
	    TimeString(lastStartTime, timestr, true, true),
	    TimeString(lastUpdateTime, timestr2, true, true),
	    latenessString(dumptime - lastUpdateTime - 600, latestrbuff));

    //remove commas so they wont break our comma separated file
    strcpy(faultStr,lastFaultStr.c_str());
    char* charpos;
    while((charpos = strchr(faultStr,','))) *charpos = ';';
    
    if (dumptime - lastUpdateTime - 600 <= 900)
      fprintf(mcdumpfile, "%2d, %d, %s, OK, %ld, %s, %f, %f\n",
	      radar, faultNo, faultStr,
	      lastUpdateTime,stn_name(radar),StnRec[radar].Lat(),StnRec[radar].Lng());
    else 
      fprintf(mcdumpfile, "%2d, %d, %s, LATE, %ld, %s, %f, %f\n",
	      radar, faultNo, faultStr,
	      lastUpdateTime,stn_name(radar),StnRec[radar].Lat(),StnRec[radar].Lng());
    
  }
  
  else
    {
      if (show_last && lastStartTime)
	fprintf(dumpfile, "%8s(%2d) OK Updated %s %s\n"
		"     ==>Last fault %d %s\n"
		"     ==>Started %s Cleared %s\n",
		stn_name(radar), radar, TimeString(lastUpdateTime, timestr3, true, true),
		latenessString(dumptime - lastUpdateTime - 600, latestrbuff),
		prevFaultNo, lastFaultStr.c_str(),
		TimeString(lastStartTime, timestr, true, true),
		TimeString(lastResolvedTime, timestr2, true, true));
      else
	fprintf(dumpfile, "%8s(%2d) OK Updated %s %s\n",
		stn_name(radar), radar,
		TimeString(lastUpdateTime, timestr2, true, true),
		latenessString(dumptime - lastUpdateTime - 600, latestrbuff));

      if (dumptime - lastUpdateTime - 600 <= 900)
	fprintf(mcdumpfile, "%2d, %d, NOFAULT, OK, %ld, %s, %f, %f\n",
		radar, faultNo, 
		lastUpdateTime,stn_name(radar),StnRec[radar].Lat(),StnRec[radar].Lng()); 
      else 
	fprintf(mcdumpfile, "%2d, %d, NOFAULT, LATE, %ld, %s, %f, %f\n",
		radar, faultNo, 
		lastUpdateTime,stn_name(radar),StnRec[radar].Lat(),StnRec[radar].Lng());
    }
  
  
  
}
Exemple #17
0
cString cEvent::GetEndTimeString(void) const
{
  return TimeString(startTime + duration);
}
Exemple #18
0
int FloatSearch(int n, int d, int delta, int r, TSubset *bset, int detail, int n_classes, fx_select_t *sel, char **file_names, int n_splits, cType classifier, char *cparam, int float_level) {
  /* a non-redundand coding of subset configurations is used.
     For easier understanding imagine our goal is to find a subset by exhaustive search,
     when d=5 and n=12
    - initial configuration is 111110000000   (actually stored in "bin" field)
    - in every step: a) find the leftmost block of 1's
                     b) shift its rightmost 1 to the right
                     c) shift the rest of this block to the left boundary (if it is not there)
    - this algorithm generates increasingly all binary representations of subsets
    - in context of floating search this algorithm is used for computation of generalized steps
      (in case of simple SFFS and simple SFBS only single-feature configurations are tested)
    - for purposes of floating search more identifiers than 0 and 1 are used to
      identify temporarily freezed features etc. (2,-1)
    - because of possibility to exchange meanings of 0 and 1 it was suitable to
      incorporate both forward and backward versions of floating search into one procedure
  */

  int *bin;   /* of size n, stores 0/1 information on currently selected features */
  int *index; /* of size d, it is computed from bin, stores indexes of selected features */
  int *bestset; double bestvalue; /* best subset */
  int *globalbestset; double *globalbestvalue; /* so-far best subsets in all dimensions */
  int wasthebest; /* indicates, if a better subset has been found during last step*/
  double value=0;
  int sumrint;
  int i;
  int sumr;     /* current subset size */
  int zmenasumr; /* how to change sumr (when changing direction of search): -2,-1,+1,+2 steps */
  int rr;
  int pom;
  int beg,piv;  /* beg - beginning of block of identifiers, piv - "pivot" - last identifier in a block */
  int stopex;    /* identifies end of internal exhaustive search */
  int stopfloat; /* identifies end of it all */
  int stopfloatmez=0;  /* identifies the dimension, for which the algorithm should end */
  int id0=0,id2=2;  /* these identifiers (0 and 2) are exchanged in case of backward search */
  int sbs=0;    /* 0=sfs, 1=sbs current search direction*/
  int vykyv=0; // stores current backtracking depth (+forward,-backward)
  float vykyvmez=0.0; // predicted delta estimate
  int vykyvcount=0; // number of direction changes (needed for delta averaging)
  int sfbs=0;   /* 0=sffs, 1=sfbs main search direction */
  int error=0;
  long globcit/*,cit*/,kombcit;
//  int timcet=0;
    double temp=-1;
  int best=0;
  int n_floats=0;
  
  time_t tbegin,telp,tlast;   /* for measuring computational time only */
//  time_t tact;
  
  tbegin=time(NULL);
  tlast=tbegin;

	if (float_level ==-1)
		float_level=n;

  if(r<0) { /* indicates SFBS, first stage will be SBS */
    sfbs=1; sbs=1; id0=2; id2=0; r=-r;
    if(delta==0) 
    	stopfloatmez=1;
	else 
		if(delta>0) {
			stopfloatmez=d-delta; 
			if(stopfloatmez<1) 
				stopfloatmez=1;
			}
    // for delta -1 and -2, stopfloatmez will be set later
  }
  else { /* indicates SFFS, first stage will be SFS */
    if(delta==0) 
    	stopfloatmez=n;
    else 
    	if(delta>0) {
    		stopfloatmez=d+delta; 
    		if(stopfloatmez>n) 
    			stopfloatmez=n;
    	}
    // for delta -1 and -2, stopfloatmez will be set later
  }
  vykyv=0;
  vykyvmez=0.0;
  vykyvcount=0;

  if((d<1)||(d>n)){
	return(24);
  } /* nothing to search for */
  
  if((r<1)||(r>=n)||((!sfbs)&&(r>=d))||((sfbs)&&(r>=n-d))){
	return(25);} /* no sense */
  if(n<2){
	return(30);
  }
  
  if((bin=(int *) rs_malloc((n+1)*sizeof(int),"bin, FloatSearch"))==NULL) {
	return(3);
	}
  if((index=(int *) rs_malloc(n*sizeof(int),"index, FloatSearch"))==NULL) {
  	rs_free(bin);
    return(3);
    }
  if((bestset=(int *) rs_malloc(n*sizeof(int),"bestset, FloatSearch"))==NULL) {
  	rs_free(index);
  	rs_free(bin);
  	return(3);
  	}
  if((globalbestset=(int *) rs_malloc(((n*(n+1L))/2L)*sizeof(int),"globalbestset, FloatSearch"))==NULL) {
  	rs_free(bestset);
  	rs_free(index);
  	rs_free(bin);
  	return(3);
  	}
  if((globalbestvalue=(double *) rs_malloc(n*sizeof(double),"globalbestvalue, FloatSearch"))==NULL) {
  	rs_free(globalbestset);
  	rs_free(bestset);
  	rs_free(index);
  	rs_free(bin);
  	return(3);
  	}
  /* k-th set of size k is stored at [(k*(k-1))/2] */
  for(i=0;i<(n*(n+1))/2;i++) 
  	globalbestset[i]=0;
  for(i=0;i<n;i++) 
  	globalbestvalue[i]=-SAFEUP;

  for(i=0;i<=n;i++) 
  	bin[i]=id0; /* bin[n]=id0 for testing the end */

  rr=r; /* initial generalization level */
  if(sfbs) {
      sumr=n-rr; 
      if(detail&STANDARD) {
           if(r>1) 
           	printf("Generalized "); 
           printf("Sequential Floating Backward Search"); 
           if(r>1) {
               printf(" (r=%d)",r);
           } 
           printf(":\n");
      }
  }          
  else {
      sumr=rr; 
      if(detail&STANDARD){
          if(r>1) 
          	printf("Generalized "); 
          printf("Sequential Floating Forward Search"); 
          if(r>1) {
              printf(" (r=%d)",r);
          } 
          printf(":\n");
      }
  }
  
  if(detail&STANDARD) {
  	printf("started on "); 
  	printf(ctime(&tbegin));}
  stopfloat=0;
  
//  hcreate(100000); //initialize hash table for set->result mapping
 
  do {

    for(i=0;i<n;i++) 
    	bestset[i]=0; 
    bestvalue=-SAFEUP;
    pom=rr;
    for(i=0;((pom>0)&&(i<n));i++) 
    	if(bin[i]==id0) {
    		bin[i]=id2; 
    		pom--;
    	} /* initialize bin for exhaustive step */
    sumrint=sumr*sizeof(int);
    globcit=0;
    // estimate the number of steps
    kombcit=1;
    if(sbs) 
    	pom=sumr+rr; 
    else 
    	pom=n-(sumr-rr); 
    for(i=0;i<rr;i++) 
    	kombcit*=pom-i; 
    for(i=2;i<=rr;i++) 
    	kombcit/=i;

    stopex=0;
    do {
      pom=0; /* convert "bin" to "index" */
      for(i=0;i<sumr;i++) {
	    while(bin[pom]<=0) 
	    	pom++;
	    index[i]=pom;
	    pom++;
      }



      /* ----------- following block serves only for outputting the information about current algorithm state ----------*/
      /* ------------it may be discarded */
//      if(!(globcit%PERCENTDETAIL)){
//          tact=time(NULL);
//          if(difftime(tact,tlast)>SECONDS) {
//              tlast=tact; 
//              timcet=true;
//              // test cancel
//              if((error=GetStopFlag())!=0) {
//              	rs_free(globalbestvalue);
//              	rs_free(globalbestset);
//              	rs_free(bestset);
//              	rs_free(index);
//              	rs_free(bin);
//              	return(error);
//              }
//          }
//      }
//      if((!globcit)/*||(!(globcit%cit))*/||timcet) {
//          pom = (int)floor((100.0*(double)sumr)/(double)n);
//          ProcessTextCS->Acquire();
//          if(sbs) ProcessText[0]='v'; else ProcessText[0]='^';
//          sprintf(ProcessText+1," k=%d, (%ld/%ld), delta=%d:%d, Cr=%g",sumr,globcit,kombcit,delta,(int)(DELTAMUL*vykyvmez+DELTAADD),globalbestvalue[d-1]);
//          ProcessTextCS->Release();
//          SetProcessFlag(pom);
//          if(detail&PERCENT) {
//              printtext("\r");
//              ProcessTextCS->Acquire();
//              printtext(ProcessText); 
//              ProcessTextCS->Release();
//              printtext(" ");
//          }
//      }
//      timcet=false;
//      globcit++;
      /* ------------previous block may be discarded */
      /* ----------- previous block served only for outputting the information about current algorithm state ----------*/      
 


      // result of criterion function should be stored to "value". When calling the criterion function, "index" field
      // contains indexes (beginning by 0) of features in the subset being currently tested, having dimension "sumr"
      if((error=Criterion(&value,index,sumr, n_classes, sel, file_names,n_splits,classifier, cparam))!=0) {
      	rs_free(globalbestvalue);
      	rs_free(globalbestset);
      	rs_free(bestset);
      	rs_free(index);
      	rs_free(bin);
      	return(error);
      }
      if(value>bestvalue) {
	    memcpy(bestset,index,sumrint);
	    bestvalue=value;
      }

      /* finding the new configuration during internal exhaustive step */
      for(beg=0;bin[beg]!=id2;beg++)
      	;
      for(piv=beg;(piv<n)&&(bin[piv]!=id0);piv++)
      	;
      if(piv==n) 
      	stopex=1;
      else {
	    pom=piv; /* remember the position of first 0 on the right */
	    do 
	    	piv--; 
	    while(bin[piv]!=id2); /* find a real pivot */
	    bin[piv]=id0; 
	    bin[pom]=id2; /* shift pivot to the right */
	    pom=0;
	    /* run "pom" from left, "piv" from right. the 0,2 pairs found are changed to 2,0 */
	    do 
	    	piv--; 
	    while((piv>0)&&(bin[piv]!=id2));
	    while((pom<piv)&&(bin[pom]!=id0))
	    	pom++;
	    while(piv-pom>0)
	    {
	      bin[piv]=id0; bin[pom]=id2;
	      do 
	      	piv--; 
	      while((piv>0)&&(bin[piv]!=id2));
	      while((pom<piv)&&(bin[pom]!=id0))
	      	pom++;
	    }
      }
    }while(!stopex);

    if(bestvalue>globalbestvalue[sumr-1]) {// sumr is from interval <1,n>
      memcpy(&globalbestset[(sumr*(sumr-1))/2],bestset,sumrint);
      globalbestvalue[sumr-1]=bestvalue;
      wasthebest=1;
    }
    else 
    	wasthebest=0;

	if (detail&STANDARD) {
		fprintf(stderr,"current best set of size %d and goodness %g:\n",sumr,bestvalue);
		printFset(bestset,sumr);
	}

    if(sfbs) {
      if(sbs) /* last step was sbs */ {
	    if(sumr<n-r) /* if adding is possible, prepare sfs */ {
	      for(i=0;i<n;i++) 
	      	bin[i]=0; /* conversion to sfs format */
	      for(i=0;i<sumr;i++) 
	      	bin[bestset[i]]=1;
	      sbs=0; 
	      id0=0; 
	      id2=2;
	      zmenasumr=1;
	    }
	    else {
	      zmenasumr=-1; /* otherwise stay by sbs */
	      for(i=0;i<n;i++) 
	      	bin[i]=-1;
	      for(i=0;i<sumr;i++) 
	      	bin[bestset[i]]=2; /* freeze the change */
	    }
      }
      else /* last step was sfs */ {
	    if(wasthebest) /* better solution was found */ {
	      if(sumr<n-r) {
	        zmenasumr=1; /* repeat sfs */
	        for(i=0;i<n;i++) 
	        	bin[i]=0;
	        for(i=0;i<sumr;i++) 
	        	bin[bestset[i]]=1; /* freeze the change */
	      }
	      else { /* nothing may be added, switch to sbs */
	        for(i=0;i<n;i++) 
	        	bin[i]=-1; 
	        for(i=0;i<sumr;i++) 
	        	bin[bestset[i]]=2;
	        sbs=1; 
	        id0=2; 
	        id2=0;
	        zmenasumr=-1;
	      }
	    }
	    else /* no improvement during last step (sfs) */ {
	      /* change "bin" for sbs but after the change of "sumr" */
	      sbs=1; 
	      id0=2; 
	      id2=0;
	      zmenasumr=-2; /* forget last step and perform one new sbs step */
	    }
      }
      /* actualize sumr and rr */
      if(zmenasumr==1) {
      	if((sumr==d)&&((n-d)%r!=0)) {
      		sumr=d+(n-d)%r; 
      		rr=(n-d)%r;
      	} 
      	else {
      		sumr+=r; 
      		rr=r;
      	}
        if(vykyv>0) 
        	vykyv+=rr; // continue
        else vykyv=rr; // begin           
      }
      else /* zmenasumr== -1 or -2 */ {
      	if((sumr>d)&&(sumr-r<d)) {
      		sumr=d; 
      		rr=(n-d)%r;
      	} 
      	else {
      		sumr-=r; 
      		rr=r;
      	}
        if(vykyv>0) { // end of going up
        	if(delta==-1){ //averaging
            	vykyvmez=(vykyvcount*vykyvmez+vykyv)/(vykyvcount+1);
                vykyvcount++;
            }
            else{ // maximization
            	if(vykyv>vykyvmez) 
            		vykyvmez=vykyv;
            }
        }
        vykyv=0;
      }
      if(zmenasumr==-2) /* once more */ {
	    for(i=0;i<n;i++) 
	    	bin[i]=-1; /* change to sbs with changed "sumr" */
	    pom=(sumr*(sumr-1))/2;
	    for(i=0;i<sumr;i++) 
	    	bin[globalbestset[pom+i]]=2;
	    if((sumr>d)&&(sumr-r<d)) {
	    	sumr=d; 
	    	rr=(n-d)%r;
	    } 
	    else {
	    	sumr-=r; 
	    	rr=r;
	    }
            // no change in direction
      }

      if(delta<0){
      	stopfloatmez=d-DELTAMUL*vykyvmez-DELTAADD; 
      	if(stopfloatmez<1) 
      		stopfloatmez=1;
      }
      if(sumr<stopfloatmez) 
      	stopfloat=1; /* end if delta reached */
    }
    else /* sffs */ {
      if(sbs) /* last step was sbs */ {
	    if(wasthebest && n_floats < float_level) /* a better subset was found */ {
	      if(sumr>r && n_floats < float_level) {
	        zmenasumr=-1; /* so repeat sbs */
	        for(i=0;i<n;i++) 
	        	bin[i]=-1;
	        for(i=0;i<sumr;i++) 
	        	bin[bestset[i]]=2; /* freeze changes */
	        n_floats++;
	      }
	      else if (wasthebest && n_floats >= float_level) {
	        for(i=0;i<n;i++) 
	        	bin[i]=0; 
	        for(i=0;i<sumr;i++) 
	        	bin[bestset[i]]=2; /* freeze changes */
	        sbs=0; 
	        id0=0; 
	        id2=2;
	        zmenasumr=1;
	      	n_floats=0;
	      }
	      else { /* nothing to remove, change to sfs */
	        for(i=0;i<n;i++) 
	        	bin[i]=0; 
	        for(i=0;i<sumr;i++) 
	        	bin[bestset[i]]=1;
	        sbs=0; 
	        id0=0; 
	        id2=2;
	        zmenasumr=1;
	        n_floats=0;
	      }
	    }
	    else /* no improvement during last step (sbs) */ {
	      /* change to "bin" for sfs later after "sumr" gets its original value */
	      sbs=0; 
	      id0=0; 
	      id2=2;
	      zmenasumr=2; /* forget last step and perform one new sfs step */
	    }
      }
      else /* last step was sfs */ {
	    if(sumr>r) /* if removing is possible, prepare sbs */ {
	      for(i=0;i<n;i++) 
	      	bin[i]=-1;
	      for(i=0;i<sumr;i++) 
	      	bin[bestset[i]]=2;
	      sbs=1; 
	      id0=2; 
	      id2=0;
	      zmenasumr=-1;
	    }
	    else {
	      zmenasumr=1; /* othervise stay by sfs */
	      for(i=0;i<n;i++) 
	      	bin[i]=0;
	      for(i=0;i<sumr;i++) 
	      	bin[bestset[i]]=1; /* freeze changes */
	    }
      }
      /* renew sumr and rr */
      if(zmenasumr==-1) {
      	if((sumr==d)&&(d%r!=0)) {
      		sumr=d-d%r; 
      		rr=d%r;
      	} 
      	else {
      		sumr-=r; 
      		rr=r;
      	}
        if(vykyv<0) 
        	vykyv-=rr; // continue
        else 
        	vykyv=-rr; // begin
      }
      else /* zmenasumr== 1 or 2 */ {
      	if((sumr<d)&&(sumr+r>d)) {
      		sumr=d; 
      		rr=d%r;
      	} 
      	else {
      		sumr+=r; 
      		rr=r;
      	}
        if(vykyv<0) { // end of going down
        	if(delta==-1){ //averaging
            	vykyvmez=(vykyvcount*vykyvmez+(-vykyv))/(vykyvcount+1);
                vykyvcount++;
            }
            else{ // maximizing
            	if(-vykyv>vykyvmez) 
            		vykyvmez=-vykyv;
            }
        }
        vykyv=0;
      }
      if(zmenasumr==2) /* once more and renew "bin"*/ {
	    for(i=0;i<n;i++) 
	    	bin[i]=0; /* change to sfs format now with actualized "sumr" */
	    pom=(sumr*(sumr-1))/2;
	    for(i=0;i<sumr;i++) 
	    	bin[globalbestset[pom+i]]=1;
	    if((sumr<d)&&(sumr+r>d)) {
	    	sumr=d; 
	    	rr=d%r;
	    } 
	    else {
	    	sumr+=r; 
	    	rr=r;
	    }
            // no direction change
      }

      if(delta<0) {
      	stopfloatmez=d+DELTAMUL*vykyvmez+DELTAADD; 
      	if(stopfloatmez>n) 
      		stopfloatmez=n;
      }
      if(sumr>stopfloatmez) 
      	stopfloat=1; /* end if delta reached */
    }


  } while(!stopfloat);


  telp=time(NULL); 
  TimeString(bset->dobavypoctu,difftime(telp,tbegin));

  /* 
   * modified by T. Vogt, 17.04.2007:
   * return the feature set with the highest evaluation and fewest features
   */
  
	for (i=0;i<d;i++) {
  	if (globalbestvalue[i]>temp) {
  		best=i;
  		temp=globalbestvalue[i];
  	}
  }
  d=best+1;

  pom=(d*(d-1))/2;
  bset->subsetsize=d;
  if((bset->featureset=(int *) rs_malloc(d*sizeof(int),"bset->featureset, FloatSearch"))==NULL) {
  	rs_free(globalbestvalue);
  	rs_free(globalbestset);
  	rs_free(bestset);
  	rs_free(index);
  	rs_free(bin);
  	return(3);
  }
  
  if (shift_indexes(sel,globalbestset+pom,&(bset->featureset),d))
  	return (3);

  bset->critvalue=globalbestvalue[d-1];
  
  rs_free(globalbestset);
  rs_free(globalbestvalue);
  rs_free(bestset);
  rs_free(index);
  rs_free(bin);
//  hdestroy();
  return(0);
}
int OmConvertRunConvert(omconvert_settings_t *settings, calc_t *calc)
{
	int retVal = EXIT_OK;
	omdata_t omdata = { 0 };
	om_convert_arrangement_t arrangement = { 0 };

	// Output information file
	FILE *infofp = NULL;
	if (settings->infoFilename != NULL)
	{
		infofp = fopen(settings->infoFilename, "wt");
		if (infofp == NULL)
		{
			fprintf(stderr, "ERROR: Cannot open output information file: %s\n", settings->infoFilename);
			return EXIT_CANTCREAT;
		}
	}
		
	// Load input data
	if (!OmDataLoad(&omdata, settings->filename))
	{
		const char *msg = "ERROR: Problem loading file.\n";
		fprintf(stderr, msg);
		fprintf(stdout, msg);
		return EXIT_DATAERR;
	}
	fprintf(stderr, "Data loaded!\n");

	OmDataDump(&omdata);

	// For each session:
	omdata_session_t *session;
	int sessionCount = 0;
	for (session = omdata.firstSession; session != NULL; session = session->sessionNext)
	{
		sessionCount++;
		fprintf(stderr, "=== SESSION %d ===\n", sessionCount);

		if (sessionCount > 1)
		{
			fprintf(stderr, "NOTE: Skipping session %d...\n", sessionCount);
			continue;
		}

		// Find a configuration
		OmConvertFindArrangement(&arrangement, settings, &omdata, session, defaultChannelPriority);

		// Calibration configuration
		omcalibrate_config_t calibrateConfig = { 0 };
		OmCalibrateConfigInit(&calibrateConfig);
		calibrateConfig.stationaryTime = settings->stationaryTime; // 10.0;
		calibrateConfig.stationaryRepeated = settings->repeatedStationary;

		// Start a player
		om_convert_player_t player = { 0 };
		OmConvertPlayerInitialize(&player, &arrangement, settings->sampleRate, settings->interpolate);					// Initialize here for find stationary points

		// Initialize calibration
		omcalibrate_calibration_t calibration;
		OmCalibrateInit(&calibration);

		if (settings->calibrate)
		{
			// Find stationary points
			omcalibrate_stationary_points_t *stationaryPoints;
			fprintf(stderr, "Finding stationary points...\n");
			stationaryPoints = OmCalibrateFindStationaryPoints(&calibrateConfig, &player);		// Player already initialized
			fprintf(stderr, "Found stationary points: %d\n", stationaryPoints->numValues);

			// Dump no calibration
			OmCalibrateDump(&calibration, stationaryPoints, 0);

			// Auto-calibrate
			fprintf(stderr, "Auto-calibrating...\n");
			int calibrationResult = OmCalibrateFindAutoCalibration(&calibrateConfig, stationaryPoints, &calibration);
			OmCalibrateDump(&calibration, stationaryPoints, 1);
			if (calibrationResult < 0)
			{
				fprintf(stderr, "Auto-calibration: using identity calibration...\n");
				int ec = calibration.errorCode;		// Copy error code
				int na = calibration.numAxes;		// ...and num-axes
				OmCalibrateInit(&calibration);
				calibration.errorCode = ec;			// Copy error code to identity calibration
				calibration.numAxes = na;			// ...and num-axes
			}

			// Free stationary points
			OmCalibrateFreeStationaryPoints(stationaryPoints);

		}

		// Output range scalings 
		int outputAccelRange = 8;								// TODO: Possibly allow for +/- 16 outputs (currently always +/-8g -> 16-bit signed)?
		if (outputAccelRange < 8) { outputAccelRange = 8; }		// Minimum of +/-2, +/-4, +/-8 all get output coded as +/-8
		int outputAccelScale = 65536 / (2 * outputAccelRange);

		int outputChannels = arrangement.numChannels + 1;
		int outputRate = (int)(player.sampleRate + 0.5);
		int outputSamples = player.numSamples;

		// Metadata - [Artist�"IART" WAV chunk] Data about the device that made the recording
		char artist[WAV_META_LENGTH] = { 0 };
		sprintf(artist,
			"Id: %u\n"
			"Device: %s\n"
			"Revision: %d\n"
			"Firmware: %d",
			omdata.metadata.deviceId,
			omdata.metadata.deviceTypeString,
			omdata.metadata.deviceVersion,
			omdata.metadata.firmwareVer
			);

		// Metadata - [Title�"INAM" WAV chunk] Data about the recording configuration
		char name[WAV_META_LENGTH] = { 0 };
		sprintf(name,
			"Session: %u\n"
			"Start: %s\n"
			"Stop: %s\n"
			"Config-A: %d,%d\n"
			"Metadata: %s",
			(unsigned int)omdata.metadata.sessionId,
			TimeString(omdata.metadata.recordingStart),
			TimeString(omdata.metadata.recordingStop),
			omdata.metadata.configAccel.frequency, omdata.metadata.configAccel.sensitivity,
			omdata.metadata.metadata
			);

		// Metadata - [Creation�date�"ICRD"�WAV�chunk] - Specify�the�time of the first sample (also in the comment for Matlab)
		char datetime[WAV_META_LENGTH] = { 0 };
		sprintf(datetime, "%s", TimeString(arrangement.startTime));

		// Metadata - [Comment�"ICMT" WAV chunk] Data about this file representation
		char comment[WAV_META_LENGTH] = { 0 };
		sprintf(comment,
			"Time: %s\n"
			"Channel-1: Accel-X\n"
			"Scale-1: %d\n"
			"Channel-2: Accel-Y\n"
			"Scale-2: %d\n"
			"Channel-3: Accel-Z\n"
			"Scale-3: %d\n"
			"Channel-4: Aux",
			TimeString(arrangement.startTime),
			outputAccelRange,
			outputAccelRange,
			outputAccelRange
			);

		// Create output WAV file
		FILE *ofp = NULL;
		if (settings->outFilename != NULL && strlen(settings->outFilename) > 0)
		{
			fprintf(stderr, "Generating WAV file: %s\n", settings->outFilename);
			ofp = fopen(settings->outFilename, "wb");
			if (ofp == NULL)
			{
				fprintf(stderr, "Cannot open output WAV file: %s\n", settings->outFilename);
				retVal = EXIT_CANTCREAT;
				break;
			}

			WavInfo wavInfo = { 0 };
			wavInfo.bytesPerChannel = 2;
			wavInfo.chans = outputChannels;
			wavInfo.freq = outputRate;
			wavInfo.numSamples = outputSamples;
			wavInfo.infoArtist = artist;
			wavInfo.infoName = name;
			wavInfo.infoDate = datetime;
			wavInfo.infoComment = comment;

			// Try to start the data at 1k offset (create a dummy 'JUNK' header)
			wavInfo.offset = 1024;

			if (WavWrite(&wavInfo, ofp) <= 0)
			{
				fprintf(stderr, "ERROR: Problem writing WAV file.\n");
				retVal = EXIT_IOERR;
				break;
			}
		}


		// Re-start the player
		OmConvertPlayerInitialize(&player, &arrangement, settings->sampleRate, settings->interpolate);

		int outputOk = CalcInit(calc, player.sampleRate, player.arrangement->startTime);		// Whether any processing outputs are used

		// Calculate each output sample between the start/end time of session
		if (!outputOk && ofp == NULL)
		{
			fprintf(stderr, "ERROR: No output.\n");
			retVal = EXIT_CONFIG;
			break;
		}
		else
		{

			// Write other information to info file
			if (infofp != NULL)
			{
				fprintf(infofp, ":\n");
				fprintf(infofp, "::: Data about the conversion process\n");
				fprintf(infofp, "Result-file-version: %d\n", 1);
				fprintf(infofp, "Convert-version: %d\n", CONVERT_VERSION);
				fprintf(infofp, "Processed: %s\n", TimeString(TimeNow()));
				fprintf(infofp, "File-input: %s\n", settings->filename);
				fprintf(infofp, "File-output: %s\n", settings->outFilename);
				fprintf(infofp, "Results-output: %s\n", settings->infoFilename);
				fprintf(infofp, "Auto-calibration: %d\n", settings->calibrate);
				fprintf(infofp, "Calibration-Result: %d\n", calibration.errorCode);
				fprintf(infofp, "Calibration: %.10f,%.10f,%.10f,%.10f,%.10f,%.10f,%.10f,%.10f,%.10f,%.10f\n",
					calibration.scale[0], calibration.scale[1], calibration.scale[2],
					calibration.offset[0], calibration.offset[1], calibration.offset[2],
					calibration.tempOffset[0], calibration.tempOffset[1], calibration.tempOffset[2],
					calibration.referenceTemperature);
				fprintf(infofp, "Input-sectors-total: %d\n", omdata.statsTotalSectors);
				fprintf(infofp, "Input-sectors-data: %d\n", omdata.statsDataSectors);
				fprintf(infofp, "Input-sectors-bad: %d\n", omdata.statsBadSectors);
				fprintf(infofp, "Output-rate: %d\n", outputRate);
				fprintf(infofp, "Output-channels: %d\n", outputChannels);
				fprintf(infofp, "Output-duration: %f\n", (float)outputSamples / outputRate);
				fprintf(infofp, "Output-samples: %d\n", outputSamples);
				fprintf(infofp, ":\n");
				fprintf(infofp, "::: Data about the device that made the recording\n");
				fprintf(infofp, "%s\n", artist);
				fprintf(infofp, ":\n");
				fprintf(infofp, "::: Data about the recording itself\n");
				fprintf(infofp, "%s\n", name);
				fprintf(infofp, ":\n");
				fprintf(infofp, "::: Data about this file representation\n");
				fprintf(infofp, "%s\n", comment);
			}

			signed short values[OMDATA_MAX_CHANNELS + 1];
			int sample;
			for (sample = 0; sample < outputSamples; sample++)
			{
				OmConvertPlayerSeek(&player, sample);

				// Convert to integers
				int c;
				double temp = player.temp;
				char clipped = player.clipped;

				double accel[OMCALIBRATE_AXES];
				for (c = 0; c < player.arrangement->numChannels; c++)
				{
					double interpVal = player.values[c];
					double v = player.scale[c] * interpVal;

					// Apply calibration
					if (c < OMCALIBRATE_AXES)
					{
						// Rescaling is:  v = (v + offset) * scale + (temp - referenceTemperature) * tempOffset
						v = (v + calibration.offset[c]) * calibration.scale[c] + (temp - calibration.referenceTemperature) * calibration.tempOffset[c];
					}

					if (c < OMCALIBRATE_AXES)
					{
						accel[c] = v;
					}

					// Output range scaled
					double ov = v * outputAccelScale;

					// Saturate
					if (ov < -32768.0) { ov = -32768.0; clipped = 1; }
					if (ov > 32767.0) { ov = 32767.0; clipped = 1; }

					// Save
					values[c] = (signed short)(ov);
				}


				// Auxilliary channel
				uint16_t aux = 0;
				if (!player.valid) { aux |= WAV_AUX_UNAVAILABLE; }
				if (clipped) { aux |= WAV_AUX_CLIPPING; }

				int cycle = sample % (int)player.sampleRate;
				if (cycle == 0) { aux |= WAV_AUX_SENSOR_BATTERY | (player.aux[0] & 0x3ff); }
				if (cycle == 1) { aux |= WAV_AUX_SENSOR_LIGHT | (player.aux[1] & 0x3ff); }
				if (cycle == 2) { aux |= WAV_AUX_SENSOR_TEMPERATURE | (player.aux[2] & 0x3ff); }

				//player.ettings.auxChannel

				values[player.arrangement->numChannels] = aux;
				if (!CalcAddValue(calc, accel, 0.0, player.valid ? true : false))
				{
					fprintf(stderr, "ERROR: Problem writing calculations.\n");
					retVal = EXIT_IOERR;
					break;
				}

#if 0
				// TEMPORARY: Write SVM (before filtering) to fourth channel
				double outSvm = svm * 4096.0;
				if (outSvm < -32768.0) { outSvm = -32768.0; }
				if (outSvm > 32767.0) { outSvm = 32767.0; }
				values[player.arrangement->numChannels] = (signed short)outSvm;
#endif

				// Output
				//for (c = 0; c < numChannels + 1; c++) { printf("%s%d", (c > 0) ? "," : "", values[c]); }
				//printf("\n");

				if (ofp != NULL)
				{
					int bytesToWrite = sizeof(int16_t) * (arrangement.numChannels + 1);
					static unsigned char cache[1024 * 1024];		// TODO: Don't do this - not thread safe
					static int cachePosition = 0;					// ...or this...

					memcpy(cache + cachePosition, values, bytesToWrite);
					cachePosition += bytesToWrite;
					if (cachePosition + bytesToWrite >= sizeof(cache) || sample + 1 >= outputSamples)
					{
						if (fwrite(cache, 1, cachePosition, ofp) != cachePosition)
						{
							fprintf(stderr, "ERROR: Problem writing output.\n");
							retVal = EXIT_IOERR;
							break;
						}
						cachePosition = 0;
						fprintf(stderr, ".");
					}
				}
			}

		}

		if (ofp != NULL) { fclose(ofp); }

		CalcClose(calc);

		fprintf(stderr, "\n");
		fprintf(stderr, "Finished.\n");

	}

	OmDataFree(&omdata);

	if (sessionCount < 1)
	{
		fprintf(stderr, "ERROR: No sessions to write.\n");
		retVal = EXIT_DATAERR;
	}

	if (infofp != NULL)
	{
		// Write other information to info file
		fprintf(infofp, ":\n");
		fprintf(infofp, "::: Data about the final state\n");
		fprintf(infofp, "Exit: %d\n", retVal);

		fclose(infofp);
		infofp = NULL;
	}

	return retVal;
}
Exemple #20
0
int main( int argc, char **argv ) {
struct stat stat_buff;
stat_record_t	sum_stat;
printer_t 	print_header, print_record;
nfprof_t 	profile_data;
char 		*rfile, *Rfile, *Mdirs, *wfile, *ffile, *filter, *tstring, *stat_type;
char		*byte_limit_string, *packet_limit_string, *print_format, *record_header;
char		*print_order, *query_file, *UnCompress_file, *nameserver, *aggr_fmt;
int 		c, ffd, ret, element_stat, fdump;
int 		i, user_format, quiet, flow_stat, topN, aggregate, aggregate_mask, bidir;
int 		print_stat, syntax_only, date_sorted, do_tag, compress, do_xstat;
int			plain_numbers, GuessDir, pipe_output, csv_output;
time_t 		t_start, t_end;
uint32_t	limitflows;
char 		Ident[IDENTLEN];

	rfile = Rfile = Mdirs = wfile = ffile = filter = tstring = stat_type = NULL;
	byte_limit_string = packet_limit_string = NULL;
	fdump = aggregate = 0;
	aggregate_mask	= 0;
	bidir			= 0;
	t_start = t_end = 0;
	syntax_only	    = 0;
	topN	        = -1;
	flow_stat       = 0;
	print_stat      = 0;
	element_stat  	= 0;
	do_xstat 		= 0;
	limitflows		= 0;
	date_sorted		= 0;
	total_bytes		= 0;
	total_flows		= 0;
	skipped_blocks	= 0;
	do_tag			= 0;
	quiet			= 0;
	user_format		= 0;
	compress		= 0;
	plain_numbers   = 0;
	pipe_output		= 0;
	csv_output		= 0;
	is_anonymized	= 0;
	GuessDir		= 0;
	nameserver		= NULL;

	print_format    = NULL;
	print_header 	= NULL;
	print_record  	= NULL;
	print_order  	= NULL;
	query_file		= NULL;
	UnCompress_file	= NULL;
	aggr_fmt		= NULL;
	record_header 	= NULL;

	Ident[0] = '\0';

	while ((c = getopt(argc, argv, "6aA:Bbc:D:E:s:hHn:i:j:f:qzr:v:w:K:M:NImO:R:XZt:TVv:x:l:L:o:")) != EOF) {
		switch (c) {
			case 'h':
				usage(argv[0]);
				exit(0);
				break;
			case 'a':
				aggregate = 1;
				break;
			case 'A':
				if ( !ParseAggregateMask(optarg, &aggr_fmt ) ) {
					exit(255);
				}
				aggregate_mask = 1;
				break;
			case 'B':
				GuessDir = 1;
			case 'b':
				if ( !SetBidirAggregation() ) {
					exit(255);
				}
				bidir	  = 1;
				// implies
				aggregate = 1;
				break;
			case 'D':
				nameserver = optarg;
				if ( !set_nameserver(nameserver) ) {
					exit(255);
				}
				break;
			case 'E':
				query_file = optarg;
				if ( !InitExporterList() ) {
					exit(255);
				}
				PrintExporters(query_file);
				exit(0);
				break;
			case 'X':
				fdump = 1;
				break;
			case 'Z':
				syntax_only = 1;
				break;
			case 'q':
				quiet = 1;
				break;
			case 'z':
				compress = 1;
				break;
			case 'c':	
				limitflows = atoi(optarg);
				if ( !limitflows ) {
					LogError("Option -c needs a number > 0\n");
					exit(255);
				}
				break;
			case 's':
				stat_type = optarg;
                if ( !SetStat(stat_type, &element_stat, &flow_stat) ) {
                    exit(255);
                } 
				break;
			case 'V': {
				char *e1, *e2;
				e1 = "";
				e2 = "";
#ifdef NSEL
				e1 = "NSEL-NEL";
#endif
				printf("%s: Version: %s%s%s\n",argv[0], e1, e2, nfdump_version);
				exit(0);
				} break;
			case 'l':
				packet_limit_string = optarg;
				break;
			case 'K':
				LogError("*** Anonymisation moved! Use nfanon to anonymise flows!\n");
				exit(255);
				break;
			case 'H':
				do_xstat = 1;
				break;
			case 'L':
				byte_limit_string = optarg;
				break;
			case 'N':
				plain_numbers = 1;
				break;
			case 'f':
				ffile = optarg;
				break;
			case 't':
				tstring = optarg;
				break;
			case 'r':
				rfile = optarg;
				if ( strcmp(rfile, "-") == 0 )
					rfile = NULL;
				break;
			case 'm':
				print_order = "tstart";
				Parse_PrintOrder(print_order);
				date_sorted = 1;
				LogError("Option -m depricated. Use '-O tstart' instead\n");
				break;
			case 'M':
				Mdirs = optarg;
				break;
			case 'I':
				print_stat++;
				break;
			case 'o':	// output mode
				print_format = optarg;
				break;
			case 'O': {	// stat order by
				int ret;
				print_order = optarg;
				ret = Parse_PrintOrder(print_order);
				if ( ret < 0 ) {
					LogError("Unknown print order '%s'\n", print_order);
					exit(255);
				}
				date_sorted = ret == 6;		// index into order_mode
				} break;
			case 'R':
				Rfile = optarg;
				break;
			case 'w':
				wfile = optarg;
				break;
			case 'n':
				topN = atoi(optarg);
				if ( topN < 0 ) {
					LogError("TopnN number %i out of range\n", topN);
					exit(255);
				}
				break;
			case 'T':
				do_tag = 1;
				break;
			case 'i':
				strncpy(Ident, optarg, IDENT_SIZE);
				Ident[IDENT_SIZE - 1] = 0;
				if ( strchr(Ident, ' ') ) {
					LogError("Ident must not contain spaces\n");
					exit(255);
				}
				break;
			case 'j':
				UnCompress_file = optarg;
				UnCompressFile(UnCompress_file);
				exit(0);
				break;
			case 'x':
				query_file = optarg;
				InitExtensionMaps(NO_EXTENSION_LIST);
				DumpExMaps(query_file);
				exit(0);
				break;
			case 'v':
				query_file = optarg;
				QueryFile(query_file);
				exit(0);
				break;
			case '6':	// print long IPv6 addr
				Setv6Mode(1);
				break;
			default:
				usage(argv[0]);
				exit(0);
		}
	}
	if (argc - optind > 1) {
		usage(argv[0]);
		exit(255);
	} else {
		/* user specified a pcap filter */
		filter = argv[optind];
		FilterFilename = NULL;
	}
	
	// Change Ident only
	if ( rfile && strlen(Ident) > 0 ) {
		ChangeIdent(rfile, Ident);
		exit(0);
	}

	if ( (element_stat || flow_stat) && (topN == -1)  ) 
		topN = 10;

	if ( topN < 0 )
		topN = 0;

	if ( (element_stat && !flow_stat) && aggregate_mask ) {
		LogError("Warning: Aggregation ignored for element statistics\n");
		aggregate_mask = 0;
	}

	if ( !flow_stat && aggregate_mask ) {
		aggregate = 1;
	}

	if ( rfile && Rfile ) {
		LogError("-r and -R are mutually exclusive. Plase specify either -r or -R\n");
		exit(255);
	}
	if ( Mdirs && !(rfile || Rfile) ) {
		LogError("-M needs either -r or -R to specify the file or file list. Add '-R .' for all files in the directories.\n");
		exit(255);
	}

	extension_map_list = InitExtensionMaps(NEEDS_EXTENSION_LIST);
	if ( !InitExporterList() ) {
		exit(255);
	}

	SetupInputFileSequence(Mdirs, rfile, Rfile);

	if ( print_stat ) {
		nffile_t *nffile;
		if ( !rfile && !Rfile && !Mdirs) {
			LogError("Expect data file(s).\n");
			exit(255);
		}

		memset((void *)&sum_stat, 0, sizeof(stat_record_t));
		sum_stat.first_seen = 0x7fffffff;
		sum_stat.msec_first = 999;
		nffile = GetNextFile(NULL, 0, 0);
		if ( !nffile ) {
			LogError("Error open file: %s\n", strerror(errno));
			exit(250);
		}
		while ( nffile && nffile != EMPTY_LIST ) {
			SumStatRecords(&sum_stat, nffile->stat_record);
			nffile = GetNextFile(nffile, 0, 0);
		}
		PrintStat(&sum_stat);
		exit(0);
	}

	// handle print mode
	if ( !print_format ) {
		// automatically select an appropriate output format for custom aggregation
		// aggr_fmt is compiled by ParseAggregateMask
		if ( aggr_fmt ) {
			int len = strlen(AggrPrependFmt) + strlen(aggr_fmt) + strlen(AggrAppendFmt) + 7;	// +7 for 'fmt:', 2 spaces and '\0'
			print_format = malloc(len);
			if ( !print_format ) {
				LogError("malloc() error in %s line %d: %s\n", __FILE__, __LINE__, strerror(errno) );
				exit(255);
			}
			snprintf(print_format, len, "fmt:%s %s %s",AggrPrependFmt, aggr_fmt, AggrAppendFmt );
			print_format[len-1] = '\0';
		} else if ( bidir ) {
			print_format = "biline";
		} else
			print_format = DefaultMode;
	}

	if ( strncasecmp(print_format, "fmt:", 4) == 0 ) {
		// special user defined output format
		char *format = &print_format[4];
		if ( strlen(format) ) {
			if ( !ParseOutputFormat(format, plain_numbers, printmap) )
				exit(255);
			print_record  = format_special;
			record_header = get_record_header();
			user_format	  = 1;
		} else {
			LogError("Missing format description for user defined output format!\n");
			exit(255);
		}
	} else {
		// predefined output format

		// Check for long_v6 mode
		i = strlen(print_format);
		if ( i > 2 ) {
			if ( print_format[i-1] == '6' ) {
				Setv6Mode(1);
				print_format[i-1] = '\0';
			} else 
				Setv6Mode(0);
		}

		i = 0;
		while ( printmap[i].printmode ) {
			if ( strncasecmp(print_format, printmap[i].printmode, MAXMODELEN) == 0 ) {
				if ( printmap[i].Format ) {
					if ( !ParseOutputFormat(printmap[i].Format, plain_numbers, printmap) )
						exit(255);
					// predefined custom format
					print_record  = printmap[i].func;
					record_header = get_record_header();
					user_format	  = 1;
				} else {
					// To support the pipe output format for element stats - check for pipe, and remember this
					if ( strncasecmp(print_format, "pipe", MAXMODELEN) == 0 ) {
						pipe_output = 1;
					}
					if ( strncasecmp(print_format, "csv", MAXMODELEN) == 0 ) {
						csv_output = 1;
						set_record_header();
						record_header = get_record_header();
					}
					// predefined static format
					print_record  = printmap[i].func;
					user_format	  = 0;
				}
				break;
			}
			i++;
		}
	}

	if ( !print_record ) {
		LogError("Unknown output mode '%s'\n", print_format);
		exit(255);
	}

	// this is the only case, where headers are printed.
	if ( strncasecmp(print_format, "raw", 16) == 0 )
		print_header = format_file_block_header;
	
	if ( aggregate && (flow_stat || element_stat) ) {
		aggregate = 0;
		LogError("Command line switch -s overwrites -a\n");
	}

	if ( !filter && ffile ) {
		if ( stat(ffile, &stat_buff) ) {
			LogError("Can't stat filter file '%s': %s\n", ffile, strerror(errno));
			exit(255);
		}
		filter = (char *)malloc(stat_buff.st_size+1);
		if ( !filter ) {
			LogError("malloc() error in %s line %d: %s\n", __FILE__, __LINE__, strerror(errno) );
			exit(255);
		}
		ffd = open(ffile, O_RDONLY);
		if ( ffd < 0 ) {
			LogError("Can't open filter file '%s': %s\n", ffile, strerror(errno));
			exit(255);
		}
		ret = read(ffd, (void *)filter, stat_buff.st_size);
		if ( ret < 0   ) {
			perror("Error reading filter file");
			close(ffd);
			exit(255);
		}
		total_bytes += ret;
		filter[stat_buff.st_size] = 0;
		close(ffd);

		FilterFilename = ffile;
	}

	// if no filter is given, set the default ip filter which passes through every flow
	if ( !filter  || strlen(filter) == 0 ) 
		filter = "any";

	Engine = CompileFilter(filter);
	if ( !Engine ) 
		exit(254);

	if ( fdump ) {
		printf("StartNode: %i Engine: %s\n", Engine->StartNode, Engine->Extended ? "Extended" : "Fast");
		DumpList(Engine);
		exit(0);
	}

	if ( syntax_only )
		exit(0);

	if ( print_order && flow_stat ) {
		printf("-s record and -O (-m) are mutually exclusive options\n");
		exit(255);
	}

	if ((aggregate || flow_stat || print_order)  && !Init_FlowTable() )
			exit(250);

	if (element_stat && !Init_StatTable(HashBits, NumPrealloc) )
			exit(250);

	SetLimits(element_stat || aggregate || flow_stat, packet_limit_string, byte_limit_string);

	if ( tstring ) {
		if ( !ScanTimeFrame(tstring, &t_start, &t_end) )
			exit(255);
	}


	if ( !(flow_stat || element_stat || wfile || quiet ) && record_header ) {
		if ( user_format ) {
			printf("%s\n", record_header);
		} else {
			// static format - no static format with header any more, but keep code anyway
			if ( Getv6Mode() ) {
				printf("%s\n", record_header);
			} else
				printf("%s\n", record_header);
		}
	}

	nfprof_start(&profile_data);
	sum_stat = process_data(wfile, element_stat, aggregate || flow_stat, print_order != NULL,
						print_header, print_record, t_start, t_end, 
						limitflows, do_tag, compress, do_xstat);
	nfprof_end(&profile_data, total_flows);

	if ( total_bytes == 0 ) {
		printf("No matched flows\n");
		exit(0);
	}

	if (aggregate || print_order) {
		if ( wfile ) {
			nffile_t *nffile = OpenNewFile(wfile, NULL, compress, is_anonymized, NULL);
			if ( !nffile ) 
				exit(255);
			if ( ExportFlowTable(nffile, aggregate, bidir, date_sorted, extension_map_list) ) {
				CloseUpdateFile(nffile, Ident );	
			} else {
				CloseFile(nffile);
				unlink(wfile);
			}
			DisposeFile(nffile);
		} else {
			PrintFlowTable(print_record, topN, do_tag, GuessDir, extension_map_list);
		}
	}

	if (flow_stat) {
		PrintFlowStat(record_header, print_record, topN, do_tag, quiet, csv_output, extension_map_list);
#ifdef DEVEL
		printf("Loopcnt: %u\n", loopcnt);
#endif
	} 

	if (element_stat) {
		PrintElementStat(&sum_stat, plain_numbers, record_header, print_record, topN, do_tag, quiet, pipe_output, csv_output);
	} 

	if ( !quiet ) {
		if ( csv_output ) {
			PrintSummary(&sum_stat, plain_numbers, csv_output);
		} else if ( !wfile ) {
			if (is_anonymized)
				printf("IP addresses anonymised\n");
			PrintSummary(&sum_stat, plain_numbers, csv_output);
			if ( t_last_flow == 0 ) {
				// in case of a pre 1.6.6 collected and empty flow file
 				printf("Time window: <unknown>\n");
			} else {
 				printf("Time window: %s\n", TimeString(t_first_flow, t_last_flow));
			}
			printf("Total flows processed: %u, Blocks skipped: %u, Bytes read: %llu\n", 
				total_flows, skipped_blocks, (unsigned long long)total_bytes);
			nfprof_print(&profile_data, stdout);
		}
	}

	Dispose_FlowTable();
	Dispose_StatTable();
	FreeExtensionMaps(extension_map_list);

#ifdef DEVEL
	if ( hash_hit || hash_miss )
		printf("Hash hit: %i, miss: %i, skip: %i, ratio: %5.3f\n", hash_hit, hash_miss, hash_skip, (float)hash_hit/((float)(hash_hit+hash_miss)));
#endif

	return 0;
}
Exemple #21
0
cString cEvent::GetTimeString(void) const
{
  return TimeString(startTime);
}