Example #1
0
bool Slang::setOutput(const char *OutputFile) {
  llvm::sys::Path OutputFilePath(OutputFile);
  std::string Error;
  llvm::tool_output_file *OS = NULL;

  switch (mOT) {
    case OT_Dependency:
    case OT_Assembly:
    case OT_LLVMAssembly: {
      OS = OpenOutputFile(OutputFile, 0, &Error, mDiagEngine);
      break;
    }
    case OT_Nothing: {
      break;
    }
    case OT_Object:
    case OT_Bitcode: {
      OS = OpenOutputFile(OutputFile, llvm::raw_fd_ostream::F_Binary,
                          &Error, mDiagEngine);
      break;
    }
    default: {
      llvm_unreachable("Unknown compiler output type");
    }
  }

  if (!Error.empty())
    return false;

  mOS.reset(OS);

  mOutputFileName = OutputFile;

  return true;
}
Example #2
0
//============================================================================//
void WriteVector_ASCII(char *path, char *fname, char vchar, int *dims, 
                       float **mesh_coords, double time, float **vec, 
                       char *stopmsg) {
    int Nq = dims[0], Nr = dims[1], Ns = dims[2];
    float *coord_arr;
    char outstr[1001];
    ofstream file;
    
    // Open the output file:    
    OpenOutputFile(file,path,fname,stopmsg);
    
    // Write the header strings:
    sprintf(outstr,"vector\n%c\nt=%7.1f\n%3d %3d %3d\n",vchar,time,Nq,Nr,Ns);
    file << outstr;
    
    // Write the data the file
    MakeCoordArray(coord_arr,mesh_coords,dims);
    WriteArray_ASCII(file,6,coord_arr,Nq+Nr+Ns);
    WriteArray_ASCII(file,6,vec[0],Nq*Nr*Ns);
    WriteArray_ASCII(file,6,vec[1],Nq*Nr*Ns);
    WriteArray_ASCII(file,6,vec[2],Nq*Nr*Ns);
        
    file.close();
    delete [] coord_arr;
    
    printf("      ASCII file \"%s\" written to disk.\n",fname);
}
H265VideoFileSink*
H265VideoFileSink::createNew(UsageEnvironment& env, char const* fileName,
			     char const* sPropVPSStr,
			     char const* sPropSPSStr,
			     char const* sPropPPSStr,
			     unsigned bufferSize, Boolean oneFilePerFrame) {
  do {
    FILE* fid;
    char const* perFrameFileNamePrefix;
    if (oneFilePerFrame) {
      // Create the fid for each frame
      fid = NULL;
      perFrameFileNamePrefix = fileName;
    } else {
      // Normal case: create the fid once
      fid = OpenOutputFile(env, fileName);
      if (fid == NULL) break;
      perFrameFileNamePrefix = NULL;
    }

    return new H265VideoFileSink(env, fid, sPropVPSStr, sPropSPSStr, sPropPPSStr, bufferSize, perFrameFileNamePrefix);
  } while (0);

  return NULL;
}
Example #4
0
void FileSink::addData(unsigned char const* data, unsigned dataSize,
		       struct timeval presentationTime) {
  if (fPerFrameFileNameBuffer != NULL && fOutFid == NULL) {
    // Special case: Open a new file on-the-fly for this frame
    if (presentationTime.tv_usec == fPrevPresentationTime.tv_usec &&
	presentationTime.tv_sec == fPrevPresentationTime.tv_sec) {
      // The presentation time is unchanged from the previous frame, so we add a 'counter'
      // suffix to the file name, to distinguish them:
      sprintf(fPerFrameFileNameBuffer, "%s-%lu.%06lu-%u", fPerFrameFileNamePrefix,
	      presentationTime.tv_sec, presentationTime.tv_usec, ++fSamePresentationTimeCounter);
    } else {
      sprintf(fPerFrameFileNameBuffer, "%s-%lu.%06lu", fPerFrameFileNamePrefix,
	      presentationTime.tv_sec, presentationTime.tv_usec);
      fPrevPresentationTime = presentationTime; // for next time
      fSamePresentationTimeCounter = 0; // for next time
    }
    fOutFid = OpenOutputFile(envir(), fPerFrameFileNameBuffer);
  }

  // Write to our file:
#ifdef TEST_LOSS
  static unsigned const framesPerPacket = 10;
  static unsigned const frameCount = 0;
  static Boolean const packetIsLost;
  if ((frameCount++)%framesPerPacket == 0) {
    packetIsLost = (our_random()%10 == 0); // simulate 10% packet loss #####
  }

  if (!packetIsLost)
#endif
  if (fOutFid != NULL && data != NULL) {
    fwrite(data, 1, dataSize, fOutFid);
  }
}
Example #5
0
out_stream OutputFileHandler::OpenOutputFile(const std::string& rFileName,
                                             unsigned number,
                                             const std::string& rFileFormat,
                                             std::ios_base::openmode mode) const
{
    std::stringstream string_stream;
    string_stream << rFileName << number << rFileFormat;
    return OpenOutputFile(string_stream.str(), mode);
}
Example #6
0
//============================================================================//
void Write_ProbeData(int cycle, char *silo_path, char *probe_path) {
    int i, j, k, n, dims[ndims];
    float time, *b_field[ndims];
    char full_name[1001], outstr[1001];
    
    // Load the magnetic field data and its dimensions
    sprintf(full_name,"HYM_%0.3d.silo",cycle);
    time = ReadTime_SILO(silo_path,full_name,"HYM_mesh",stopmsg);
    ReadVector_SILO(silo_path,full_name,"b_field",b_field,dims,stopmsg);
    
    // Index and interpolation array initializations:
    int zInd[zLen], rInd[rLen], pInd[pLen];
    float zInterp[zLen], rInterp[rLen], pInterp[pLen];
    
    // Index mapping and printing calls:
    Map_Indices(zLoc,zLen,dims[0]-1,zInd,zInterp);
    Map_Indices(rLoc,rLen,dims[1]-1,rInd,rInterp);
    Map_Indices(pLoc,pLen,dims[2],pInd,pInterp);
    
    // Print out the dimensions and the mapped indices:
    // Print_Dims(dims);
    // Print_Indices(zLen,"z",zInd,zInterp);
    // Print_Indices(rLen,"r",rInd,rInterp);
    // Print_Indices(pLen,"p",pInd,pInterp);

    //------------------------------------------------------------------------//
    // Hack overwrite of zInd array for gathering shifted probe data:
    int ipr_east = 125;
    zInd[0] = ipr_east;
    zInd[1] = 256;
    zInd[2] = 512-ipr_east;
    //------------------------------------------------------------------------//
    
    // Write the magnetic field values at the various probe locations
    ofstream file;
    sprintf(full_name,"Probes_%0.3d.dat",cycle);
    OpenOutputFile(file,probe_path,full_name,stopmsg);
    file << "time= " << time << endl;
    for(i=0; i<zLen; i++) {
        for(j=0; j<rLen; j++) {
            for(k=0; k<pLen; k++) {
                n = fn(zInd[i],rInd[j],pInd[k],dims[0],dims[1]);
                sprintf(outstr,"%6.2f  %5.2f  %8.6f  %13.6E  %13.6E  %13.6E\n",
                        61.0*zLoc[i]-30.5,20.3*rLoc[j],2.0*pi*pLoc[k],
                        b_field[0][n],b_field[1][n],b_field[2][n]);
                file << outstr;
            }
        }
    }
    file.close();
    
    for(int m=0; m<ndims; m++)
        delete [] b_field[m];
    
    cout << "    Output: \"" << probe_path << full_name << "\"\n";
}
Example #7
0
bool Slang::setDepOutput(const char *OutputFile) {
  llvm::sys::Path OutputFilePath(OutputFile);
  std::string Error;

  mDOS.reset(OpenOutputFile(OutputFile, 0, &Error, mDiagnostics.getPtr()));
  if (!Error.empty() || (mDOS.get() == NULL))
    return false;

  mDepOutputFileName = OutputFile;

  return true;
}
Example #8
0
AVIFileSink::AVIFileSink(UsageEnvironment& env,
			 MediaSession& inputSession,
			 char const* outputFileName,
			 unsigned bufferSize,
			 unsigned short movieWidth, unsigned short movieHeight,
			 unsigned movieFPS, Boolean packetLossCompensate)
  : Medium(env), fInputSession(inputSession),
    fIndexRecordsHead(NULL), fIndexRecordsTail(NULL), fNumIndexRecords(0),
    fBufferSize(bufferSize), fPacketLossCompensate(packetLossCompensate),
    fAreCurrentlyBeingPlayed(False), fNumSubsessions(0), fNumBytesWritten(0),
    fHaveCompletedOutputFile(False),
    fMovieWidth(movieWidth), fMovieHeight(movieHeight), fMovieFPS(movieFPS) {
  fOutFid = OpenOutputFile(env, outputFileName);
  if (fOutFid == NULL) return;

  // Set up I/O state for each input subsession:
  MediaSubsessionIterator iter(fInputSession);
  MediaSubsession* subsession;
  while ((subsession = iter.next()) != NULL) {
    // Ignore subsessions without a data source:
    FramedSource* subsessionSource = subsession->readSource();
    if (subsessionSource == NULL) continue;

    // If "subsession's" SDP description specified screen dimension
    // or frame rate parameters, then use these.
    if (subsession->videoWidth() != 0) {
      fMovieWidth = subsession->videoWidth();
    }
    if (subsession->videoHeight() != 0) {
      fMovieHeight = subsession->videoHeight();
    }
    if (subsession->videoFPS() != 0) {
      fMovieFPS = subsession->videoFPS();
    }

    AVISubsessionIOState* ioState
      = new AVISubsessionIOState(*this, *subsession);
    subsession->miscPtr = (void*)ioState;

    // Also set a 'BYE' handler for this subsession's RTCP instance:
    if (subsession->rtcpInstance() != NULL) {
      subsession->rtcpInstance()->setByeHandler(onRTCPBye, ioState);
    }

    ++fNumSubsessions;
  }

  // Begin by writing an AVI header:
  addFileHeader_AVI();
}
void Application::Menu_select()
{
	y -= 3;
	switch(y)
	{
	case 1:
		RunClient();
		Client_select();
		break;
	case 2:
		RunAdmin();
		Admin_select();
		CW.DeleteCW();
		break;
	case 3:
		OpenOutputFile();
		PutClientListToFile();
		exit(100);
	}
}
Example #10
0
static BROTLI_BOOL OpenFiles(Context* context) {
  BROTLI_BOOL is_ok = OpenInputFile(context->current_input_path, &context->fin);
  if (context->decompress) {
    //
    // skip the decoder data header
    //
    fseek(context->fin, DECODE_HEADER_SIZE, SEEK_SET);
  }
  if (!context->test_integrity && is_ok && context->fout == NULL) {
    is_ok = OpenOutputFile(
        context->current_output_path, &context->fout, context->force_overwrite);
  }
  if (!context->decompress) {
    //
    // append the decoder data header
    //
    fseek(context->fout, DECODE_HEADER_SIZE, SEEK_SET);
  }
  return is_ok;
}
Example #11
0
void FileSink::addData(unsigned char const* data, unsigned dataSize,
		       struct timeval presentationTime) {
  if (fPerFrameFileNameBuffer != NULL) {
    // Special case: Open a new file on-the-fly for this frame
    sprintf(fPerFrameFileNameBuffer, "%s-%lu.%06lu", fPerFrameFileNamePrefix,
	    presentationTime.tv_sec, presentationTime.tv_usec);
    fOutFid = OpenOutputFile(envir(), fPerFrameFileNameBuffer);
  }

  // Write to our file:
#ifdef TEST_LOSS
  static unsigned const framesPerPacket = 10;
  static unsigned const frameCount = 0;
  static Boolean const packetIsLost;
  if ((frameCount++)%framesPerPacket == 0) {
    packetIsLost = (our_random()%10 == 0); // simulate 10% packet loss #####
  }

  if (!packetIsLost)
#endif
  if (fOutFid != NULL && data != NULL) {
    fwrite(data, 1, dataSize, fOutFid);
  }
}
Example #12
0
int WriteOutResults(PPROGRAM_CONTEXT ProgramContext)
{
	FILE_WRITER_CONTEXT FileWriterContext;
	int Result = NO_ERROR;
	
	//Open File
	Result = OpenOutputFile(ProgramContext, &FileWriterContext);
	if(Result != NO_ERROR)
	{
		return Result;
	}	
	
	mlock(ProgramContext->TweetStrings, ProgramContext->TweetStringsSize);
	
	//Write all Elements
	WriteTweetsToFile(ProgramContext, &FileWriterContext);
	
	munlock(ProgramContext->TweetStrings, ProgramContext->TweetStringsSize);
	
	//close file
	fclose(FileWriterContext.OutputFile);

	return Result;
}
void MinimalizationSimulation(void)
{
  int j,k;
  REAL Drift,ReferenceEnergy,ran;
  int NumberOfSystemMoves,NumberOfParticleMoves,NumberOfSteps;
  int ran_int;

  Drift=0.0;
  ReferenceEnergy=0.0;
  CurrentSystem=0;

  fprintf(stderr, "Starting minimization\n");

  OpenOutputFile();

  //InitializeNoseHooverAllSystems();

  InitializesEnergiesAllSystems();
  InitializesEnergyAveragesAllSystems();

  InitializeSmallMCStatisticsAllSystems();
  InitializeMCMovesStatisticsAllSystems();

  CalculateTotalEnergyAllSystems();

  PrintPreSimulationStatus();

  for(CurrentSystem=0;CurrentSystem<NumberOfSystems;CurrentSystem++)
  {
    for(k=0;k<NumberOfCycles;k++)
    {
      InitializesEnergiesAllSystems();
      InitializesEnergyAveragesAllSystems();
      CalculateTotalEnergyAllSystems();

      for(CurrentCycle=0;CurrentCycle<NumberOfInitializationCycles;CurrentCycle++)
      {
        if((CurrentCycle%PrintEvery)==0)
          PrintIntervalStatusInit(CurrentCycle,NumberOfInitializationCycles,OutputFilePtr[CurrentSystem]);

        NumberOfSystemMoves=12;
        NumberOfParticleMoves=MAX2(MinimumInnerCycles,NumberOfAdsorbateMolecules[CurrentSystem]+NumberOfCationMolecules[CurrentSystem]);
        NumberOfSteps=(NumberOfSystemMoves+NumberOfParticleMoves)*NumberOfComponents;

        for(j=0;j<NumberOfSteps;j++)
        {
          ran_int=(int)(RandomNumber()*NumberOfSteps);
          switch(ran_int)
          {
            case 0:
              if(RandomNumber()<ProbabilityParallelTemperingMove) ParallelTemperingMove();
              break;
            case 1:
              if(RandomNumber()<ProbabilityHyperParallelTemperingMove) HyperParallelTemperingMove();
              break;
            case 2:
              if(RandomNumber()<ProbabilityParallelMolFractionMove) ParallelMolFractionMove();
              break;
            case 3:
              if(RandomNumber()<ProbabilityChiralInversionMove) ChiralInversionMove();
              break;
            case 4:
              if(RandomNumber()<ProbabilityHybridNVEMove) HybridNVEMove();
              break;
            case 5:
              if(RandomNumber()<ProbabilityHybridNPHMove) HybridNPHMove();
              break;
            case 6:
              if(RandomNumber()<ProbabilityHybridNPHPRMove) HybridNPHPRMove();
              break;
            case 7:
              if(RandomNumber()<ProbabilityVolumeChangeMove) VolumeMove();
              break;
            case 8:
              if(RandomNumber()<ProbabilityBoxShapeChangeMove) BoxShapeChangeMove();
              break;
            case 9:
              if(RandomNumber()<ProbabilityGibbsVolumeChangeMove) GibbsVolumeMove();
              break;
            case 10:
              if(RandomNumber()<ProbabilityFrameworkChangeMove) FrameworkChangeMove();
              break;
            case 11:
              if(RandomNumber()<ProbabilityFrameworkShiftMove) FrameworkShiftMove();
              break;
            default:
              // choose component at random
              CurrentComponent=(int)(RandomNumber()*(REAL)NumberOfComponents);

              // choose the Monte Carlo move at random
              ran=RandomNumber();

              if(ran<Components[CurrentComponent].ProbabilityTranslationMove)
                TranslationMove();
              else if(ran<Components[CurrentComponent].ProbabilityRandomTranslationMove)
                RandomTranslationMove();
              else if(ran<Components[CurrentComponent].ProbabilityRotationMove)
                RotationMove();
              else if(ran<Components[CurrentComponent].ProbabilityPartialReinsertionMove)
                PartialReinsertionMove();
              else if(ran<Components[CurrentComponent].ProbabilityReinsertionMove)
                ReinsertionMove();
              else if(ran<Components[CurrentComponent].ProbabilityReinsertionInPlaceMove)
                ReinsertionInPlaceMove();
              else if(ran<Components[CurrentComponent].ProbabilityReinsertionInPlaneMove)
                ReinsertionInPlaneMove();
              else if(ran<Components[CurrentComponent].ProbabilityIdentityChangeMove)
                IdentityChangeMove();
              else if(ran<Components[CurrentComponent].ProbabilitySwapMove)
              {
                if(RandomNumber()<0.5) SwapAddMove();
                else SwapRemoveMove();
              }
              else if(ran<Components[CurrentComponent].ProbabilityWidomMove)
               ;
              else if(ran<Components[CurrentComponent].ProbabilitySurfaceAreaMove)
               ;
              else if(ran<Components[CurrentComponent].ProbabilityGibbsChangeMove)
                GibbsParticleTransferMove();
              else if(ran<Components[CurrentComponent].ProbabilityGibbsIdentityChangeMove)
               GibbsIdentityChangeMove();
          }
        }

        if(CurrentCycle%1000==0)
          OptimizeTranslationAcceptence();
      }

      // do the minimization
      Minimization(k);

      InitializesEnergiesCurrentSystem();
      CalculateEnergy();
      PrintEnergyStatus(OutputFilePtr[CurrentSystem],"minimization full energy");
    }

    PrintRestartFile();
  }

  PrintPostSimulationStatus();
  CloseOutputFile();
}
Example #14
0
void MolecularDynamicsSimulation(void)
{
  int i,j,k;
  REAL ran;

  // for a crash-recovery we skip the initialization and jump to the
  // position right after the crash-file was written in the production run
  if(ContinueAfterCrash)
  {
    if(SimulationStage==POSITION_INITIALIZATION) goto ContinueAfterCrashLabel1;
    else if(SimulationStage==VELOCITY_EQUILIBRATION) goto ContinueAfterCrashLabel2;
    else goto ContinueAfterCrashLabel3;
  }

  // compute gas properties
  // here the pressure is converted to fugacities
  ComputeGasPropertiesForAllSystems();

  // open output-file
  OpenOutputFile();

  // print all the pre-simulations data
  PrintPreSimulationStatus();

  // allocate memory
  SampleRadialDistributionFunction(ALLOCATE);
  SampleProjectedLengthsDistributionFunction(ALLOCATE);
  SampleProjectedAnglesDistributionFunction(ALLOCATE);
  SampleNumberOfMoleculesHistogram(ALLOCATE);
  SamplePositionHistogram(ALLOCATE);
  SampleFreeEnergyProfile(ALLOCATE);
  SampleEndToEndDistanceHistogram(ALLOCATE);
  SampleEnergyHistogram(ALLOCATE);
  SampleFrameworkSpacingHistogram(ALLOCATE);
  SampleResidenceTimes(ALLOCATE);
  SampleDistanceHistogram(ALLOCATE);
  SampleBendAngleHistogram(ALLOCATE);
  SampleDihedralAngleHistogram(ALLOCATE);
  SampleAngleBetweenPlanesHistogram(ALLOCATE);
  SampleMoleculePropertyHistogram(ALLOCATE);
  SampleInfraRedSpectra(ALLOCATE);
  SampleMeanSquaredDisplacementOrderN(ALLOCATE);
  SampleVelocityAutoCorrelationFunctionOrderN(ALLOCATE);
  SampleRotationalVelocityAutoCorrelationFunctionOrderN(ALLOCATE);
  SampleMolecularOrientationAutoCorrelationFunctionOrderN(ALLOCATE);
  SampleBondOrientationAutoCorrelationFunctionOrderN(ALLOCATE);
  SampleMeanSquaredDisplacement(ALLOCATE);
  SampleVelocityAutoCorrelationFunction(ALLOCATE);
  SampleDensityProfile3DVTKGrid(ALLOCATE);
  SampleCationAndAdsorptionSites(ALLOCATE);
  SampleDcTSTConfigurationFiles(ALLOCATE);
  SamplePDBMovies(ALLOCATE,-1);


  // initialize
  InitializesEnergiesAllSystems();
  InitializeSmallMCStatisticsAllSystems();
  InitializeMCMovesStatisticsAllSystems();

  // compute initial energy
  CalculateTotalEnergyAllSystems();


  // Monte-Carlo initializing period to achieve a rapid equilibration of the positions
  SimulationStage=POSITION_INITIALIZATION;
  for(CurrentCycle=0;CurrentCycle<NumberOfInitializationCycles;CurrentCycle++)
  {
    if((CurrentCycle%PrintEvery)==0)
      for(CurrentSystem=0;CurrentSystem<NumberOfSystems;CurrentSystem++)
        PrintIntervalStatusInit(CurrentCycle,NumberOfInitializationCycles,OutputFilePtr[CurrentSystem]);

    for(j=0;j<NumberOfSystems*NumberOfComponents;j++)
    {
      // choose a random system
      CurrentSystem=(int)(RandomNumber()*(REAL)NumberOfSystems);

      for(k=0;k<MAX2(MinimumInnerCycles,NumberOfAdsorbateMolecules[CurrentSystem]);k++)
      {
        // choose a random component
        CurrentComponent=(int)(RandomNumber()*(REAL)NumberOfComponents);

        // choose any of the MC moves randomly with the selected probability
        ran=RandomNumber();

        if(ran<Components[CurrentComponent].ProbabilityTranslationMove)
          TranslationMove();
        else if(ran<Components[CurrentComponent].ProbabilityRandomTranslationMove)
          RandomTranslationMove();
        else if(ran<Components[CurrentComponent].ProbabilityRotationMove)
          RotationMove();
        else if(ran<Components[CurrentComponent].ProbabilityPartialReinsertionMove)
          PartialReinsertionMove();
        else if(ran<Components[CurrentComponent].ProbabilityReinsertionMove)
          ReinsertionMove();
        else if(ran<Components[CurrentComponent].ProbabilityReinsertionInPlaceMove)
          ReinsertionInPlaceMove();
        else if(ran<Components[CurrentComponent].ProbabilityReinsertionInPlaneMove)
          ReinsertionInPlaneMove();
        else if(ran<Components[CurrentComponent].ProbabilityIdentityChangeMove)
          IdentityChangeMove();
        else if(ran<Components[CurrentComponent].ProbabilitySwapMove)
        {
          if(RandomNumber()<0.5) SwapAddMove();
          else SwapRemoveMove();
        }
        else if(ran<Components[CurrentComponent].ProbabilityCFSwapLambdaMove)
          CFSwapLambaMove();
        else if(ran<Components[CurrentComponent].ProbabilityCBCFSwapLambdaMove)
          CBCFSwapLambaMove();
        else if(ran<Components[CurrentComponent].ProbabilityWidomMove)
          ;
        else if(ran<Components[CurrentComponent].ProbabilitySurfaceAreaMove)
          ;
        else if(ran<Components[CurrentComponent].ProbabilityGibbsChangeMove)
          GibbsParticleTransferMove();
        else if(ran<Components[CurrentComponent].ProbabilityGibbsIdentityChangeMove)
          GibbsIdentityChangeMove();
        else if(ran<Components[CurrentComponent].ProbabilityCFGibbsChangeMove)
          CFGibbsParticleTransferMove();
        else if(ran<Components[CurrentComponent].ProbabilityCBCFGibbsChangeMove)
          CBCFGibbsParticleTransferMove();
        else if(ran<Components[CurrentComponent].ProbabilityParallelTemperingMove)
          ParallelTemperingMove();
        else if(ran<Components[CurrentComponent].ProbabilityHyperParallelTemperingMove)
          HyperParallelTemperingMove();
        else if(ran<Components[CurrentComponent].ProbabilityParallelMolFractionMove)
          ParallelMolFractionMove();
        else if(ran<Components[CurrentComponent].ProbabilityChiralInversionMove)
          ChiralInversionMove();
        else if(ran<Components[CurrentComponent].ProbabilityHybridNVEMove)
          HybridNVEMove();
        else if(ran<Components[CurrentComponent].ProbabilityHybridNPHMove)
          HybridNPHMove();
        else if(ran<Components[CurrentComponent].ProbabilityHybridNPHPRMove)
          HybridNPHPRMove();
        else if(ran<Components[CurrentComponent].ProbabilityVolumeChangeMove)
          VolumeMove();
        else if(ran<Components[CurrentComponent].ProbabilityBoxShapeChangeMove)
          BoxShapeChangeMove();
        else if(ran<Components[CurrentComponent].ProbabilityGibbsVolumeChangeMove)
          GibbsVolumeMove();
        else if(ran<Components[CurrentComponent].ProbabilityFrameworkChangeMove)
          FrameworkChangeMove();
        else if(ran<Components[CurrentComponent].ProbabilityFrameworkShiftMove)
          FrameworkShiftMove();
      }
    }

    if(CurrentCycle%PrintEvery==0)
    {
      for(CurrentSystem=0;CurrentSystem<NumberOfSystems;CurrentSystem++)
      {
        OptimizeVolumeChangeAcceptence();
        OptimizeTranslationAcceptence();
        if(Framework[CurrentSystem].FrameworkModel==FLEXIBLE)
        {
          OptimizeFrameworkChangeAcceptence();
          OptimizeFrameworkShiftAcceptence();
        }
        RescaleMaximumRotationAnglesSmallMC();
      }
    }

    if((CurrentCycle>0)&&(WriteBinaryRestartFileEvery>0)&&(CurrentCycle%WriteBinaryRestartFileEvery==0))
      WriteBinaryRestartFiles();

    ContinueAfterCrashLabel1:;
  }

  // initialize
  InitializesEnergiesAllSystems();
  InitializeSmallMCStatisticsAllSystems();
  InitializeMCMovesStatisticsAllSystems();

  SimulationStage=VELOCITY_SCALING;
  if(ReinitializeVelocities)
  {
    for(CurrentSystem=0;CurrentSystem<NumberOfSystems;CurrentSystem++)
    {
      InitializeAdsorbateVelocities();
      InitializeCationVelocities();
      if(Framework[CurrentSystem].FrameworkModel==FLEXIBLE)
        InitializeFrameworkVelocities();

      RemoveVelocityDrift();
      //AdjustSystemAngularRotationToZero();
    }
  }

  //InitializeNoseHooverCurrentSystem();
  InitializeNoseHooverAllSystems();

  // compute initial energy
  InitializeForcesAllSystems();

  // Molecular-Dynamics initializing period to remove excessive kinetic energy due to
  // poor equilibration of the positions (use with caution)
  // Velocity-scaling scales the velocities at each time step to the desired temperature
/*
  for(CurrentCycle=0;CurrentCycle<NumberOfVelocityScalingCycles;CurrentCycle++)
  {
    for(CurrentSystem=0;CurrentSystem<NumberOfSystems;CurrentSystem++)
    {
      // scake the velocity to the exact temperature
      AdjustVelocitiesToTemperature();

      // regularly output system status and restart files
      if(CurrentCycle%PrintEvery==0)
      {
        PrintIntervalStatusEquilibration(CurrentCycle,NumberOfEquilibrationCycles,OutputFilePtr[CurrentSystem]);
        PrintRestartFile();
      }
      // evolve the system a full time-step
      Integration();
    }
  }
*/

  // set the current ensemble to the initialization ensemble
  for(i=0;i<NumberOfSystems;i++)
    Ensemble[i]=InitEnsemble[i];

  InitializesEnergyAveragesAllSystems();

  for(CurrentSystem=0;CurrentSystem<NumberOfSystems;CurrentSystem++)
  {
    ReferenceEnergy[CurrentSystem]=ConservedEnergy[CurrentSystem];
    Drift[CurrentSystem]=0.0;
  }

  // Molecular-Dynamics initializing period to achieve a rapid equilibration of the velocities
  SimulationStage=VELOCITY_EQUILIBRATION;
  for(CurrentCycle=0;CurrentCycle<NumberOfEquilibrationCycles;CurrentCycle++)
  {
    for(CurrentSystem=0;CurrentSystem<NumberOfSystems;CurrentSystem++)
    {
      // regularly output system status and restart files
      if(CurrentCycle%PrintEvery==0)
      {
        PrintIntervalStatusEquilibration(CurrentCycle,NumberOfEquilibrationCycles,OutputFilePtr[CurrentSystem]);
        PrintRestartFile();
      }

      // insertion/deletion for the osmotic-ensemble
      if(Ensemble[CurrentSystem]==MuPT)
      {
        CurrentComponent=(int)(RandomNumber()*NumberOfComponents);
        if((CurrentCycle%(Components[CurrentComponent].SwapEvery)==0)&&
           (Components[CurrentComponent].ProbabilitySwapMove>0.0))
        {
          if(RandomNumber()<0.5) SwapAddMove();
          else SwapRemoveMove();
        }
      }

      // evolve the system a full time-step
      Integration();

      // prevent heating of the core-shells
      AdjustCoreShellVelocities();

      // update the current energy-drift
      Drift[CurrentSystem]+=fabs((ConservedEnergy[CurrentSystem]-ReferenceEnergy[CurrentSystem])/ReferenceEnergy[CurrentSystem]);
    }

    if((CurrentCycle>0)&&(WriteBinaryRestartFileEvery>0)&&(CurrentCycle%WriteBinaryRestartFileEvery==0))
      WriteBinaryRestartFiles();

    ContinueAfterCrashLabel2:;
  }


  // initialize sampling-routines at the start of the production run
  for(CurrentSystem=0;CurrentSystem<NumberOfSystems;CurrentSystem++)
  {
    Ensemble[CurrentSystem]=RunEnsemble[CurrentSystem];

    ReferenceEnergy[CurrentSystem]=ConservedEnergy[CurrentSystem];
    Drift[CurrentSystem]=0.0;

    SampleRadialDistributionFunction(INITIALIZE);
    SampleProjectedLengthsDistributionFunction(INITIALIZE);
    SampleProjectedAnglesDistributionFunction(INITIALIZE);
    SampleNumberOfMoleculesHistogram(INITIALIZE);
    SamplePositionHistogram(INITIALIZE);
    SampleFreeEnergyProfile(INITIALIZE);
    SampleEndToEndDistanceHistogram(INITIALIZE);
    SampleEnergyHistogram(INITIALIZE);
    SampleFrameworkSpacingHistogram(INITIALIZE);
    SampleResidenceTimes(INITIALIZE);
    SampleDistanceHistogram(INITIALIZE);
    SampleBendAngleHistogram(INITIALIZE);
    SampleDihedralAngleHistogram(INITIALIZE);
    SampleAngleBetweenPlanesHistogram(INITIALIZE);
    SampleMoleculePropertyHistogram(INITIALIZE);
    SampleInfraRedSpectra(INITIALIZE);
    SampleMeanSquaredDisplacementOrderN(INITIALIZE);
    SampleVelocityAutoCorrelationFunctionOrderN(INITIALIZE);
    SampleRotationalVelocityAutoCorrelationFunctionOrderN(INITIALIZE);
    SampleMolecularOrientationAutoCorrelationFunctionOrderN(INITIALIZE);
    SampleBondOrientationAutoCorrelationFunctionOrderN(INITIALIZE);
    SampleMeanSquaredDisplacement(INITIALIZE);
    SampleVelocityAutoCorrelationFunction(INITIALIZE);
    SampleDensityProfile3DVTKGrid(INITIALIZE);
    SampleCationAndAdsorptionSites(INITIALIZE);
    SampleDcTSTConfigurationFiles(INITIALIZE);
    SamplePDBMovies(INITIALIZE,-1);
  }

  // Molecular-Dynamics production run
  // loop over the amount of production cycles (MD integration steps)
  SimulationStage=PRODUCTION;
  for(CurrentCycle=0;CurrentCycle<NumberOfCycles;CurrentCycle++)
  {
    // detect erroneous chirality changes
    for(CurrentSystem=0;CurrentSystem<NumberOfSystems;CurrentSystem++)
      CheckChiralityMolecules();

    // loop over all the systems and handle one by one
    for(CurrentSystem=0;CurrentSystem<NumberOfSystems;CurrentSystem++)
    {
      // update all the average energies
      UpdateEnergyAveragesCurrentSystem();

      if(CurrentCycle%PrintPropertiesEvery==0)
        PrintPropertyStatus(CurrentCycle,NumberOfCycles,OutputFilePtr[CurrentSystem]);

      if(CurrentCycle%PrintEvery==0)
      {
        PrintIntervalStatus(CurrentCycle,NumberOfCycles,OutputFilePtr[CurrentSystem]);
        PrintRestartFile();
      }

      // insertion/deletion for the osmotic-ensemble
      if(Ensemble[CurrentSystem]==MuPT)
      {
        CurrentComponent=(int)(RandomNumber()*NumberOfComponents);
        if((CurrentCycle%(Components[CurrentComponent].SwapEvery)==0)&&
           (Components[CurrentComponent].FractionOfSwapMove>0.0))
        {
          if(RandomNumber()<0.5) SwapAddMove();
          else SwapRemoveMove();
        }
      }

      for(CurrentComponent=0;CurrentComponent<NumberOfComponents;CurrentComponent++)
      {
        if(Components[CurrentComponent].FractionOfWidomMove>0.0)
          WidomMove();
      }

      // evolve the system a full time step
      Integration();

      // update the current energy-drift
      Drift[CurrentSystem]+=fabs((ConservedEnergy[CurrentSystem]-ReferenceEnergy[CurrentSystem])/
            ReferenceEnergy[CurrentSystem]);

      if(Drift[CurrentSystem]/(CurrentCycle+1.0)>1e2)
      {
        fprintf(OutputFilePtr[CurrentSystem],"\n\nERROR: unstable integration (energy drift %g > 1e2, simulation stopped)\n\n",Drift[CurrentSystem]/(CurrentCycle+1.0));
        fprintf(OutputFilePtr[CurrentSystem],"Check that: 1) all interaction are defined properly\n");
        fprintf(OutputFilePtr[CurrentSystem],"            2) the time step is not too large\n");
        fprintf(OutputFilePtr[CurrentSystem],"            3) the system is equilibrated\n\n");
        fflush(OutputFilePtr[CurrentSystem]);
        exit(0);
      }
    }

    for(CurrentSystem=0;CurrentSystem<NumberOfSystems;CurrentSystem++)
    {
      SampleRadialDistributionFunction(SAMPLE);
      SampleProjectedLengthsDistributionFunction(SAMPLE);
      SampleProjectedAnglesDistributionFunction(SAMPLE);
      SampleNumberOfMoleculesHistogram(SAMPLE);
      SamplePositionHistogram(SAMPLE);
      SampleFreeEnergyProfile(SAMPLE);
      SampleEndToEndDistanceHistogram(SAMPLE);
      SampleEnergyHistogram(SAMPLE);
      SampleFrameworkSpacingHistogram(SAMPLE);
      SampleResidenceTimes(SAMPLE);
      SampleDistanceHistogram(SAMPLE);
      SampleBendAngleHistogram(SAMPLE);
      SampleDihedralAngleHistogram(SAMPLE);
      SampleAngleBetweenPlanesHistogram(SAMPLE);
      SampleMoleculePropertyHistogram(SAMPLE);
      SampleInfraRedSpectra(SAMPLE);
      SampleMeanSquaredDisplacementOrderN(SAMPLE);
      SampleVelocityAutoCorrelationFunctionOrderN(SAMPLE);
      SampleRotationalVelocityAutoCorrelationFunctionOrderN(SAMPLE);
      SampleMolecularOrientationAutoCorrelationFunctionOrderN(SAMPLE);
      SampleBondOrientationAutoCorrelationFunctionOrderN(SAMPLE);
      SampleMeanSquaredDisplacement(SAMPLE);
      SampleVelocityAutoCorrelationFunction(SAMPLE);
      SampleDensityProfile3DVTKGrid(SAMPLE);
      SampleCationAndAdsorptionSites(SAMPLE);
      SampleDcTSTConfigurationFiles(SAMPLE);
      SamplePDBMovies(SAMPLE,-1);
    }

    if((CurrentCycle>0)&&(WriteBinaryRestartFileEvery>0)&&(CurrentCycle%WriteBinaryRestartFileEvery==0))
      WriteBinaryRestartFiles();

    ContinueAfterCrashLabel3:;

    for(CurrentSystem=0;CurrentSystem<NumberOfSystems;CurrentSystem++)
    {
      // regulary output sampling function
      SampleRadialDistributionFunction(PRINT);
      SampleProjectedLengthsDistributionFunction(PRINT);
      SampleProjectedAnglesDistributionFunction(PRINT);
      SampleNumberOfMoleculesHistogram(PRINT);
      SamplePositionHistogram(PRINT);
      SampleFreeEnergyProfile(PRINT);
      SampleEndToEndDistanceHistogram(PRINT);
      SampleEnergyHistogram(PRINT);
      SampleFrameworkSpacingHistogram(PRINT);
      SampleResidenceTimes(PRINT);
      SampleDistanceHistogram(PRINT);
      SampleBendAngleHistogram(PRINT);
      SampleDihedralAngleHistogram(PRINT);
      SampleAngleBetweenPlanesHistogram(PRINT);
      SampleMoleculePropertyHistogram(PRINT);
      SampleInfraRedSpectra(PRINT);
      SampleMeanSquaredDisplacementOrderN(PRINT);
      SampleVelocityAutoCorrelationFunctionOrderN(PRINT);
      SampleRotationalVelocityAutoCorrelationFunctionOrderN(PRINT);
      SampleMolecularOrientationAutoCorrelationFunctionOrderN(PRINT);
      SampleBondOrientationAutoCorrelationFunctionOrderN(PRINT);
      SampleMeanSquaredDisplacement(PRINT);
      SampleVelocityAutoCorrelationFunction(PRINT);
      SampleDensityProfile3DVTKGrid(PRINT);
      SampleCationAndAdsorptionSites(PRINT);
      SampleDcTSTConfigurationFiles(PRINT);
      if(Movies[CurrentSystem]&&(CurrentCycle%WriteMoviesEvery[CurrentSystem]==0))
        SamplePDBMovies(PRINT,-1);
    }
  }

  if(WriteBinaryRestartFileEvery>0)
    WriteBinaryRestartFiles();

  // finalize and clean up
  for(CurrentSystem=0;CurrentSystem<NumberOfSystems;CurrentSystem++)
  {
    SampleRadialDistributionFunction(FINALIZE);
    SampleProjectedLengthsDistributionFunction(FINALIZE);
    SampleProjectedAnglesDistributionFunction(FINALIZE);
    SampleNumberOfMoleculesHistogram(FINALIZE);
    SamplePositionHistogram(FINALIZE);
    SampleFreeEnergyProfile(FINALIZE);
    SampleEndToEndDistanceHistogram(FINALIZE);
    SampleEnergyHistogram(FINALIZE);
    SampleFrameworkSpacingHistogram(FINALIZE);
    SampleResidenceTimes(FINALIZE);
    SampleDistanceHistogram(FINALIZE);
    SampleBendAngleHistogram(FINALIZE);
    SampleDihedralAngleHistogram(FINALIZE);
    SampleAngleBetweenPlanesHistogram(FINALIZE);
    SampleMoleculePropertyHistogram(FINALIZE);
    SampleInfraRedSpectra(FINALIZE);
    SampleMeanSquaredDisplacementOrderN(FINALIZE);
    SampleVelocityAutoCorrelationFunctionOrderN(FINALIZE);
    SampleRotationalVelocityAutoCorrelationFunctionOrderN(FINALIZE);
    SampleMolecularOrientationAutoCorrelationFunctionOrderN(FINALIZE);
    SampleBondOrientationAutoCorrelationFunctionOrderN(FINALIZE);
    SampleMeanSquaredDisplacement(FINALIZE);
    SampleVelocityAutoCorrelationFunction(FINALIZE);
    SampleDensityProfile3DVTKGrid(FINALIZE);
    SampleCationAndAdsorptionSites(FINALIZE);
    SampleDcTSTConfigurationFiles(FINALIZE);
    SamplePDBMovies(FINALIZE,-1);
  }

  // print post-status
  PrintPostSimulationStatus();
  CloseOutputFile();
}
void GlobalMinimumSimulation(void)
{
  int i,j,k,l;
  int success;
  REAL ran,GlobalMinimumEnergy,UInitial,UAfterMC;

  success=0;

  GlobalMinimumEnergy=EnergyOverlapCriteria;

  OpenOutputFile();

  PrintPreSimulationStatus();

  for(k=0;k<NumberOfCycles;k++)
  {
    do
    {
      CurrentSystem=0;
      for(i=0;i<NumberOfAdsorbateMolecules[0];i++)
        RemoveAdsorbateMolecule();

      for(i=0;i<NumberOfCationMolecules[0];i++)
        RemoveCationMolecule();

      for(j=0;j<NumberOfComponents;j++)
      {
        if(Components[j].CreateNumberOfMolecules[0]>0)
        {
          CurrentSystem=0;
          if(Components[j].ExtraFrameworkMolecule)
            MakeInitialCations(Components[j].CreateNumberOfMolecules[0],j);
          else
            MakeInitialAdsorbates(Components[j].CreateNumberOfMolecules[0],j);
        }
      }
      CalculateForce();
      UInitial=UTotal[0];

      for(l=0;l<NumberOfInitializationCycles;l++)
      {
        for(j=0;j<MAX2(MinimumInnerCycles,NumberOfAdsorbateMolecules[CurrentSystem]+NumberOfCationMolecules[CurrentSystem]);j++)
        {
          // choose component at random
          CurrentComponent=(int)(RandomNumber()*(REAL)NumberOfComponents);

          // choose the Monte Carlo move at random
          ran=RandomNumber();

          if(Components[CurrentComponent].ExtraFrameworkMolecule)
          {
            if(ran<Components[CurrentComponent].ProbabilityTranslationMove)
              TranslationMoveCation();
            if(ran<Components[CurrentComponent].ProbabilityRotationMove)
              RotationMoveCation();
            else if(ran<Components[CurrentComponent].ProbabilityReinsertionMove)
              ReinsertionCationMove();
          }
          else
          {
            if(ran<Components[CurrentComponent].ProbabilityTranslationMove)
              TranslationMoveAdsorbate();
            if(ran<Components[CurrentComponent].ProbabilityRotationMove)
              RotationMoveAdsorbate();
            else if(ran<Components[CurrentComponent].ProbabilityReinsertionMove)
              ReinsertionAdsorbateMove();
          }
        }
      }


      CalculateForce();
      UAfterMC=UTotal[0];

      // do the minimization as
      //success=BakerMinimizationNoOutput();
      if(success==0)
        fprintf(OutputFilePtr[0],"Minimization failed to convergence within %d steps\n",MaximumNumberOfMinimizationSteps);
    } while(success==0);

    // recompute energy
    CalculateForce();
    CurrentSystem=0;
    fprintf(OutputFilePtr[0],"iteration: %d Energy before Monte-Carlo: %18.10f [K] Energy after Monte-Carlo: %18.10f [K]\n",
      k,UInitial*ENERGY_TO_KELVIN,UAfterMC*ENERGY_TO_KELVIN);
    fflush(OutputFilePtr[0]);

    if(UTotal[0]<GlobalMinimumEnergy)
    {
      fprintf(OutputFilePtr[0],"found lower new minimum, positions saved to restart-file\n");
      GlobalMinimumEnergy=UTotal[0];
      PrintRestartFile();
    }

    fprintf(OutputFilePtr[0],"\t\tMinimization steps: %d Minimized energy: %18.10f [K] (%18.10f [kJ/mol]) Global minimum: %18.10f (%18.10f [kJ/mol])\n",
        success,UTotal[0]*ENERGY_TO_KELVIN,UTotal[0]*ENERGY_TO_KJ_PER_MOL,GlobalMinimumEnergy*ENERGY_TO_KELVIN,GlobalMinimumEnergy*ENERGY_TO_KJ_PER_MOL);
    fflush(OutputFilePtr[0]);
  }


  PrintPostSimulationStatus();
  CloseOutputFile();
}
Example #16
0
int main(int argc, char** argv) {
  char *input_path = 0;
  char *output_path = 0;
  char *dictionary_path = 0;
  int force = 0;
  int quality = 11;
  int decompress = 0;
  int repeat = 1;
  int verbose = 0;
  int lgwin = 0;
  clock_t clock_start;
  int i;
  ParseArgv(argc, argv, &input_path, &output_path, &dictionary_path, &force,
            &quality, &decompress, &repeat, &verbose, &lgwin);
  clock_start = clock();
  for (i = 0; i < repeat; ++i) {
    FILE* fin = OpenInputFile(input_path);
    FILE* fout = OpenOutputFile(output_path, force || repeat);
    int is_ok = 0;
    if (decompress) {
      is_ok = Decompress(fin, fout, dictionary_path);
    } else {
      is_ok = Compress(quality, lgwin, fin, fout, dictionary_path);
    }
    if (!is_ok) {
      unlink(output_path);
      exit(1);
    }
    if (fclose(fin) != 0) {
      perror("fclose");
      exit(1);
    }
    if (fclose(fout) != 0) {
      perror("fclose");
      exit(1);
    }
  }
  if (verbose) {
    clock_t clock_end = clock();
    double duration = (double)(clock_end - clock_start) / CLOCKS_PER_SEC;
    int64_t uncompressed_size;
    double uncompressed_bytes_in_MB;
    if (duration < 1e-9) {
      duration = 1e-9;
    }
    uncompressed_size = FileSize(decompress ? output_path : input_path);
    if (uncompressed_size == -1) {
      fprintf(stderr, "failed to determine uncompressed file size\n");
      exit(1);
    }
    uncompressed_bytes_in_MB =
        (double)(repeat * uncompressed_size) / (1024.0 * 1024.0);
    if (decompress) {
      printf("Brotli decompression speed: ");
    } else {
      printf("Brotli compression speed: ");
    }
    printf("%g MB/s\n", uncompressed_bytes_in_MB / duration);
  }
  return 0;
}
Example #17
0
extern "C" int sfkl_Decode(const char *InFileName, const char *ReqOutFileName)
{
	char	OutFileName[MAX_FILEPATH];	// File name for current output file
	int	NumLoops;			// Number of loops before screen update etc.

	BLOCK_DATA	Blk;
	memset(&Blk, 0, sizeof(Blk));
	V2_FILEHEADER	*FileHeader = &Blk.FileHeader;

	// NB: We keep 2 buffers with pointers in Blk->SrcBuf and Blk->DstBuf
        // Generally we process from SrcBuf to DstBuf then swap the pointers,
	// so that current data is always at SrcBuf

        // NB: On MacOS/GNU C, the following allocation of Zbuf1 and Zbuf2 causes "segmentation fault"
	// BYTE	Zbuf1[ZBUF_SIZE];					// Buffer1
	// BYTE	Zbuf2[ZBUF_SIZE];					// Buffer2
        // so instead...
        
        #if 0
	static BYTE	Zbuf1[ZBUF_SIZE];				// Buffer1
	static BYTE	Zbuf2[ZBUF_SIZE];				// Buffer2
        
        #else
        if (Zbuf1 == NULL) Zbuf1 = (BYTE *) calloc(ZBUF_SIZE, sizeof(BYTE));
        if (Zbuf2 == NULL) Zbuf2 = (BYTE *) calloc(ZBUF_SIZE, sizeof(BYTE));
        
        if (Zbuf1 == NULL  ||  Zbuf2 == NULL)
            return EndProcess(SFARKLIB_ERR_MALLOC);
        #endif
        
	Blk.SrcBuf = (AWORD *) Zbuf1;					// Point to Zbuf1
	Blk.DstBuf = (AWORD *) Zbuf2;					// Point to Zbuf2

	// Initialisation...
	BioDecompInit();						// Initialise bit i/o
	LPCinit();							// Init LPC
	GlobalErrorFlag = SFARKLIB_SUCCESS;

	// Open input (.sfArk) file and read the header...
	OpenInputFile(InFileName);
	if (GlobalErrorFlag)  return EndProcess(GlobalErrorFlag);				// Something went wrong?
	ReadHeader(FileHeader, Zbuf1, ZBUF_SIZE);

	if (GlobalErrorFlag)  return EndProcess(GlobalErrorFlag);				// Something went wrong?

	if (ReqOutFileName == NULL)							// If no output filename requested
		ReqOutFileName = FileHeader->FileName;

	if ((FileHeader->Flags & FLAGS_License) != 0)		// License file exists?
	{
		if (ExtractTextFile(&Blk, FLAGS_License) == 0)
			return EndProcess(GlobalErrorFlag);
	}

	if ((FileHeader->Flags & FLAGS_Notes) != 0)		// Notes file exists?
	{
		if (ExtractTextFile(&Blk, FLAGS_Notes) == 0)
			return EndProcess(GlobalErrorFlag);
	}

        // Use original file extension for OutFileName...
        strncpy(OutFileName, ReqOutFileName, sizeof(OutFileName));			// Copy output filename
        OpenOutputFile(OutFileName);																		// Create the main output file...

	// Set the decompression parameters...
	switch (FileHeader->CompMethod)		// Depending on compression method that was used...
	{
		case COMPRESSION_v2Max:
		{
			//msg("Compression: Max\n");
			Blk.ReadSize = 4096;
			Blk.MaxLoops = 3;
			Blk.MaxBD4Loops = 5;
			Blk.nc = 128;
			Blk.WinSize = OPTWINSIZE;
			NumLoops = 2 * 4096 / Blk.ReadSize;
			break;
		}
		case COMPRESSION_v2Standard:
		{
			//printf("Compression: Standard\n");
			Blk.MaxLoops = 3;
			Blk.MaxBD4Loops = 3;
			Blk.ReadSize = 4096;
			Blk.nc = 8;
			Blk.WinSize = OPTWINSIZE;
			NumLoops = 50 * 4096 / Blk.ReadSize;
			break;
		}
		case COMPRESSION_v2Fast:
		{
			//printf("Compression: Fast\n");
			Blk.MaxLoops = 20;
			Blk.MaxBD4Loops = 20;
			Blk.ReadSize = 1024;
			Blk.WinSize = OPTWINSIZE;
			NumLoops = 300 * 4096 / Blk.ReadSize;
			break;
		}
		case COMPRESSION_v2Turbo:
		{
			//printf("Compression: Turbo\n");
			Blk.MaxLoops = 3;
			Blk.MaxBD4Loops = 0;
			Blk.ReadSize = 4096;
			Blk.WinSize = OPTWINSIZE << 3;
			NumLoops = 400 * 4096 / Blk.ReadSize;
			break;
		}
		default:
		{
			sprintf(MsgTxt, "Unknown Compression Method: %d%s", FileHeader->CompMethod, CorruptedMsg);
                        GlobalErrorFlag = SFARKLIB_ERR_INCOMPATIBLE;
			msg(MsgTxt, MSG_PopUp);
			return EndProcess(GlobalErrorFlag);
		}
	}

	// Process the main file...
        Blk.FileSection = PRE_AUDIO;		// We start with pre-audio data

        ULONG ProgressUpdateInterval = Blk.FileHeader.OriginalSize / 100; // Calculate progress update
	ULONG NextProgressUpdate = ProgressUpdateInterval;
        int ProgressPercent = 0;
	UpdateProgress(0);

	//int BlockNum = 0;
	for (Blk.FileSection = PRE_AUDIO; Blk.FileSection != FINISHED; )
	{
            for (int BlockCount = 0; BlockCount < NumLoops  &&  Blk.FileSection != FINISHED; BlockCount++)
            {
                //printf("Block: %d\n", ++BlockNum);
		ProcessNextBlock(&Blk);
			
		while (Blk.TotBytesWritten >= NextProgressUpdate)  	// Further 1% done since last UpdateProgress?
                {
                    UpdateProgress(++ProgressPercent);
                    NextProgressUpdate += ProgressUpdateInterval;
		}
  		if (GlobalErrorFlag)  return EndProcess(GlobalErrorFlag);
            }
            // CheckForCancel();
            if (GlobalErrorFlag)  return EndProcess(GlobalErrorFlag);
	}
	
	if (ProgressPercent != 100)  UpdateProgress(100);

    // Check the CheckSum...
    if (Blk.FileCheck != FileHeader->FileCheck)
    {
        sprintf(MsgTxt, "CheckSum Fail!%s",CorruptedMsg);
	msg(MsgTxt, MSG_PopUp);
        //sprintf(MsgTxt, "Calc check %lx", Blk.FileCheck);
	//msg(MsgTxt, MSG_PopUp);
	GlobalErrorFlag = SFARKLIB_ERR_FILECHECK;
	return EndProcess(GlobalErrorFlag);
    }

    sprintf(MsgTxt, "Created %s (%ld kb) successfully.", ReqOutFileName, Blk.TotBytesWritten/1024);
    msg(MsgTxt, 0);
    
    return EndProcess(GlobalErrorFlag);
}
Example #18
0
// ==============================================================
// Extract License & Notes files
// These are stored as 4-bytes length, followed by length-bytes of compressed data
int	ExtractTextFile(BLOCK_DATA *Blk, ULONG FileType)
{
		ULONG n, m;
		BYTE *zSrcBuf = (BYTE *) Blk->SrcBuf;
		BYTE *zDstBuf = (BYTE *) Blk->DstBuf;

		const char *FileExt;
		if (FileType == FLAGS_License)
			FileExt = LicenseExt;
		else if (FileType == FLAGS_Notes)
			FileExt = NotesExt;
		else
			return 0;

		// NB:Can't use BioReadBuf... aligment problems? Yet it works for ProcessNextBlock() !!??
		// Ok, can use ReadInputFile here cause everythjing is whole no. of bytes...

		//BioReadBuf((BYTE *)&n, sizeof(n));					// Read length of block from file
	  ReadInputFile((BYTE *)&n, sizeof(n));					// Read length of block from file
	  FixEndian(&n, sizeof(n));										// Fix endian

		if (n <= 0  ||  n > ZBUF_SIZE)								// Check for valid block length
		{
			sprintf(MsgTxt, "ERROR - Invalid length for %s file (apparently %ld bytes) %s", FileExt, n, CorruptedMsg);
			msg(MsgTxt, MSG_PopUp);
			GlobalErrorFlag = SFARKLIB_ERR_CORRUPT;
			return 0;
		}

		//BioReadBuf(zSrcBuf, n);																					// Read the block
	  ReadInputFile((BYTE *)zSrcBuf, n);																// Read the block
		m = UnMemcomp(zSrcBuf, n, zDstBuf, ZBUF_SIZE);										// Uncompress
		Blk->FileCheck = adler32(Blk->FileCheck, zDstBuf, m);	   					// Accumulate checksum
		if (GlobalErrorFlag  ||  m > ZBUF_SIZE)														// Uncompressed ok & size is valid?
			return 0;

		// Write file - Use original file name plus specified extension for OutFileName...
		char OutFileName[MAX_FILENAME];
		strncpy(OutFileName, Blk->FileHeader.FileName, sizeof(OutFileName));	// copy output filename
		ChangeFileExt(OutFileName, FileExt, sizeof(OutFileName));
		OpenOutputFile(OutFileName);	// Create notes / license file
		WriteOutputFile(zDstBuf, m);																			// and write to output file
		CloseOutputFile();
		if (FileType == FLAGS_License)
		{
                    sprintf(MsgTxt, "Created license file: %s", OutFileName);
                    msg(MsgTxt, 0);
			if (GetLicenseAgreement((const char *)zDstBuf, OutFileName) == 0)
			{
				GlobalErrorFlag = SFARKLIB_ERR_LICENSE;
				return EndProcess(0);
			}
		}
		else if (FileType == FLAGS_Notes)
                {
                    sprintf(MsgTxt, "Created notes file: %s", OutFileName);
                    msg(MsgTxt, 0);
                    DisplayNotes((const char *)zDstBuf, OutFileName);
                }

		return 1;
}
Example #19
0
void	CAAudioFileConverter::ConvertFile(const ConversionParameters &_params)
{
	FSRef destFSRef;
	UInt32 propertySize;
	CAStreamBasicDescription destFormat;
	CAAudioChannelLayout origSrcFileLayout, srcFileLayout, destFileLayout;
	bool openedSourceFile = false, createdOutputFile = false;
	
	mParams = _params;
	mReadBuffer = NULL;
	mReadPtrs = NULL;
	CABufferList *writeBuffer = NULL;
	CABufferList *writePtrs = NULL;
	
	PrepareConversion();

	try {
		if (TaggedDecodingFromCAF())
			ReadCAFInfo();
		OpenInputFile();
		openedSourceFile = true;
		
		// get input file's format
		const CAStreamBasicDescription &srcFormat = mSrcFile.GetFileDataFormat();
		if (mParams.flags & kOpt_Verbose) {
			printf("Input file: %s, %qd frames\n", mParams.input.filePath ? basename(mParams.input.filePath) : "?", 
				mSrcFile.GetNumberFrames());
		}
		mSrcFormat = srcFormat;
		
		bool encoding = !destFormat.IsPCM();
		bool decoding = !srcFormat.IsPCM();
		
		// prepare output file's format
		destFormat = mParams.output.dataFormat;

		if (!encoding && destFormat.mSampleRate == 0.)
			// on encode, it's OK to have a 0 sample rate; ExtAudioFile will get the SR from the converter and set it on the file.
			// on decode or PCM->PCM, a sample rate of 0 is interpreted as using the source sample rate
			destFormat.mSampleRate = srcFormat.mSampleRate;
		
		// source channel layout
		srcFileLayout = mSrcFile.GetFileChannelLayout();
		origSrcFileLayout = srcFileLayout;
		if (mParams.input.channelLayoutTag != 0) {
			XThrowIf(AudioChannelLayoutTag_GetNumberOfChannels(mParams.input.channelLayoutTag)
				!= srcFormat.mChannelsPerFrame, -1, "input channel layout has wrong number of channels for file");
			srcFileLayout = CAAudioChannelLayout(mParams.input.channelLayoutTag);
			mSrcFile.SetFileChannelLayout(srcFileLayout);
		}
		
		// destination channel layout
		int outChannels = mParams.output.channels;
		if (mParams.output.channelLayoutTag != 0) {
			// use the one specified by caller, if any
			destFileLayout = CAAudioChannelLayout(mParams.output.channelLayoutTag);
		} else if (srcFileLayout.IsValid()) {
			// otherwise, assume the same as the source, if any
			destFileLayout = srcFileLayout;
		}
		if (destFileLayout.IsValid()) {
			// the output channel layout specifies the number of output channels
			if (outChannels != -1)
				XThrowIf((unsigned)outChannels != destFileLayout.NumberChannels(), -1,
					"output channel layout has wrong number of channels");
			else
				outChannels = destFileLayout.NumberChannels();
		}

		if (!(mParams.flags & kOpt_NoSanitizeOutputFormat)) {
			// adjust the output format's channels; output.channels overrides the channels
			if (outChannels == -1)
				outChannels = srcFormat.mChannelsPerFrame;
			if (outChannels > 0) {
				destFormat.mChannelsPerFrame = outChannels;
				destFormat.mBytesPerPacket *= outChannels;
				destFormat.mBytesPerFrame *= outChannels;
			}
		
			// use AudioFormat API to clean up the output format
			propertySize = sizeof(AudioStreamBasicDescription);
			XThrowIfError(AudioFormatGetProperty(kAudioFormatProperty_FormatInfo, 0, NULL, &propertySize, &destFormat),
					"get destination format info");
		}
		OpenOutputFile(srcFormat, destFormat, destFSRef, destFileLayout);
		createdOutputFile = true;
		mDestFormat = destFormat;
		
		// set up client formats
		CAStreamBasicDescription srcClientFormat, destClientFormat;
		{
			CAAudioChannelLayout srcClientLayout, destClientLayout;
			
			if (encoding) {
				if (decoding) {
					// transcoding
//					XThrowIf(encoding && decoding, -1, "transcoding not currently supported");
					
					if (srcFormat.mChannelsPerFrame > 2 || destFormat.mChannelsPerFrame > 2)
						CAXException::Warning("Transcoding multichannel audio may not handle channel layouts correctly", 0);
					srcClientFormat.SetCanonical(std::min(srcFormat.mChannelsPerFrame, destFormat.mChannelsPerFrame), true);
					srcClientFormat.mSampleRate = std::max(srcFormat.mSampleRate, destFormat.mSampleRate);
					mSrcFile.SetClientFormat(srcClientFormat, NULL);
					
					destClientFormat = srcClientFormat;
				} else {
					// encoding
					srcClientFormat = srcFormat;
					destClientFormat = srcFormat;
				}
				// by here, destClientFormat will have a valid sample rate
				destClientLayout = srcFileLayout.IsValid() ? srcFileLayout : destFileLayout;

				mDestFile.SetClientFormat(destClientFormat, &destClientLayout);
			} else {
				// decoding or PCM->PCM
				if (destFormat.mSampleRate == 0.)
					destFormat.mSampleRate = srcFormat.mSampleRate;
		
				destClientFormat = destFormat;
				srcClientFormat = destFormat;
				srcClientLayout = destFileLayout;
				
				mSrcFile.SetClientFormat(srcClientFormat, &srcClientLayout);
			}
		}
		
		XThrowIf(srcClientFormat.mBytesPerPacket == 0, -1, "source client format not PCM"); 
		XThrowIf(destClientFormat.mBytesPerPacket == 0, -1, "dest client format not PCM"); 		
		if (encoding) {
			// set the bitrate
			if (mParams.output.bitRate != -1) {
				if (mParams.flags & kOpt_Verbose)
					printf("bitrate = %ld\n", mParams.output.bitRate);
				mDestFile.SetConverterProperty(kAudioConverterEncodeBitRate, sizeof(UInt32), &mParams.output.bitRate);
			}

			// set the codec quality
			if (mParams.output.codecQuality != -1) {
				if (mParams.flags & kOpt_Verbose)
					printf("codec quality = %ld\n", mParams.output.codecQuality);
				mDestFile.SetConverterProperty(kAudioConverterCodecQuality, sizeof(UInt32), &mParams.output.codecQuality);
			}

			// set the bitrate strategy -- called bitrate format in the codecs since it had already shipped
			if (mParams.output.strategy != -1) {
				if (mParams.flags & kOpt_Verbose)
					printf("strategy = %ld\n", mParams.output.strategy);
				mDestFile.SetConverterProperty(kAudioCodecBitRateFormat, sizeof(UInt32), &mParams.output.strategy);
			}
		}
		// set the SRC quality
		if (mParams.output.srcQuality != -1) {
			if (srcFormat.mSampleRate != 0. && destFormat.mSampleRate != 0. && srcFormat.mSampleRate != destFormat.mSampleRate) {
				if (mParams.flags & kOpt_Verbose)
					printf("SRC quality = %ld\n", mParams.output.srcQuality);
				if (encoding)
					mDestFile.SetConverterProperty(kAudioConverterSampleRateConverterQuality, sizeof(UInt32), &mParams.output.srcQuality);
				else
					mSrcFile.SetConverterProperty(kAudioConverterSampleRateConverterQuality, sizeof(UInt32), &mParams.output.srcQuality);
			}
		}
		if (decoding) {
			if (mParams.output.primeMethod != -1)
				mSrcFile.SetConverterProperty(kAudioConverterPrimeMethod, sizeof(UInt32), &mParams.output.primeMethod);
		}

		PrintFormats(&origSrcFileLayout);

		// prepare I/O buffers
		UInt32 bytesToRead = 0x10000;
		UInt32 framesToRead = bytesToRead;	// OK, ReadPackets will limit as appropriate
		ComputeReadSize(srcFormat, destFormat, bytesToRead, framesToRead);

//		const SInt64 totalFrames = mSrcFile.GetNumberFrames();
//#warning "GetNumberFrames() can be prohibitively slow for some formats"
		
		mReadBuffer = CABufferList::New("readbuf", srcClientFormat);
		mReadBuffer->AllocateBuffers(bytesToRead);
		mReadPtrs = CABufferList::New("readptrs", srcClientFormat);
		
		BeginConversion();
		
		while (true) {
			//XThrowIf(Progress(mSrcFile.Tell(), totalFrames), userCanceledErr, "user stopped");
				// this was commented out for awhile -- performance? make it optional?
			UInt32 nFrames = framesToRead;
			mReadPtrs->SetFrom(mReadBuffer);
			AudioBufferList *readbuf = &mReadPtrs->GetModifiableBufferList();
			
			mSrcFile.Read(nFrames, readbuf);
			//printf("read %ld of %ld frames\n", nFrames, framesToRead);
			if (nFrames == 0)
				break;

			mDestFile.Write(nFrames, readbuf);
			if (ShouldTerminateConversion())
				break;
		}
		
		if (decoding) {
			// fix up the destination file's length if necessary and possible
			SInt64 nframes = mSrcFile.GetNumberFrames();
			if (nframes != 0) {
				// only shorten, don't try to lengthen
				nframes = SInt64(ceil(nframes * destFormat.mSampleRate / srcFormat.mSampleRate));
				if (nframes < mDestFile.GetNumberFrames()) {
					mDestFile.SetNumberFrames(nframes);
				}
			}
		}
		EndConversion();
	}
	catch (...) {
		delete mReadBuffer;
		delete mReadPtrs;
		delete writeBuffer;
		delete writePtrs;
		if (!createdOutputFile)
			PrintFormats(&origSrcFileLayout);
		try { mSrcFile.Close(); } catch (...) { }
		try { mDestFile.Close(); } catch (...) { }
		if (createdOutputFile)
			unlink(mOutName);
		throw;
	}
	delete mReadBuffer;
	delete mReadPtrs;
	delete writeBuffer;
	delete writePtrs;
	mSrcFile.Close();
	mDestFile.Close();
	if (TaggedEncodingToCAF())
		WriteCAFInfo();
	
	if (mParams.flags & kOpt_Verbose) {
		// must close to flush encoder; GetNumberFrames() not necessarily valid until afterwards but then
		// the file is closed
		CAAudioFile temp;
		FSRef destFSRef;
		if (FSPathMakeRef((UInt8 *)mOutName, &destFSRef, NULL) == noErr) {
			temp.Open(destFSRef);
			printf("Output file: %s, %qd frames\n", basename(mOutName), temp.GetNumberFrames());
		}
	}
}