示例#1
0
// _______________________________________________________________________________________
//
void	CAAudioFile::Write(UInt32 numPackets, const AudioBufferList *data)
{
	if (mIOBufferList.mBuffers[0].mData == NULL) {
#if DEBUG
		printf("warning: CAAudioFile::AllocateBuffers called from WritePackets\n");
#endif
		AllocateBuffers();
	}

	if (mMode == kPreparingToWrite)
		mMode = kWriting;
	else
		XThrowIf(mMode != kWriting, kExtAudioFileError_InvalidOperationOrder, "can't write to this file");
	if (mConverter != NULL) {
		mWritePackets = numPackets;
		mWriteBufferList->SetFrom(data);
		WritePacketsFromCallback(WriteInputProc, this);
	} else {
		StartTiming(this, write);
		XThrowIfError(AudioFileWritePackets(mAudioFile, mUseCache, data->mBuffers[0].mDataByteSize,
						NULL, mPacketMark, &numPackets, data->mBuffers[0].mData),
						"write audio file");
		ElapsedTime(this, write, mTicksInIO);
#if VERBOSE_IO
		printf("CAAudioFile::WritePackets: wrote %ld packets at %qd, %ld bytes\n", numPackets, mPacketMark, data->mBuffers[0].mDataByteSize);
#endif
		//mNumberPackets =
		mPacketMark += numPackets;
		if (mFileDataFormat.mFramesPerPacket > 0)
			mFrameMark += numPackets * mFileDataFormat.mFramesPerPacket;
		// else: shouldn't happen since we're only called when there's no converter
	}
}
示例#2
0
int Message::Read(const char *filename)
{
    FILE *msgfile;
    int size;
    char cur;

    if(!(msgfile=fopen(filename,"r"))) return 0;

    //get file size
    fseek(msgfile,0,SEEK_END);
    size=ftell(msgfile)+1;
    fseek(msgfile,0,SEEK_SET);

    AllocateBuffers(size);

    if(!cipher || !plain) return 0;

    //read from file
    msg_len=0;

    while(fscanf(msgfile,"%c",&cur)!=EOF)
    {
        if(!IS_ASCII(cur) || cur==' ') continue;
        cipher[msg_len++]=cur;
    }

    cipher[msg_len]='\0';
    fclose(msgfile);

    SetInfo(true);

    return msg_len;
}
示例#3
0
status_t
SoundPlayNode::SetBufferGroup(const media_source& forSource,
	BBufferGroup* newGroup)
{
	CALLED();

	// is this our output?
	if (forSource != fOutput.source) {
		TRACE("SoundPlayNode::SetBufferGroup returning B_MEDIA_BAD_SOURCE\n");
		return B_MEDIA_BAD_SOURCE;
	}

	// Are we being passed the buffer group we're already using?
	if (newGroup == fBufferGroup)
		return B_OK;

	// Ahh, someone wants us to use a different buffer group. At this point we
	// delete the one we are using and use the specified one instead.
	// If the specified group is NULL, we need to recreate one ourselves, and
	// use *that*. Note that if we're caching a BBuffer that we requested
	// earlier, we have to Recycle() that buffer *before* deleting the buffer
	// group, otherwise we'll deadlock waiting for that buffer to be recycled!
	delete fBufferGroup;
		// waits for all buffers to recycle

	if (newGroup != NULL) {
		// we were given a valid group; just use that one from now on
		fBufferGroup = newGroup;
		return B_OK;
	}

	// we were passed a NULL group pointer; that means we construct
	// our own buffer group to use from now on
	return AllocateBuffers();
}
int mainCPU(int argc, char **argv) {
	amiSmallptCPU = 1;

	//fprintf(stderr, "Usage: %s\n", argv[0]);
	//fprintf(stderr, "Usage: %s <window width> <window height> <scene file>\n", argv[0]);
	/*
	if (argc == 4) {
		width = atoi(argv[1]);
		height = atoi(argv[2]);
		ReadScene(argv[3]);
	} else if (argc == 1) {
	*/
		spheres = CornellSpheres;
		sphereCount = sizeof(CornellSpheres) / sizeof(Sphere);

		vinit(camera.orig, 50.f, 45.f, 205.6f);
		vinit(camera.target, 50.f, 45 - 0.042612f, 204.6);
/*
	} else
		exit(-1);
*/
	UpdateCamera();

	/*------------------------------------------------------------------------*/

	AllocateBuffers();

	/*------------------------------------------------------------------------*/

	InitGlut(argc, argv, "SmallPT CPU V1.6 (Written by David Bucciarelli)");

    glutMainLoop( );

	return 0;
}
示例#5
0
int main(int argc, char *argv[]) {
	amiMandelCPU = 1;

	fprintf(stderr, "Usage: %s\n", argv[0]);
	fprintf(stderr, "Usage: %s <window width> <window height> <max. iterations>\n", argv[0]);

	if (argc == 4) {
		width = atoi(argv[4]);
		height = atoi(argv[5]);
		maxIterations = atoi(argv[1]);
	} else if (argc != 1)
		exit(-1);

	AllocateBuffers();
	UpdateMandel();

	//--------------------------------------------------------------------------

	InitGlut(argc, argv, "MandelCPU V1.3 (Written by David Bucciarelli)");

	glutMainLoop();

	//--------------------------------------------------------------------------

	return 0;
}
示例#6
0
void 
ESDSinkNode::Connect(status_t error, const media_source& source, const media_destination& destination, const media_format& format, char* io_name)
{
	CALLED();
	
	node_output *channel = FindOutput(source);
	
	// is this our output?
	if (channel == NULL)
	{
		fprintf(stderr, "ESDSinkNode::Connect returning (cause : B_MEDIA_BAD_SOURCE)\n");
		return;
	}
	
	// If something earlier failed, Connect() might still be called, but with a non-zero
	// error code.  When that happens we simply unreserve the connection and do
	// nothing else.
	if (error)
	{
		channel->fOutput.destination = media_destination::null;
		channel->fOutput.format = channel->fPreferredFormat;
		return;
	}

	// Okay, the connection has been confirmed.  Record the destination and format
	// that we agreed on, and report our connection name again.
	channel->fOutput.destination = destination;
	channel->fOutput.format = format;
	strncpy(io_name, channel->fOutput.name, B_MEDIA_NAME_LENGTH);

	// reset our buffer duration, etc. to avoid later calculations
	bigtime_t duration = channel->fOutput.format.u.raw_audio.buffer_size * 10000
			/ ( (channel->fOutput.format.u.raw_audio.format & media_raw_audio_format::B_AUDIO_SIZE_MASK)
				* channel->fOutput.format.u.raw_audio.channel_count) 
			/ ((int32)(channel->fOutput.format.u.raw_audio.frame_rate / 100));
	
	SetBufferDuration(duration);
	
	// Now that we're connected, we can determine our downstream latency.
	// Do so, then make sure we get our events early enough.
	media_node_id id;
	FindLatencyFor(channel->fOutput.destination, &fLatency, &id);
	PRINT(("\tdownstream latency = %Ld\n", fLatency));

	fInternalLatency = BufferDuration();
	PRINT(("\tbuffer-filling took %Ld usec on this machine\n", fInternalLatency));
	//SetEventLatency(fLatency + fInternalLatency);

	// Set up the buffer group for our connection, as long as nobody handed us a
	// buffer group (via SetBufferGroup()) prior to this.  That can happen, for example,
	// if the consumer calls SetOutputBuffersFor() on us from within its Connected()
	// method.
	if (!channel->fBufferGroup) 
		AllocateBuffers(*channel);
		
	// we are sure the thread is started
	StartThread();
}
示例#7
0
GLDEF_C void CallTestsL(void)
//
// Call all tests
//
{
    test.Title();
    test.Start(_L("Start Benchmarking ..."));

    test.Next(gSessionPath);

    ParseCommandLine();

    AllocateBuffers();
    RProcess().SetPriority(EPriorityBackground);

    TInt r = HAL::Get(HAL::EFastCounterFrequency, gFastCounterFreq);
    test_KErrNone(r);
    test.Printf(_L("HAL::EFastCounterFrequency %d\n"), gFastCounterFreq);

    test.Printf(_L("gReadCachingOn %d  gWriteCachingOn %d gFlushAfterWrite %d gFileSequentialModeOn %d\n"),
                gReadCachingOn, gWriteCachingOn, gFlushAfterWrite, gFileSequentialModeOn);

    TestFileSeek();

    // read once
    TestFileRead(KMaxFileSize, gMisalignedReadWrites, EFalse);

    // re-read
    TestFileRead(KMaxFileSize, gMisalignedReadWrites, ETrue);

    TestFileReadCPU(gMisalignedReadWrites);

    // append to file
    TestFileWrite(KMaxFileSize, gMisalignedReadWrites, EFalse);

    // update (overwrite) file
    TestFileWrite(KMaxFileSize, gMisalignedReadWrites, ETrue);

    TestFileWriteCPU(gMisalignedReadWrites);

    TestFileDelete();

//	TestDirRead();
//	PrintDirResults();
#ifdef SYMBIAN_ENABLE_64_BIT_FILE_SERVER_API
    TestLargeFileDelete();
#endif //SYMBIAN_ENABLE_64_BIT_FILE_SERVER_API

    TestMkDir();

    RecursiveRmDir(gSessionPath);

    DeAllocateBuffers();

    test.End();
    test.Close();
}
示例#8
0
void
SoundPlayNode::Connect(status_t error, const media_source& source,
	const media_destination& destination, const media_format& format,
	char* name)
{
	CALLED();

	// is this our output?
	if (source != fOutput.source) {
		TRACE("SoundPlayNode::Connect returning\n");
		return;
	}

	// If something earlier failed, Connect() might still be called, but with
	// a non-zero error code.  When that happens we simply unreserve the
	// connection and do nothing else.
	if (error) {
		fOutput.destination = media_destination::null;
		fOutput.format.type = B_MEDIA_RAW_AUDIO;
		fOutput.format.u.raw_audio = media_multi_audio_format::wildcard;
		return;
	}

	// Okay, the connection has been confirmed.  Record the destination and
	// format that we agreed on, and report our connection name again.
	fOutput.destination = destination;
	fOutput.format = format;
	strcpy(name, Name());

	// Now that we're connected, we can determine our downstream latency.
	// Do so, then make sure we get our events early enough.
	media_node_id id;
	FindLatencyFor(fOutput.destination, &fLatency, &id);
	TRACE("SoundPlayNode::Connect: downstream latency = %Ld\n", fLatency);

	// reset our buffer duration, etc. to avoid later calculations
	bigtime_t duration = ((fOutput.format.u.raw_audio.buffer_size * 1000000LL)
		/ ((fOutput.format.u.raw_audio.format
				& media_raw_audio_format::B_AUDIO_SIZE_MASK)
			* fOutput.format.u.raw_audio.channel_count))
		/ (int32)fOutput.format.u.raw_audio.frame_rate;
	SetBufferDuration(duration);
	TRACE("SoundPlayNode::Connect: buffer duration is %Ld\n", duration);

	fInternalLatency = (3 * BufferDuration()) / 4;
	TRACE("SoundPlayNode::Connect: using %Ld as internal latency\n",
		fInternalLatency);
	SetEventLatency(fLatency + fInternalLatency);

	// Set up the buffer group for our connection, as long as nobody handed us
	// a buffer group (via SetBufferGroup()) prior to this.
	// That can happen, for example, if the consumer calls SetOutputBuffersFor()
	// on us from within its Connected() method.
	if (!fBufferGroup)
		AllocateBuffers();
}
void ReInitCPU(const int reallocBuffers) {
	// Check if I have to reallocate buffers
	if (reallocBuffers) {
		FreeBuffers();
		AllocateBuffers();
	}

	UpdateCamera();
	currentSample = 0;
	UpdateRenderingCPU();
}
//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
//	WaveformViewDemo::Initialize
//
//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
OSStatus			SonogramViewDemo::Initialize()
{
	OSStatus result = AUEffectBase::Initialize();
	
	if(result == noErr )
	{
		AllocateBuffers();
	}
	
	return result;
}
示例#11
0
//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
//	WaveformViewDemo::Initialize
//
//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
ComponentResult		WaveformViewDemo::Initialize()
{
	ComponentResult result = AUEffectBase::Initialize();
	
	if(result == noErr )
	{
		AllocateBuffers();
	}
	
	return result;
}
示例#12
0
// _______________________________________________________________________________________
//
void	CAAudioFile::InitFileMaxPacketSize()
{
	LOG_FUNCTION("CAAudioFile::InitFileMaxPacketSize", "%p", this);
	UInt32 propertySize = sizeof(UInt32);
	OSStatus err = AudioFileGetProperty(mAudioFile, kAudioFilePropertyMaximumPacketSize,
		&propertySize, &mFileMaxPacketSize);
	if (err) {
		// workaround for 3361377: not all file formats' maximum packet sizes are supported
		if (!mFileDataFormat.IsPCM())
			XThrowIfError(err, "get audio file's maximum packet size");
		mFileMaxPacketSize = mFileDataFormat.mBytesPerFrame;
	}
	AllocateBuffers(true /* okToFail */);
}
示例#13
0
// _______________________________________________________________________________________
//
void	CAAudioFile::SetIOBuffer(void *buf)
{
	if (!mClientOwnsIOBuffer)
		delete[] (Byte *)mIOBufferList.mBuffers[0].mData;
	mIOBufferList.mBuffers[0].mData = buf;

	if (buf == NULL) {
		mClientOwnsIOBuffer = false;
		SetIOBufferSizeBytes(mIOBufferSizeBytes);
	} else {
		mClientOwnsIOBuffer = true;
		AllocateBuffers();
	}
//	printf("CAAudioFile::SetIOBuffer %p: %p, 0x%lx bytes, mClientOwns = %d\n", this, mIOBufferList.mBuffers[0].mData, mIOBufferSizeBytes, mClientOwnsIOBuffer);
}
示例#14
0
void Message::SetCipher(const char *new_cipher)
{
    int new_len=(int)strlen(new_cipher);

    if(new_len>msg_len) //realloacte buffers
    {
        DeleteBuffers();
        AllocateBuffers(new_len);
    }

    msg_len=new_len;

    strcpy(cipher,new_cipher);
    SetInfo(true);
}
示例#15
0
/**************************************************************************************
 * Function:    AACInitDecoder
 *
 * Description: allocate memory for platform-specific data
 *              clear all the user-accessible fields
 *              initialize SBR decoder if enabled
 *
 * Inputs:      none
 *
 * Outputs:     none
 *
 * Return:      handle to AAC decoder instance, 0 if malloc fails
 **************************************************************************************/
HAACDecoder AACInitDecoder(void)
{
	AACDecInfo *aacDecInfo;

	aacDecInfo = AllocateBuffers();
	if (!aacDecInfo)
		return 0;

#ifdef AAC_ENABLE_SBR
	if (InitSBR(aacDecInfo)) {
		AACFreeDecoder(aacDecInfo);
		return 0;
	}
#endif

	return (HAACDecoder)aacDecInfo;
}
示例#16
0
	void SetUpOpenCL() {
		//----------------------------------------------------------------------
		// Compile kernel
		//----------------------------------------------------------------------

		const std::string &kernelFileName = commandLineOpts["kernel"].as<std::string>();
		OCLTOY_LOG("Compile OpenCL kernel: " << kernelFileName);

		// Read the kernel
		const std::string kernelSource = ReadSources(kernelFileName, "jugCLer");

		// Create the kernel program
		cl::Device &oclDevice = selectedDevices[0];
		cl::Context &oclContext = deviceContexts[0];
		cl::Program program = cl::Program(oclContext, kernelSource);
		try {
			VECTOR_CLASS<cl::Device> buildDevice;
			buildDevice.push_back(oclDevice);
			program.build(buildDevice);
		} catch (cl::Error err) {
			cl::STRING_CLASS strError = program.getBuildInfo<CL_PROGRAM_BUILD_LOG>(oclDevice);
			OCLTOY_LOG("Kernel compilation error:\n" << strError.c_str());

			throw err;
		}

		kernelsJugCLer = cl::Kernel(program, "render_gpu");
		kernelsJugCLer.getWorkGroupInfo<size_t>(oclDevice, CL_KERNEL_WORK_GROUP_SIZE, &kernelsWorkGroupSize);
		if (commandLineOpts.count("workgroupsize"))
			kernelsWorkGroupSize = commandLineOpts["workgroupsize"].as<size_t>();
		OCLTOY_LOG("Using workgroup size: " << kernelsWorkGroupSize);

		//----------------------------------------------------------------------
		// Allocate buffer
		//----------------------------------------------------------------------

		AllocateBuffers();

		//----------------------------------------------------------------------
		// Set kernel arguments
		//----------------------------------------------------------------------

		kernelsJugCLer.setArg(0, *sceneBuff);
		kernelsJugCLer.setArg(1, *pixelsBuff);
	}
示例#17
0
int Message::ReadFromString(const char* ciphertext)
{
    int size = strlen(ciphertext) + 1;
    AllocateBuffers(size);

    for (int i = 0; i < strlen(ciphertext); ++i)
    {
        char c = ciphertext[i];
        if(!IS_ASCII(c) || c==' ') continue;
        cipher[i]=c;
    }

    cipher[size] = '\0';

    SetInfo(true);

    return size;
}
示例#18
0
bool CPixelConverter::Decode(const uint8_t* pData, unsigned int size)
{
  if (pData == nullptr || size == 0 || m_swsContext == nullptr)
    return false;

  if (!AllocateBuffers(m_pFrame))
    return false;

  uint8_t* dataMutable = const_cast<uint8_t*>(pData);

  const int stride = size / m_height;

  uint8_t* src[] =       { dataMutable,         0,                   0,                   0 };
  int      srcStride[] = { stride,              0,                   0,                   0 };
  uint8_t* dst[] =       { m_pFrame->data[0],     m_pFrame->data[1],     m_pFrame->data[2],     0 };
  int      dstStride[] = { m_pFrame->linesize[0], m_pFrame->linesize[1], m_pFrame->linesize[2], 0 };

  sws_scale(m_swsContext, src, srcStride, 0, m_height, dst, dstStride);

  return true;
}
示例#19
0
XnStatus XnBufferPool::ChangeBufferSize(XnUInt32 nBufferSize)
{
	XnStatus nRetVal = XN_STATUS_OK;

	xnDumpWriteString(m_dump, "changing buffer size to %d\n", nBufferSize);

	xnOSEnterCriticalSection(&m_hLock);

	m_nBufferSize = nBufferSize;

	nRetVal = AllocateBuffers();
	if (nRetVal != XN_STATUS_OK)
	{
		xnOSLeaveCriticalSection(&m_hLock);
		return (nRetVal);
	}

	xnOSLeaveCriticalSection(&m_hLock);
	
	return (XN_STATUS_OK);
}
示例#20
0
Result Par2Creator::Process(const CommandLine &commandline)
{
  // Get information from commandline
  noiselevel = commandline.GetNoiseLevel();
  blocksize = commandline.GetBlockSize();
  sourceblockcount = commandline.GetBlockCount();
  const list<CommandLine::ExtraFile> extrafiles = commandline.GetExtraFiles();
  sourcefilecount = (u32)extrafiles.size();
  u32 redundancy = commandline.GetRedundancy();
  recoveryblockcount = commandline.GetRecoveryBlockCount();
  recoveryfilecount = commandline.GetRecoveryFileCount();
  firstrecoveryblock = commandline.GetFirstRecoveryBlock();
  recoveryfilescheme = commandline.GetRecoveryFileScheme();
  string par2filename = commandline.GetParFilename();
  size_t memorylimit = commandline.GetMemoryLimit();
  largestfilesize = commandline.GetLargestSourceSize();

  // Compute block size from block count or vice versa depending on which was
  // specified on the command line
  if (!ComputeBlockSizeAndBlockCount(extrafiles))
    return eInvalidCommandLineArguments;

  // Determine how many recovery blocks to create based on the source block
  // count and the requested level of redundancy.
  if (redundancy > 0 && !ComputeRecoveryBlockCount(redundancy))
    return eInvalidCommandLineArguments;

  // Determine how much recovery data can be computed on one pass
  if (!CalculateProcessBlockSize(memorylimit))
    return eLogicError;

  // Determine how many recovery files to create.
  if (!ComputeRecoveryFileCount())
    return eInvalidCommandLineArguments;

  if (noiselevel > CommandLine::nlQuiet)
  {
    // Display information.
    cout << "Block size: " << blocksize << endl;
    cout << "Source file count: " << sourcefilecount << endl;
    cout << "Source block count: " << sourceblockcount << endl;
    if (redundancy>0 || recoveryblockcount==0)
      cout << "Redundancy: " << redundancy << '%' << endl;
    cout << "Recovery block count: " << recoveryblockcount << endl;
    cout << "Recovery file count: " << recoveryfilecount << endl;
    cout << endl;
  }

  // Open all of the source files, compute the Hashes and CRC values, and store
  // the results in the file verification and file description packets.
  if (!OpenSourceFiles(extrafiles))
    return eFileIOError;

  // Create the main packet and determine the setid to use with all packets
  if (!CreateMainPacket())
    return eLogicError;

  // Create the creator packet.
  if (!CreateCreatorPacket())
    return eLogicError;

  // Initialise all of the source blocks ready to start reading data from the source files.
  if (!CreateSourceBlocks())
    return eLogicError;

  // Create all of the output files and allocate all packets to appropriate file offets.
  if (!InitialiseOutputFiles(par2filename))
    return eFileIOError;

  if (recoveryblockcount > 0)
  {
    // Allocate memory buffers for reading and writing data to disk.
    if (!AllocateBuffers())
      return eMemoryError;

    // Compute the Reed Solomon matrix
    if (!ComputeRSMatrix())
      return eLogicError;

    // Set the total amount of data to be processed.
    progress = 0;
    totaldata = blocksize * sourceblockcount * recoveryblockcount;
	previouslyReportedFraction = -10000000;	// Big negative

    // Start at an offset of 0 within a block.
    u64 blockoffset = 0;
    while (blockoffset < blocksize) // Continue until the end of the block.
    {
      // Work out how much data to process this time.
      size_t blocklength = (size_t)min((u64)chunksize, blocksize-blockoffset);

      // Read source data, process it through the RS matrix and write it to disk.
      if (!ProcessData(blockoffset, blocklength))
        return eFileIOError;

      blockoffset += blocklength;
    }

    if (noiselevel > CommandLine::nlQuiet)
      cout << "Writing recovery packets" << endl;

    // Finish computation of the recovery packets and write the headers to disk.
    if (!WriteRecoveryPacketHeaders())
      return eFileIOError;

    // Finish computing the full file hash values of the source files
    if (!FinishFileHashComputation())
      return eLogicError;
  }

  // Fill in all remaining details in the critical packets.
  if (!FinishCriticalPackets())
    return eLogicError;

  if (noiselevel > CommandLine::nlQuiet)
    cout << "Writing verification packets" << endl;

  // Write all other critical packets to disk.
  if (!WriteCriticalPackets())
    return eFileIOError;

  // Close all files.
  if (!CloseFiles())
    return eFileIOError;

  if (noiselevel > CommandLine::nlSilent)
    cout << "Done" << endl;

  return eSuccess;
}
示例#21
0
// _______________________________________________________________________________________
//
void	CAAudioFile::Read(UInt32 &ioNumPackets, AudioBufferList *ioData)
			// May read fewer packets than requested if:
			//		buffer is not big enough
			//		file does not contain that many more packets
			// Note that eofErr is not fatal, just results in 0 packets returned
			// ioData's buffer sizes may be shortened
{
	XThrowIf(mClientMaxPacketSize == 0, kExtAudioFileError_MaxPacketSizeUnknown, "client maximum packet size is 0");
	if (mIOBufferList.mBuffers[0].mData == NULL) {
#if DEBUG
		printf("warning: CAAudioFile::AllocateBuffers called from ReadPackets\n");
#endif
		AllocateBuffers();
	}
	UInt32 bufferSizeBytes = ioData->mBuffers[0].mDataByteSize;
	UInt32 maxNumPackets = bufferSizeBytes / mClientMaxPacketSize;
	// older versions of AudioConverterFillComplexBuffer don't do this, so do our own sanity check
	UInt32 nPackets = std::min(ioNumPackets, maxNumPackets);

	mMaxPacketsToRead = ~0UL;

	if (mClientDataFormat.mFramesPerPacket == 1) {  // PCM or equivalent
		while (mFramesToSkipFollowingSeek > 0) {
			UInt32 skipFrames = std::min(mFramesToSkipFollowingSeek, maxNumPackets);
			UInt32 framesPerPacket;
			if ((framesPerPacket=mFileDataFormat.mFramesPerPacket) > 0)
				mMaxPacketsToRead = (skipFrames + framesPerPacket - 1) / framesPerPacket;

			if (mConverter == NULL) {
				XThrowIfError(ReadInputProc(NULL, &skipFrames, ioData, NULL, this), "read audio file");
			} else {
#if CAAUDIOFILE_PROFILE
				mInConverter = true;
#endif
				StartTiming(this, fill);
				XThrowIfError(AudioConverterFillComplexBuffer(mConverter, ReadInputProc, this, &skipFrames, ioData, NULL), "convert audio packets (pcm read)");
				ElapsedTime(this, fill, mTicksInConverter);
#if CAAUDIOFILE_PROFILE
				mInConverter = false;
#endif
			}
			if (skipFrames == 0) {	// hit EOF
				ioNumPackets = 0;
				return;
			}
			mFrameMark += skipFrames;
#if VERBOSE_IO
			printf("CAAudioFile::ReadPackets: skipped %ld frames\n", skipFrames);
#endif

			mFramesToSkipFollowingSeek -= skipFrames;

			// restore mDataByteSize
			for (int i = ioData->mNumberBuffers; --i >= 0 ; )
				ioData->mBuffers[i].mDataByteSize = bufferSizeBytes;
		}
	}

	if (mFileDataFormat.mFramesPerPacket > 0)
		// don't read more packets than we are being asked to produce
		mMaxPacketsToRead = nPackets / mFileDataFormat.mFramesPerPacket + 1;
	if (mConverter == NULL) {
		XThrowIfError(ReadInputProc(NULL, &nPackets, ioData, NULL, this), "read audio file");
	} else {
#if CAAUDIOFILE_PROFILE
		mInConverter = true;
#endif
		StartTiming(this, fill);
		XThrowIfError(AudioConverterFillComplexBuffer(mConverter, ReadInputProc, this, &nPackets, ioData, NULL), "convert audio packets (read)");
		ElapsedTime(this, fill, mTicksInConverter);
#if CAAUDIOFILE_PROFILE
		mInConverter = false;
#endif
	}
	if (mClientDataFormat.mFramesPerPacket == 1)
		mFrameMark += nPackets;

	ioNumPackets = nPackets;
}
示例#22
0
// _______________________________________________________________________________________
//
// called to create the file -- or update its format/channel layout/properties based on an encoder
// setting change
void	CAAudioFile::FileFormatChanged(const FSRef *parentDir, CFStringRef filename, AudioFileTypeID filetype)
{
	LOG_FUNCTION("CAAudioFile::FileFormatChanged", "%p", this);
	XThrowIf(mMode != kPreparingToCreate && mMode != kPreparingToWrite, kExtAudioFileError_InvalidOperationOrder, "new file not prepared");

	UInt32 propertySize;
	OSStatus err;
	AudioStreamBasicDescription saveFileDataFormat = mFileDataFormat;

#if VERBOSE_CONVERTER
	mFileDataFormat.PrintFormat(stdout, "", "Specified file data format");
#endif

	// Find out the actual format the converter will produce. This is necessary in
	// case the bitrate has forced a lower sample rate, which needs to be set correctly
	// in the stream description passed to AudioFileCreate.
	if (mConverter != NULL) {
		propertySize = sizeof(AudioStreamBasicDescription);
		Float64 origSampleRate = mFileDataFormat.mSampleRate;
		XThrowIfError(AudioConverterGetProperty(mConverter, kAudioConverterCurrentOutputStreamDescription, &propertySize, &mFileDataFormat), "get audio converter's output stream description");
		// do the same for the channel layout being output by the converter
#if VERBOSE_CONVERTER
		mFileDataFormat.PrintFormat(stdout, "", "Converter output");
#endif
		if (fiszero(mFileDataFormat.mSampleRate))
			mFileDataFormat.mSampleRate = origSampleRate;
		err = AudioConverterGetPropertyInfo(mConverter, kAudioConverterOutputChannelLayout, &propertySize, NULL);
		if (err == noErr && propertySize > 0) {
			AudioChannelLayout *layout = static_cast<AudioChannelLayout *>(malloc(propertySize));
			err = AudioConverterGetProperty(mConverter, kAudioConverterOutputChannelLayout, &propertySize, layout);
			if (err) {
				free(layout);
				XThrow(err, "couldn't get audio converter's output channel layout");
			}
			mFileChannelLayout = layout;
#if VERBOSE_CHANNELMAP
			printf("got new file's channel layout from converter: %s\n", CAChannelLayouts::ConstantToString(mFileChannelLayout.Tag()));
#endif
			free(layout);
		}
	}

	// create the output file
	if (mMode == kPreparingToCreate) {
		CAStreamBasicDescription newFileDataFormat = mFileDataFormat;
		if (fiszero(newFileDataFormat.mSampleRate))
			newFileDataFormat.mSampleRate = 44100;	// just make something up for now
#if VERBOSE_CONVERTER
		newFileDataFormat.PrintFormat(stdout, "", "Applied to new file");
#endif
		XThrowIfError(AudioFileCreate(parentDir, filename, filetype, &newFileDataFormat, 0, &mFSRef, &mAudioFile), "create audio file");
		mMode = kPreparingToWrite;
		mOwnOpenFile = true;
	} else if (saveFileDataFormat != mFileDataFormat || fnotequal(saveFileDataFormat.mSampleRate, mFileDataFormat.mSampleRate)) {
		// second check must be explicit since operator== on ASBD treats SR of zero as "don't care"
		if (fiszero(mFileDataFormat.mSampleRate))
			mFileDataFormat.mSampleRate = mClientDataFormat.mSampleRate;
#if VERBOSE_CONVERTER
		mFileDataFormat.PrintFormat(stdout, "", "Applied to new file");
#endif
		XThrowIf(fiszero(mFileDataFormat.mSampleRate), kExtAudioFileError_InvalidDataFormat, "file's sample rate is 0");
		XThrowIfError(AudioFileSetProperty(mAudioFile, kAudioFilePropertyDataFormat, sizeof(AudioStreamBasicDescription), &mFileDataFormat), "couldn't update file's data format");
	}

	UInt32 deferSizeUpdates = 1;
	err = AudioFileSetProperty(mAudioFile, kAudioFilePropertyDeferSizeUpdates, sizeof(UInt32), &deferSizeUpdates);

	if (mConverter != NULL) {
		// encoder
		// get the magic cookie, if any, from the converter
		delete[] mMagicCookie;	mMagicCookie = NULL;
		mMagicCookieSize = 0;

		err = AudioConverterGetPropertyInfo(mConverter, kAudioConverterCompressionMagicCookie, &propertySize, NULL);

		// we can get a noErr result and also a propertySize == 0
		// -- if the file format does support magic cookies, but this file doesn't have one.
		if (err == noErr && propertySize > 0) {
			mMagicCookie = new Byte[propertySize];
			XThrowIfError(AudioConverterGetProperty(mConverter, kAudioConverterCompressionMagicCookie, &propertySize, mMagicCookie), "get audio converter's magic cookie");
			mMagicCookieSize = propertySize;	// the converter lies and tell us the wrong size
			// now set the magic cookie on the output file
			UInt32 willEatTheCookie = false;
			// the converter wants to give us one; will the file take it?
			err = AudioFileGetPropertyInfo(mAudioFile, kAudioFilePropertyMagicCookieData,
					NULL, &willEatTheCookie);
			if (err == noErr && willEatTheCookie) {
#if VERBOSE_CONVERTER
				printf("Setting cookie on encoded file\n");
#endif
				XThrowIfError(AudioFileSetProperty(mAudioFile, kAudioFilePropertyMagicCookieData, mMagicCookieSize, mMagicCookie), "set audio file's magic cookie");
			}
		}

		// get maximum packet size
		propertySize = sizeof(UInt32);
		XThrowIfError(AudioConverterGetProperty(mConverter, kAudioConverterPropertyMaximumOutputPacketSize, &propertySize, &mFileMaxPacketSize), "get audio converter's maximum output packet size");

		AllocateBuffers(true /* okToFail */);
	} else {
		InitFileMaxPacketSize();
	}

	if (mFileChannelLayout.IsValid() && mFileChannelLayout.NumberChannels() > 2) {
		// don't bother tagging mono/stereo files
		UInt32 isWritable;
		err = AudioFileGetPropertyInfo(mAudioFile, kAudioFilePropertyChannelLayout, NULL, &isWritable);
		if (!err && isWritable) {
#if VERBOSE_CHANNELMAP
			printf("writing file's channel layout: %s\n", CAChannelLayouts::ConstantToString(mFileChannelLayout.Tag()));
#endif
			err = AudioFileSetProperty(mAudioFile, kAudioFilePropertyChannelLayout,
				mFileChannelLayout.Size(), &mFileChannelLayout.Layout());
			if (err)
				CAXException::Warning("could not set the file's channel layout", err);
		} else {
#if VERBOSE_CHANNELMAP
			printf("file won't accept a channel layout (write)\n");
#endif
		}
	}

	UpdateClientMaxPacketSize();	// also sets mFrame0Offset
	mPacketMark = 0;
	mFrameMark = 0;
}
示例#23
0
void
ToneProducer::Connect(status_t error, const media_source& source, const media_destination& destination, const media_format& format, char* io_name)
{
	FPRINTF(stderr, "ToneProducer::Connect\n");

	// If something earlier failed, Connect() might still be called, but with a non-zero
	// error code.  When that happens we simply unreserve the connection and do
	// nothing else.
	if (error)
	{
		mOutput.destination = media_destination::null;
		mOutput.format = mPreferredFormat;
		return;
	}

// old workaround for format bug: Connect() receives the format data from the
// input returned from BBufferConsumer::Connected().
//
//	char formatStr[256];
//	string_for_format(format, formatStr, 255);
//	FPRINTF(stderr, "\trequested format: %s\n", formatStr);
//	if(format.type != B_MEDIA_RAW_AUDIO) {
//		// +++++ this is NOT proper behavior
//		//       but it works
//		FPRINTF(stderr, "\tcorrupted format; falling back to last suggested format\n");
//		format = mOutput.format;
//	}
//

	// Okay, the connection has been confirmed.  Record the destination and format
	// that we agreed on, and report our connection name again.
	mOutput.destination = destination;
	mOutput.format = format;
	strncpy(io_name, mOutput.name, B_MEDIA_NAME_LENGTH);

	// Now that we're connected, we can determine our downstream latency.
	// Do so, then make sure we get our events early enough.
	media_node_id id;
	FindLatencyFor(mOutput.destination, &mLatency, &id);
	FPRINTF(stderr, "\tdownstream latency = %" B_PRIdBIGTIME "\n", mLatency);

	// Use a dry run to see how long it takes me to fill a buffer of data
	bigtime_t start, produceLatency;
	size_t samplesPerBuffer = mOutput.format.u.raw_audio.buffer_size / sizeof(float);
	size_t framesPerBuffer = samplesPerBuffer / mOutput.format.u.raw_audio.channel_count;
	float* data = new float[samplesPerBuffer];
	mTheta = 0;
	start = ::system_time();
	FillSineBuffer(data, framesPerBuffer, mOutput.format.u.raw_audio.channel_count==2);
	produceLatency = ::system_time();
	mInternalLatency = produceLatency - start;

	// +++++ e.moon [13jun99]: fiddling with latency, ick
	mInternalLatency += 20000LL;

	delete [] data;
	FPRINTF(stderr, "\tbuffer-filling took %" B_PRIdBIGTIME
			" usec on this machine\n", mInternalLatency);
	SetEventLatency(mLatency + mInternalLatency);

	// reset our buffer duration, etc. to avoid later calculations
	// +++++ e.moon 11jun99: crashes w/ divide-by-zero when connecting to LoggingConsumer
	ASSERT(mOutput.format.u.raw_audio.frame_rate);

	bigtime_t duration = bigtime_t(1000000) * samplesPerBuffer / bigtime_t(mOutput.format.u.raw_audio.frame_rate);
	SetBufferDuration(duration);

	// Set up the buffer group for our connection, as long as nobody handed us a
	// buffer group (via SetBufferGroup()) prior to this.  That can happen, for example,
	// if the consumer calls SetOutputBuffersFor() on us from within its Connected()
	// method.
	if (!mBufferGroup) AllocateBuffers();
}
Result Par1Repairer::Process(const CommandLine &commandline, bool dorepair) {
	// How noisy should we be
	noiselevel = commandline.GetNoiseLevel();

	// Do we want to purge par files on success ?
	bool purgefiles = commandline.GetPurgeFiles();

	// Get filesnames from the command line
	string par1filename = commandline.GetParFilename();
	const list<CommandLine::ExtraFile> &extrafiles = commandline.GetExtraFiles();

	// Determine the searchpath from the location of the main PAR file
	string name;
	DiskFile::SplitFilename(par1filename, searchpath, name);

	// Load the main PAR file
	if (!LoadRecoveryFile(searchpath + name))
		return eLogicError;

	// Load other PAR files related to the main PAR file
	if (!LoadOtherRecoveryFiles(par1filename))
		return eLogicError;

	// Load any extra PAR files specified on the command line
	if (!LoadExtraRecoveryFiles(extrafiles))
		return eLogicError;

	if (noiselevel > CommandLine::nlQuiet)
		cout << endl << "Verifying source files:" << endl << endl;

	// Check for the existence of and verify each of the source files
	if (!VerifySourceFiles())
		return eFileIOError;

	if (completefilecount<sourcefiles.size()) {
		if (noiselevel > CommandLine::nlQuiet)
			cout << endl << "Scanning extra files:" << endl << endl;

		// Check any other files specified on the command line to see if they are
		// actually copies of the source files that have the wrong filename
		if (!VerifyExtraFiles(extrafiles))
			return eLogicError;
	}

	// Find out how much data we have found
	UpdateVerificationResults();

	if (noiselevel > CommandLine::nlSilent)
		cout << endl;

	// Check the verification results and report the details
	if (!CheckVerificationResults())
		return eRepairNotPossible;

	// Are any of the files incomplete
	if (completefilecount<sourcefiles.size()) {
		// Do we want to carry out a repair
		if (dorepair) {
			if (noiselevel > CommandLine::nlSilent)
				cout << endl;

			// Rename any damaged or missnamed target files.
			if (!RenameTargetFiles())
				return eFileIOError;

			// Are we still missing any files
			if (completefilecount<sourcefiles.size()) {
				// Work out which files are being repaired, create them, and allocate
				// target DataBlocks to them, and remember them for later verification.
				if (!CreateTargetFiles())
					return eFileIOError;

				// Work out which data blocks are available, which need to be recreated,
				// and compute the appropriate Reed Solomon matrix.
				if (!ComputeRSmatrix()) {
					// Delete all of the partly reconstructed files
					DeleteIncompleteTargetFiles();
					return eFileIOError;
				}

				// Allocate memory buffers for reading and writing data to disk.
				if (!AllocateBuffers(commandline.GetMemoryLimit())) {
					// Delete all of the partly reconstructed files
					DeleteIncompleteTargetFiles();
					return eMemoryError;
				}
				if (noiselevel > CommandLine::nlSilent)
					cout << endl;

				// Set the total amount of data to be processed.
				progress = 0;
				totaldata = blocksize * sourcefiles.size() * verifylist.size();

				// Start at an offset of 0 within a block.
				u64 blockoffset = 0;
				while (blockoffset < blocksize) { // Continue until the end of the block.
					// Work out how much data to process this time.
					size_t blocklength = (size_t)min((u64)chunksize, blocksize-blockoffset);

					// Read source data, process it through the RS matrix and write it to disk.
					if (!ProcessData(blockoffset, blocklength)) {
						// Delete all of the partly reconstructed files
						DeleteIncompleteTargetFiles();
						return eFileIOError;
					}

					// Advance to the need offset within each block
					blockoffset += blocklength;
				}

				if (noiselevel > CommandLine::nlSilent)
					cout << endl << "Verifying repaired files:" << endl << endl;

				// Verify that all of the reconstructed target files are now correct
				if (!VerifyTargetFiles()) {
					// Delete all of the partly reconstructed files
					DeleteIncompleteTargetFiles();
					return eFileIOError;
				}
			}

			// Are all of the target files now complete?
			if (completefilecount<sourcefiles.size()) {
				cerr << "Repair Failed." << endl;
				return eRepairFailed;
			} else {
				if (noiselevel > CommandLine::nlSilent)
					cout << endl << "Repair complete." << endl;
			}
		} else {
			return eRepairPossible;
		}
	}

	if (purgefiles == true) {
		RemoveBackupFiles();
		RemoveParFiles();
	}

	return eSuccess;
}
示例#25
0
bool CUrlParts::SplitUrl(BSTR bUrl)
{
	if(bUrl == NULL)
		return false;

	DWORD ilen = ::SysStringLen(bUrl);
	if(ilen == 0)
		return false;
	//Allocate buffers
	if(AllocateBuffers(ilen) == false)
		return false;

	URL_COMPONENTS URLComponentsOut;
	ZeroMemory((LPVOID)&URLComponentsOut, sizeof(URLComponentsOut));
	URLComponentsOut.dwStructSize = sizeof(URLComponentsOut);

	URLComponentsOut.lpszScheme = szScheme;         // pointer to scheme name
	URLComponentsOut.dwSchemeLength = ilen;     // length of scheme name
	
	URLComponentsOut.lpszHostName = szHostName;       // pointer to host name
	URLComponentsOut.dwHostNameLength = ilen;   // length of host name
	
	URLComponentsOut.lpszUserName = szUserName;       // pointer to user name
	URLComponentsOut.dwUserNameLength = ilen;   // length of user name
	
	URLComponentsOut.lpszPassword = szPassword;       // pointer to password
	URLComponentsOut.dwPasswordLength = ilen;   // length of password
	
	URLComponentsOut.lpszUrlPath = szUrlPath;        // pointer to URL-path
	URLComponentsOut.dwUrlPathLength = ilen;    // length of URL-path
    
	URLComponentsOut.lpszExtraInfo = szExtraInfo;      // pointer to extra information (e.g. ?foo or #foo)
    URLComponentsOut.dwExtraInfoLength = ilen;  // length of extra information
//Flags
	DWORD dwFlags = ICU_DECODE;

//0 default
	//Return as is
//1 ICU_DECODE Converts encoded characters back to their normal form.
	//This can be used only if the user provides buffers in the URL_COMPONENTS structure to copy the components into. 
//8 ICU_ESCAPE Converts all escape sequences (%xx) to their corresponding characters.
	//This can be used only if the user provides buffers in the URL_COMPONENTS structure to copy the components into. 

	//If the pointer contains the address of the user-supplied buffer,
	//the length member must contain the size of the buffer.
	//InternetCrackUrl copies the component into the buffer, and
	//the length member is set to the length of the copied component, minus 1
	//for the trailing string terminator.
	USES_CONVERSION;
	if(!InternetCrackUrl(OLE2T(bUrl), 0, dwFlags, &URLComponentsOut))
		return false;

	dwScheme = URLComponentsOut.dwSchemeLength;
	dwHostName = URLComponentsOut.dwHostNameLength;
	dwUserName = URLComponentsOut.dwUserNameLength;
	dwPassword = URLComponentsOut.dwPasswordLength;
	dwUrlPath = URLComponentsOut.dwUrlPathLength;
	dwExtraInfo = URLComponentsOut.dwExtraInfoLength;
	
	lnScheme = URLComponentsOut.nScheme;

	if(dwUrlPath > 0)
	{
		//Look for filename here
		TCHAR *lpStr1 = szUrlPath;
		lpStr1 += _tcslen(lpStr1);
    	if (*lpStr1 == _T('/'))
    		--lpStr1;
    	while (*lpStr1 != _T('/'))
		{
			//Look for extension at the same time
			
			//if not using ICU_DECODE flag in InternetCrackUrl function,
			//Watch out for decoded charcters,"%2E" -> "."

			//(dwFileExtension == (DWORD)0),
			//To avoid abc.somesite.com.mpg style of file naming
			
			if( (*lpStr1 == _T('.')) && (dwFileExtension == (DWORD)0) )
			{
				dwFileExtension = _tcslen(lpStr1);
				if(dwFileExtension > 0)
				{
					memcpy(szFileExtension, lpStr1, dwFileExtension * sizeof(TCHAR) );
					szFileExtension[dwFileExtension] = _T('\0');
				}
			}
    		--lpStr1;
		}
		lpStr1++;
		dwFileName = _tcslen(lpStr1);
		if(dwFileName > 0)
		{
			memcpy(szFileName, lpStr1, dwFileName * sizeof(TCHAR));
			szFileName[dwFileName] = _T('\0');
		}
	}
	dwPort = URLComponentsOut.nPort;
	return true;
}