Example #1
0
static FObject LoadLibrary(FObject nam)
{
    FDontWait dw;
    FObject lp = R.LibraryPath;

    while (PairP(lp))
    {
        FAssert(StringP(First(lp)));

        FObject le = R.LibraryExtensions;

        while (PairP(le))
        {
            FAssert(StringP(First(le)));

            FObject libfn = LibraryNameFlat(First(lp), nam, First(le));
            FObject port = OpenInputFile(libfn);

            if (TextualPortP(port) == 0)
            {
                libfn = LibraryNameDeep(First(lp), nam, First(le));
                port = OpenInputFile(libfn);
            }

            if (TextualPortP(port))
            {
                WantIdentifiersPort(port, 1);

                for (;;)
                {
                    FObject obj = Read(port);

                    if (obj == EndOfFileObject)
                        break;

                    if (PairP(obj) == 0 || EqualToSymbol(First(obj), R.DefineLibrarySymbol) == 0)
                        RaiseExceptionC(R.Syntax, "define-library", "expected a library",
                                List(libfn, obj));

                    CompileLibrary(obj);
                }
            }

            FObject lib = FindLibrary(nam);
            if (LibraryP(lib))
                return(lib);

            le = Rest(le);
        }

        lp = Rest(lp);
    }

    FAssert(lp == EmptyListObject);

    return(NoValueObject);
}
MP3FileSource* MP3FileSource::createNew(UsageEnvironment& env, char const* fileName) {
  MP3FileSource* newSource = NULL;

  do {
#ifdef __LINUX__
    FILE* fid;
#else
    UFILE* fid;
#endif

    fid = OpenInputFile(env, fileName);
    if (fid == NULL) break;

    newSource = new MP3FileSource(env, fid);
    if (newSource == NULL) break;

    unsigned fileSize = (unsigned)GetFileSize(fileName, fid);
    newSource->assignStream(fid, fileSize);
    if (!newSource->initializeStream()) break;

    return newSource;
  } while (0);

  Medium::closeMedium(newSource);
  return NULL;
}
AMRAudioFileSource*
AMRAudioFileSource::createNew(UsageEnvironment& env, char const* fileName) {
  FILE* fid = NULL;
  Boolean magicNumberOK = True;
  do {

    fid = OpenInputFile(env, fileName);
    if (fid == NULL) break;

    // Now, having opened the input file, read the first few bytes, to
    // check the required 'magic number':
    magicNumberOK = False; // until we learn otherwise
    Boolean isWideband = False; // by default
    unsigned numChannels = 1; // by default
    char buf[100];
    // Start with the first 6 bytes (the first 5 of which must be "#!AMR"):
    if (fread(buf, 1, 6, fid) < 6) break;
    if (strncmp(buf, "#!AMR", 5) != 0) break; // bad magic #
    unsigned bytesRead = 6;
    
    // The next bytes must be "\n", "-WB\n", "_MC1.0\n", or "-WB_MC1.0\n"
    if (buf[5] == '-') {
      // The next bytes must be "WB\n" or "WB_MC1.0\n"
      if (fread(&buf[bytesRead], 1, 3, fid) < 3) break;
      if (strncmp(&buf[bytesRead], "WB", 2) != 0) break; // bad magic #
      isWideband = True;
      bytesRead += 3;
    }
    if (buf[bytesRead-1] == '_') {
      // The next bytes must be "MC1.0\n"
      if (fread(&buf[bytesRead], 1, 6, fid) < 6) break;
      if (strncmp(&buf[bytesRead], "MC1.0\n", 6) != 0) break; // bad magic #
      bytesRead += 6;

      // The next 4 bytes contain the number of channels:
      char channelDesc[4];
      if (fread(channelDesc, 1, 4, fid) < 4) break;
      numChannels = channelDesc[3]&0xF;
    } else if (buf[bytesRead-1] != '\n') {
      break; // bad magic #
    }

    // If we get here, the magic number was OK:
    magicNumberOK = True;

#ifdef DEBUG
    fprintf(stderr, "isWideband: %d, numChannels: %d\n",
	    isWideband, numChannels);
#endif
    return new AMRAudioFileSource(env, fid, isWideband, numChannels);
  } while (0);

  // An error occurred:
  CloseInputFile(fid);
  if (!magicNumberOK) {
    env.setResultMsg("Bad (or nonexistent) AMR file header");
  }
  return NULL;
}
/*====================================================================================
// Function	: default constructor, Initialize member variables.
// Pre		: None
// Post		: Initialize member variables.
=====================================================================================*/
Application::Application()
{
	OpenInputFile();		//불러들이고자 하는 파일 입력
	GetClientListFromFile();	// 파일로부터 고객 입력

	Sleep(1000);
	system("cls");
}
Boolean MPEG2TransportStreamIndexFile::openFid() {
  if (fFid == NULL && fFileName != NULL) {
    if ((fFid = OpenInputFile(envir(), fFileName)) != NULL) {
      fCurrentIndexRecordNum = 0;
    }
  }

  return fFid != NULL;
}
Example #6
0
//============================================================================//
void ReadVector_ASCII(char *path, char *fname, float **vec, int *dims, 
                      char *stopmsg) {
    ifstream file;
    OpenInputFile(file,path,fname,"ascii",stopmsg);
    ScanMesh_ASCII(file);        
    ReadVar_ASCII(file,vec[0],dims);
    ReadVar_ASCII(file,vec[1],dims);
    ReadVar_ASCII(file,vec[2],dims);
    file.close();
}
Example #7
0
//============================================================================//
void ReadScalar_ASCII(char *path, char *fname, float *&var, int *dims,
                      char *stopmsg) {
    // This function reads a scalar variable into the array var
    ifstream file;
    OpenInputFile(file,path,fname,"ascii",stopmsg);
    // OpenInputFile(fp,path,fname,"r",stopmsg);
    ScanMesh_ASCII(file);    
    ReadVar_ASCII(file, var, dims);
    file.close();
}
Example #8
0
int WindDecoder::SetDataSource(const char *url) {
    if (url == NULL) {
        ERROR ("url == NULL!");
        return -1;
    }

    mOperationLock.Lock ();
    int ret = Clear ();
    msUrl = url;
    ret = OpenInputFile (msUrl);
    mOperationLock.Unlock ();
    return ret;
}
ByteStreamFileSource*
ByteStreamFileSource::createNew(UsageEnvironment& env, char const* fileName,
				unsigned preferredFrameSize,
				unsigned playTimePerFrame) {
  FILE* fid = OpenInputFile(env, fileName);
  if (fid == NULL) return NULL;

  ByteStreamFileSource* newSource
    = new ByteStreamFileSource(env, fid, preferredFrameSize, playTimePerFrame);
  newSource->fFileSize = GetFileSize(fileName, fid);

  return newSource;
}
	void Loop()
	{
		UE_LOG(LogShaders, Log, TEXT("Entering job loop"));

		while(true)
		{
			TArray<FJobResult> JobResults;

			// Read & Process Input
			{
				FArchive* InputFilePtr = OpenInputFile();
				if(!InputFilePtr)
				{
					break;
				}

				UE_LOG(LogShaders, Log, TEXT("Processing shader"));
				LastCompileTime = FPlatformTime::Seconds();

				ProcessInputFromArchive(InputFilePtr, JobResults);

				// Close the input file.
				delete InputFilePtr;
			}

			// Prepare for output
			FArchive* OutputFilePtr = CreateOutputArchive();
			check(OutputFilePtr);
			WriteToOutputArchive(OutputFilePtr, JobResults);

			// Close the output file.
			delete OutputFilePtr;

			// Change the output file name to requested one
			IFileManager::Get().Move(*OutputFilePath, *TempFilePath);

			if (GShaderCompileUseXGE)
			{
				// To signal compilation completion, create a zero length file in the working directory.
				WriteXGESuccessFile(*WorkingDirectory);

				// We only do one pass per process when using XGE.
				break;
			}
		}

		UE_LOG(LogShaders, Log, TEXT("Exiting job loop"));
	}
Example #11
0
//============================================================================//
//############################################################################//
//============================================================================//
HYMDataObj::HYMDataObj(char vchar, char *data_path, char *fname_src,
                       int *dims, char *stopmsg, int nvals) {
    // Assign basic members:
    this->data_path = data_path;
    this->fname_src = fname_src;
    this->vchar = vchar;
    this->stopmsg = stopmsg;
    this->cycle_mask=NULL;
    this->times = NULL;
    
    // Verify the source data file:
    if(!VerifyInputFile(data_path,fname_src,"binary",stopmsg)) {
        char message[1001];
        sprintf(message,"      %s%c%s\n      %s%s\n      %s%s\n      %s",
                "The data for the variable ",vchar," was not found:",
                "    Data Path:    ",data_path,"    Missing File: ",fname_src,
                stopmsg);
        StopExecution(message);
    }
    
    // Open the source data file:
    OpenInputFile(this->file,data_path,this->fname_src,"binary",this->stopmsg);
    
    // Assign mesh and dimension attribute members:
    this->dims = dims;
    this->Ntot = dims[0]*dims[1]*dims[2];
    
    this->dims_in[0] = Nghost_q1 + dims[0] + Nghost_q2;
    this->dims_in[1] = Nghost_r1 + dims[1] + Nghost_r2;
    this->dims_in[2] = Nghost_s1 + dims[2] + Nghost_s2;
    this->Ntot_in = dims_in[0]*dims_in[1]*dims_in[2];
    
    // Assign data attribute members:
    this->nvals = nvals;
    if(nvals == 1)
        this->data_type = "scalar";
    else if(nvals == 3)
        this->data_type = "vector";
    else
        StopExecution("  Invalid nvals argument in HYMDataObj constructor.");
    this->record_length = (long)(5*intsize + (1+Ntot_in*nvals)*dblsize + 20);
    
    // Validate the source data file and build the time vector:
    this->ValidateSourceFile();
    this->GetTimes();
}
ByteStreamFileSource*
ByteStreamFileSource::createNew(UsageEnvironment& env, char const* fileName,
				unsigned preferredFrameSize,
				unsigned playTimePerFrame) {
  FILE* fid = OpenInputFile(env, fileName);
  if (fid == NULL) return NULL;

  Boolean deleteFidOnClose = fid == stdin ? False : True;
  ByteStreamFileSource* newSource
    = new ByteStreamFileSource(env, fid, deleteFidOnClose,
			       preferredFrameSize, playTimePerFrame);
  newSource->fFileSize = GetFileSize(fileName, fid);
  DEBUG_LOG(INF, "Create ByteStreamFileSource1:"
    "File size = %lld, preferredFrameSize = %u, playTimePerFrame = %u", 
    newSource->fFileSize, preferredFrameSize, playTimePerFrame);
  
  return newSource;
}
WAVAudioFileSource*
WAVAudioFileSource::createNew(UsageEnvironment& env, char const* fileName) {
  do {
    FILE* fid = OpenInputFile(env, fileName);
    if (fid == NULL) break;

    WAVAudioFileSource* newSource = new WAVAudioFileSource(env, fid);
    if (newSource != NULL && newSource->bitsPerSample() == 0) {
      // The WAV file header was apparently invalid.
      Medium::close(newSource);
      break;
    }

    newSource->fFileSize = (unsigned)GetFileSize(fileName, fid);

    return newSource;
  } while (0);

  return NULL;
}
Example #14
0
bool WebAppInputLine::OpenInputFile(C4P::FileRoot& f, const PathName& fileName)
{
  FILE* pFile = nullptr;

  if (!OpenInputFile(&pFile, fileName))
  {
    return false;
  }

  f.Attach(pFile, true);

#ifdef PASCAL_TEXT_IO
  not_implemented();
  get(f);
#endif

  pimpl->lastInputFileName = fileName;

  return true;
}
Example #15
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 #16
0
//============================================================================//
//============================================================================//
void HYMDataObj::ReadMesh_Binary(char *data_path, char* fname_mesh, int *dims,
                                 float **mesh_coords, char *stopmsg) {
    // This function loads the HYM mesh from a data file (3D or 2D)
    int k, kshift, Nq, Nr, Ns, Ntot;
    char str[1024];
    ifstream file;
    
    // Open the designated file:
    OpenInputFile(file,data_path,fname_mesh,"binary",stopmsg);

    // Scroll through unneeded variables:
    file.seekg(6*intsize,ios::beg);

    // Get the input dimensions:
    file.read((char*)&Nq,intsize);
    file.read((char*)&Nr,intsize);
    file.read((char*)&Ns,intsize);
    
    // Read the mesh coordinates:
    file.seekg(dblsize,ios::cur);
    double *q_buffer = new double[Nq];
    double *r_buffer = new double[Nr];
    double *s_buffer = new double[Ns];
    file.read((char*)q_buffer,Nq*dblsize);
    file.read((char*)r_buffer,Nr*dblsize);
    file.read((char*)s_buffer,Ns*dblsize);
    
    file.close();
    
    // Strip off the HYM ghost coordinates:
    StripGhostCoords(q_buffer,mesh_coords[0],Nq,Nghost_q1,Nghost_q2);
    StripGhostCoords(r_buffer,mesh_coords[1],Nr,Nghost_r1,Nghost_r2);
    StripGhostCoords(s_buffer,mesh_coords[2],Ns,Nghost_s1,Nghost_s2);
    
    // Validate the dims values:
    int fdims[ndims];
    fdims[0] = Nq - Nghost_q2 - Nghost_q1;
    fdims[1] = Nr - Nghost_r2 - Nghost_r1;
    fdims[2] = Ns - Nghost_s2 - Nghost_s1;
    HYMDataObj::CompareMeshDims(fdims,dims,fname_mesh,stopmsg);
}
Example #17
0
//============================================================================//
void ReadMesh_ASCII(char* path, char *fname, int* dims, float **mesh_coords,
                    double &time, char *stopmsg) {
    // This function loads the HYM mesh from a data files
    int Nq, Nr, Ns;
    char str[1024];
    ifstream file;
    
    // Open the designated file
    OpenInputFile(file,path,fname,"ascii",stopmsg);
    // Scroll through the header strings
    for(int i=0; i<3; i++)
        file >> str;
        
    // Get the time and dimension numbers
    file >> time;
    file >> Nq;
    file >> Nr;
    file >> Ns;
    
    // Get the z and r mappings
    float *q = new float[Nq];
    float *r = new float[Nr];
    float *s = new float[Ns];
    
    for(int i=0; i<Nq; i++)
        file >> q[i];
    for(int j=0; j<Nr; j++)
        file >> r[j];
    for(int k=0; k<Ns; k++)
        file >> s[k];    
    
    dims[0] = Nq;
    dims[1] = Nr;
    dims[2] = Ns;
    
    mesh_coords[0] = q;
    mesh_coords[1] = r;
    mesh_coords[2] = s;

    file.close();
}
Example #18
0
static int ProgramMode(int adx, int argc, FChS * argv[])
{
    FAssert(adx < argc);

    FObject nam = MakeStringS(argv[adx]);

    adx += 1;
    R.CommandLine = MakePair(MakeInvocation(adx, argv), MakeCommandLine(argc - adx, argv + adx));

    FObject port;
    {
        FDontWait dw;

        port = OpenInputFile(nam);
        if (TextualPortP(port) == 0)
        {
#ifdef FOMENT_WINDOWS
            printf("error: unable to open program: %S\n", argv[adx - 1]);
#endif // FOMENT_WINDOWS

#ifdef FOMENT_UNIX
            printf("error: unable to open program: %s\n", argv[adx - 1]);
#endif // FOMENT_UNIX
            return(Usage());
        }
    }

    FCh ch;

    // Skip #!/usr/local/bin/foment

    if (PeekCh(port, &ch) && ch == '#')
        ReadLine(port);

    FObject proc = CompileProgram(nam, port);

    ExecuteThunk(proc);
    ExitFoment();
    return(0);
}
Example #19
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 #20
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 #21
0
	void Loop()
	{
		UE_LOG(LogShaders, Log, TEXT("Entering job loop"));

		while(true)
		{
			TArray<FJobResult> JobResults;

			// Read & Process Input
			{
				FArchive* InputFilePtr = OpenInputFile();
				if(!InputFilePtr)
				{
					break;
				}

				UE_LOG(LogShaders, Log, TEXT("Processing shader"));
				LastCompileTime = FPlatformTime::Seconds();

				ProcessInputFromArchive(InputFilePtr, JobResults);

				// Close the input file.
				delete InputFilePtr;
			}

			// Prepare for output
			FArchive* OutputFilePtr = CreateOutputArchive();
			check(OutputFilePtr);
			WriteToOutputArchive(OutputFilePtr, JobResults);

			// Close the output file.
			delete OutputFilePtr;

#if PLATFORM_MAC || PLATFORM_LINUX
			// Change the output file name to requested one
			IFileManager::Get().Move(*OutputFilePath, *TempFilePath);
#endif

#if PLATFORM_SUPPORTS_NAMED_PIPES
			if (CommunicationMode == ThroughNamedPipeOnce || CommunicationMode == ThroughNamedPipe)
			{
				VerifyResult(Pipe.WriteInt32(TransferBufferOut.Num()), TEXT("Writing Transfer Size"));
				VerifyResult(Pipe.WriteBytes(TransferBufferOut.Num(), TransferBufferOut.GetData()), TEXT("Writing Transfer Buffer"));
//FPlatformMisc::LowLevelOutputDebugStringf(TEXT("*** Closing pipe...\n"));
				Pipe.Destroy();

				if (CommunicationMode == ThroughNamedPipeOnce)
				{
					// Give up CPU time while we are waiting
					FPlatformProcess::Sleep(0.02f);
					break;
				}

				LastConnectionTime = FPlatformTime::Seconds();
			}
#endif	// PLATFORM_SUPPORTS_NAMED_PIPES

			if (GShaderCompileUseXGE)
			{
				// To signal compilation completion, create a zero length file in the working directory.
				WriteXGESuccessFile(*WorkingDirectory);

				// We only do one pass per process when using XGE.
				break;
			}
		}

		UE_LOG(LogShaders, Log, TEXT("Exiting job loop"));
	}
Example #22
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());
		}
	}
}