示例#1
0
LONG CPlayerView::OnWinAmpPlugWmUserMessage( WPARAM wParam, LPARAM lParam )
{
	int nReturn = 0;

	ENTRY_TRACE( _T( "CPlayerView::OnWinAmpPlugWmUserMessage( %d, %d)" ), wParam, lParam );

	switch ( lParam )
	{
		case 104:
			// Return Playing Status 
			if ( PAUSING == m_nStatus  )
			{
				nReturn = 3;
			} else
			if ( PLAYING == m_nStatus  )
			{
				nReturn = 1;
			}
		break;

		case 105:
			// return playing position in ms
			return m_nCurrentTime;
		break;

		case 106:
			// resume playing at pos wParam
			nReturn = 1;
		break;
	}

	EXIT_TRACE( _T( "CPlayerView::OnWinAmpPlugWmUserMessage, return %d" ), nReturn );

	return nReturn;
}
示例#2
0
void CPlayerView::OnPause() 
{
	ENTRY_TRACE( _T( "CPlayerView::OnPause()" ) );

	if ( PLAYING == m_nStatus )
	{
		m_nStatus = PAUSING;

		if ( m_pPlayStream )
		{
			m_dwSeekOffset+= m_pPlayStream->GetCurrentTime();

			m_pPlayStream->Pause();
		}

		m_ePaused.ResetEvent();
	}
	else
	{

		if ( m_pPlayStream )
		{
			m_pPlayStream->Resume();
		}

		m_nStatus = PLAYING;

		m_ePaused.SetEvent();

	}
	UpdateData( FALSE );

	EXIT_TRACE( _T( "CPlayerView::OnPause()" ) );

}
示例#3
0
int openInputFile(config* conf){
    struct stat filestat;
    if (stat(conf->infile, &filestat) < 0) {
        EXIT_TRACE("input file not found: %s\n", conf->infile);
    }

    if (!(filestat.st_mode & S_IFREG)) {
        EXIT_TRACE("not a normal file: %s\n", conf->infile);
    }

    int fd = OPEN(conf->infile, O_RDONLY | O_LARGEFILE, S_IREAD);
    /* src file open */
    if( fd < 0) {
        EXIT_TRACE("%s file open error %s\n", conf->infile, strerror(errno));
    }
    return fd;
}
示例#4
0
void CCDPlayDigital::Pause( BOOL bPause )
{
	ENTRY_TRACE( _T( "CCDPlayDigital::Pause( %d )" ), bPause );

	m_bPause = bPause;

	EXIT_TRACE( _T( "CCDPlayDigital::Pause()" ) );
}
示例#5
0
/*
 * Decompress the data
 */
void * 
Decompress(void * args) {
  u_char tmpstr[UNCOMPRESS_BOUND];
  while (1) {
    send_buf_item * item;
    //get one item
    if (tail_decompress == head_decompress && end_RecvBlock) {
      break;     
    }
    
    item = buf_decompress[tail_decompress];
    tail_decompress ++;
    if (tail_decompress == NUM_BUF_DECOMPRESS) tail_decompress = 0;
        
    send_body * body = (send_body*)item->str;

    u_char * pstr = NULL;
    u_long len = 0;
    int t = 0;
    unsigned long len_32;

    //uncompress the item
    switch (compress_way) {
    case COMPRESS_GZIP:
      len_32 = UNCOMPRESS_BOUND;
      t = uncompress(tmpstr, &len_32, item->content, body->len);

      len = len_32;
      pstr= (u_char *)malloc(len);
      body->len = len;
      memcpy(pstr, tmpstr, len);
      MEM_FREE(item->content);
      item->content = pstr;
      break;
    case COMPRESS_BZIP2:
      break;
    case COMPRESS_NONE:
      break;
    }
    u_char * key = (u_char * )malloc(SHA1_LEN);
    Calc_SHA1Sig(item->content, body->len, key);
    
    data_chunk * value = (data_chunk *)malloc(sizeof(data_chunk));
    value->start = item->content;
    value->len = body->len;

    if (hashtable_insert(cache, key, value) == 0) {
      EXIT_TRACE("hashtable_insert failed");
    }  
    //put it into the reassemble queue
    buf_reassemble[head_reassemble] = item;
    head_reassemble ++;
    if (head_reassemble == NUM_BUF_REASSEMBLE) head_reassemble = 0;
  }

  end_Decompress += 1;
  return NULL;
}
示例#6
0
void CPlayerView::OnNext() 
{
	ENTRY_TRACE( _T( "CPlayerView::OnNext()" ) );

	m_ThreadCommand = THREAD_PLAY_NEXT_TRACK;
	m_bAbortCurrent = TRUE;

	EXIT_TRACE( _T( "CPlayerView::OnNext()" ) );
}
示例#7
0
文件: TagData.cpp 项目: elha/CDex
// CONSRUCTOR
CTagData::CTagData()
{
	ENTRY_TRACE( _T( "CTagData::CTagData()" ) );

    // Initialize the variables
	Init();

	EXIT_TRACE( _T( "CTagData::CTagData()" ) );
}
示例#8
0
void CPlayerView::OnDetails() 
{
	ENTRY_TRACE( _T( "CPlayerView::OnDetails()" ) );

	if ( m_pInStream )
	{
		m_pInStream->InfoBox( GetSafeHwnd() );
	}

	EXIT_TRACE( _T( "CPlayerView::OnDetails()" ) );
}
示例#9
0
void CCDPlayDigital::Stop( )
{
	ENTRY_TRACE( _T( "CCDPlayDigital::Stop()" ) );

	m_bPause = FALSE;
	m_bAbort = TRUE;

	// wait till thread has been finished
	while ( NULL != (volatile void*)m_pThread )
	{
		::Sleep( 10 );
	}

	EXIT_TRACE( _T( "CCDPlayDigital::Stop()" ) );
}
示例#10
0
CCDPlayDigital::CCDPlayDigital():
			CObject()
{
	ENTRY_TRACE( _T( "CCDPlayDigital::CCDPlayDigital" ) );

	m_pThread = NULL;
	m_bAbort = FALSE;
	m_dwBeginSector = 0;
	m_dwEndSector = 0;
	m_dwCurrentSector = 0;
	m_bIsPlaying = TRUE;
	m_dwTotalBytes = 0;
	m_dwBytesWritten = 0;
	m_dwCurrentTime = 0;
	m_dwSeekTimeOffset = 0;
	m_bPause = FALSE;

	EXIT_TRACE( _T( "CCDPlayDigital::CCDPlayDigital" ) );

}
示例#11
0
void CCDPlayDigital::Play( DWORD dwBeginSector, DWORD dwEndSector )
{
	ENTRY_TRACE( _T( "CCDPlayDigital::Play( %d, %d )" ), dwBeginSector, dwEndSector );

	m_bIsPlaying = TRUE;

	ASSERT( dwBeginSector <= dwEndSector );

	SetBeginSector( dwBeginSector );
	SetEndSector( dwEndSector );

	m_dwTotalBytes = (dwEndSector - dwBeginSector ) * CB_CDDASECTORSIZE;
	m_dwBytesWritten = 0;

	// Fire thread
	m_pThread = AfxBeginThread( RipAndPlay, (void*)this, g_config.GetThreadPriority() );

	EXIT_TRACE( _T( "CCDPlay::Play( )" ) );

}
示例#12
0
void CPlayerView::OnStop() 
{
	ENTRY_TRACE( _T( "CPlayerView::OnStop()" ) );

	// stop immediately the output WAV playing
	if ( m_pPlayStream )
	{
		m_pPlayStream->Pause();
		m_pPlayStream->Stop();
	}

	// Now make sure that the thread gets aborted properly
	m_bAbortThread = TRUE;

	// Set status to abort
	m_nStatus = ABORT;

	// Make sure that pause event has been set
	m_ePaused.SetEvent();

	// Wait for thread to finish
	if ( WAIT_OBJECT_0 != WaitForSingleObject( m_eThreadFinished, 13000 ) )
	{
		if ( m_pThread )
		{
			m_pThread->ResumeThread();
			TerminateThread( m_pThread->m_hThread, -2 );
		}
	}

	m_pThread = NULL;

	m_nStatus = IDLE;

	SetControls();

	m_Position.SetPos( 0 );

	EXIT_TRACE( _T( "CPlayerView::OnStop()" ) );

}
示例#13
0
void CMP3ToWavDlg::OnCancel() 
{
	ENTRY_TRACE( _T( "CMP3ToWavDlg::OnCancel" ) );

	// Beep if we have finished
	MessageBeep( MB_OK );
	MessageBeep( 0xFFFFFFFF );

	// Set abort flag, so don't process any more files
	m_bAbortThread = TRUE;

	// Stop the timer
	KillTimer( TIMERID );

	// Wait for thread to finish
	WaitForSingleObject( m_eThreadFinished, INFINITE );


	// Destroy myself
	DestroyWindow();

	EXIT_TRACE( _T( "CMP3ToWavDlg::OnCancel" ) );
}
示例#14
0
CDEX_ERR CEncoderFaacDll::InitEncoder( CTaskInfo* pTask )
{
	CDEX_ERR bReturn = CDEX_OK;

	CUString	strLang;

	ENTRY_TRACE( _T( "CEncoderFaacDll::InitEncoder" ) );

	CEncoder::InitEncoder( pTask );

	if ( !LoadDLL(	m_strEncoderPath,
					_W( "\\encoders\\libraries\\libfaac\\Dll" ),
					m_hDLL,
					FALSE,
					FALSE ) )
	{
		bReturn = CDEX_ERROR;
	}

	EXIT_TRACE( _T( "CEncoderFaacDll::InitEncoder, return value %d" ), bReturn );

	return bReturn;
}
示例#15
0
文件: Aspi.cpp 项目: joshlong/libcd
CDEX_ERR DeInitAspiDll( )
{
	CDEX_ERR bReturn = CDEX_OK;

	ENTRY_TRACE( _T( "DeInitAspiDLL()" ) );

	// release the ASPI library
	if ( hAspiLib )
	{
		FreeLibrary( hAspiLib );
		hAspiLib = NULL;
	}

	// DeInit NT SCSI library
	(void)NtScsiDeInit();



	EXIT_TRACE( _T( "DeInitAspiDLL(), return value: %d" ), bReturn );

	return bReturn;

}
示例#16
0
文件: TagData.cpp 项目: elha/CDex
// Init CTagData variables
void CTagData::Init()
{
	ENTRY_TRACE( _T( "CTagData::Init()" ) );

	// Initialize all strings and variables
    m_strTitle		= _T( "" );
    m_strArtist		= _T( "" );
    m_strAlbum		= _T( "" );
    m_strYear		= _T( "" );
    m_strComment	= _T( "" );
	m_strEncodedBy  = _T( "" );
    m_strGenre		= _T( "" );
	m_strLengthInMs = _T( "" );
	m_dwCDBID		= 0;
	m_dwVOLID		= 0;
	m_dwCDBID       = 0;
	m_dwVOLID       = 0;
	m_dwTotalTracks = 0;
    m_lTrackOffset  = 0;
	memset( m_btaRawToc, 0, sizeof( m_btaRawToc ) );

    EXIT_TRACE( _T( "CTagData::Init()" ) );
}
示例#17
0
UINT CMP3ToWavDlg::ConvertFunc(PVOID pParams)
{
	CUString		strLang;
	int			nPeakValue	= 0;
	DWORD		dwIndex		= 0;
	CDEX_ERR	bErr		= CDEX_OK;
	PBYTE		pStream		= NULL;
 	DWORD       dwTotalTime = 0;

	ENTRY_TRACE( _T( "ConvertFunc" ) );

	CMP3ToWavDlg* pDlg = (CMP3ToWavDlg*)pParams;

	pDlg->m_wCurrentTrack = 0;
	pDlg->m_bAbortThread = FALSE;


	CUString strOutDir(g_config.GetCnvOutputDir());

	while(	pDlg->m_wCurrentTrack < pDlg->m_nTotalFiles && 
			!pDlg->m_bAbortThread )
	{
		BOOL bNoToAll = FALSE;

		nPeakValue	= 0;

		POSITION nFileListPos = pDlg->m_Pos;

		pDlg->m_strMP3FileName = pDlg->m_pFileDlg->GetNextPathName( pDlg->m_Pos );
		pDlg->m_strWavFileName = pDlg->m_pFileDlg->GetFileName( nFileListPos );

		CUString strSubPath = pDlg->m_pFileDlg->GetSubPath( nFileListPos );

		int nPos = pDlg->m_strWavFileName.ReverseFind('.');

		if (nPos > 0 )
		{
			pDlg->m_strWavFileName= pDlg->m_strWavFileName.Left( nPos );
		}

		strOutDir = g_config.GetCnvOutputDir() + strSubPath;

		// Prepend output directory
		pDlg->m_strWavFileName= strOutDir + CUString( pDlg->m_strWavFileName );

		// Create Ouput directory
		if ( CDEX_OK != DoesDirExist( strOutDir, FALSE )  )
		{
			LTRACE( _T( "ConvertFunc::Error creating output dir %s" ), strOutDir );

			strLang = g_language.GetString( IDS_CANNOT_CREATE_OUTDIR );
			CDexMessageBox( strLang + strOutDir );
			bErr = CDEX_ERROR;
		}

		// Clear error flag
		bErr = CDEX_OK;

		LTRACE( _T( "Converting track %d" ), pDlg->m_wCurrentTrack );

		// Reset estimate timer
		//pDlg->m_TimeTrack.ReInit();

		pDlg->m_nPercentCompleted=0;

		// create proper input stream
		pDlg->m_pInStream = ICreateStream( CUString( pDlg->m_strMP3FileName ) );

		if ( FALSE == CheckNoFileOverwrite(	pDlg,
										CUString( pDlg->m_strWavFileName ) + _W( ".wav" ), 
										TRUE,
										pDlg->m_bYesToAll,
										bNoToAll ) )
		{
			// Open the input stream if available
			if (	pDlg->m_pInStream && 
					pDlg->m_pInStream->OpenStream( CUString( pDlg->m_strMP3FileName ) ) )
			{
				DWORD	dwBufferSize = pDlg->m_pInStream->GetBufferSize();

				// Reset estimate timer
 				dwTotalTime = pDlg->m_pInStream->GetTotalTime();
 				pDlg->m_TimeTrack.ReInit( dwTotalTime );

				// Create a play stream object
				OSndStreamWAV wavStream;

				wavStream.CopyStreamInfo( *pDlg->m_pInStream );

				// Initialize output WAV stream object
				wavStream.OpenStream( CUString( pDlg->m_strWavFileName ) );

				// Allocate stream input buffer
				pStream = new BYTE[ dwBufferSize ];

				int nMPEGBytes = 0;

				double dSampleRatio = 1.0;

				BOOL bFinished = FALSE;

				while( ( FALSE == bFinished ) && !pDlg->m_bAbortThread )
				{
					nMPEGBytes = pDlg->m_pInStream->Read( pStream, dwBufferSize );
	
					if ( nMPEGBytes > 0 )
					{

						for ( dwIndex=0; dwIndex< (DWORD)nMPEGBytes / 2; dwIndex++ )
						{
							if ( abs( ((SHORT*)pStream)[dwIndex]) > nPeakValue )
								nPeakValue=abs( ((SHORT*)pStream )[ dwIndex ] );
						}

						if ( nMPEGBytes > 0 )
						{
							wavStream.Write( pStream, nMPEGBytes );
						}

						int nTotalTime = pDlg->m_pInStream->GetTotalTime();
						int nCurrentTime = pDlg->m_pInStream->GetCurrentTime();

						if ( nTotalTime )
						{
							pDlg->m_nPercentCompleted = nCurrentTime * 100 / nTotalTime;
						}
						else
						{
							pDlg->m_nPercentCompleted = 0;
						}
					}
					else
					{
						bFinished = TRUE;
					}

				}

				delete [] pStream; pStream= NULL;

				// Close input stream
				pDlg->m_pInStream->CloseStream();

				// Close the WAV stream
				wavStream.CloseStream();

				// close the Input stream

				// Check if we have to normalize the file
				if (	pDlg->m_pFileDlg->m_bNormalize && 
						FALSE == pDlg->m_bAbortThread )
				{
					double dNormFactor=1.0;

					// Reset estimate timer
					pDlg->m_TimeTrack.ReInit(dwTotalTime);

					// Set percentage completed to zero
					pDlg->m_nPercentCompleted=0;

					// Determine normalization factor
					dNormFactor=((nPeakValue-1.0)/327.68);

					// DO we have to normalize this file
					if (dNormFactor<(double)g_config.GetLowNormLevel() || dNormFactor>(double)g_config.GetHighNormLevel())
					{
						if (dNormFactor<(double)g_config.GetLowNormLevel())
						{
							// Normalize to for desired level
							dNormFactor=(double)g_config.GetLNormFactor()/dNormFactor;
						}
						else
						{
							// Normalize to for desired level
							dNormFactor=(double)g_config.GetHNormFactor()/dNormFactor;
						}

						// Little fine tuning to avoid overflows due to round off errors
						dNormFactor*=0.9999;

						LTRACE( _T( "CMP3ToWavDlg::Normalizing Track/File %s with factor %f" ), pDlg->m_strWavFileName, dNormFactor );

						CWAV myWav;

						// Step 1: Open the input WAV file
						if ( myWav.StartNormalizeAudioFile( CUString( pDlg->m_strWavFileName ) )!=0)
						{
							// Step 2: Loop through data and normalize chunk
							while ( myWav.NormalizeAudioFileChunk( dNormFactor, pDlg->m_nPercentCompleted ) == FALSE && 
									!pDlg->m_bAbortThread )
							{
								::Sleep(0);
							}
					
							// Step 3: Close the input WAV file, and replace original
							myWav.CloseNormalizeAudioFile( CUString( pDlg->m_strWavFileName ) , pDlg->m_bAbortThread, TRUE );
						}
					}
				}

				// Check if thread has been aborted, if so, remove original file
				if ( TRUE == pDlg->m_bAbortThread )
				{
					LTRACE( _T( "Deleting file ( due to abort ) %s.wav" ), pDlg->m_strWavFileName );
					DeleteFile( pDlg->m_strWavFileName + _T( ".wav" ) );
				}

				// Check if we have to delete the file
				if ( pDlg->m_pFileDlg->m_bDeleteOriginal && ( FALSE == pDlg->m_bAbortThread )  )
				{
					LTRACE( _T( "Deleting file ( user request ) %s" ), pDlg->m_strMP3FileName );
					DeleteFile( pDlg->m_strMP3FileName );
				}
			}
		}
		else
		{
			if ( TRUE == bNoToAll )
			{
				pDlg->m_bAbortThread = TRUE;
			}
		}

		// delete input stream object
		delete pDlg->m_pInStream;pDlg->m_pInStream=NULL;

		// Jump to the next track
		pDlg->m_wCurrentTrack++;
	}

	pDlg->m_eThreadFinished.SetEvent();

	// OK close the stuff
	pDlg->PostMessage( WM_COMMAND, IDCANCEL,0);

	EXIT_TRACE( _T( "RipFunc" ) );
	return 0;
}
示例#18
0
UINT CPlayerView::PlayThreadFunc(PVOID pParams)
{
	BYTE*			pStream		 = NULL;
	CDEX_ERR		bErr		 = CDEX_OK;
	CPlayerView*	pDlg		 = NULL;
	int				nCurrentFile = -1;
	CString			strFileName;

	ENTRY_TRACE( _T( "CPlayerView::PlayFunc" ) );

	nCurrentFile	= 0;

	pDlg=(CPlayerView*)pParams;

	pDlg->m_bAbortThread	= FALSE;
	pDlg->m_nTotalTime = 0;
	pDlg->m_nCurrentTime = 0;

	nCurrentFile = 	pDlg->m_PlayList.GetCurSel( );

	if ( pDlg->GetPlayRandom() )
	{
		srand( (unsigned)time( NULL ) );
		nCurrentFile = rand() % pDlg->m_vFileNames.size();
	}

	if ( nCurrentFile < 0 )
	{
		nCurrentFile = 0;
	}

	while(	( nCurrentFile >= 0 ) &&
			( nCurrentFile < (int)pDlg->m_vFileNames.size() ) && 
			( FALSE == pDlg->m_bAbortThread ) )
	{
		DWORD	dwStreamIndex=0;

		strFileName = pDlg->m_vFileNames[ nCurrentFile ];

#ifdef _DEBUG
//		strFileName = "http://urn.nottingham.ac.uk/urnlive.pls";
//		strFileName = "http://reclib.su.nottingham.ac.uk:8080";
#endif

		pDlg->m_PlayList.SetCurSel( nCurrentFile );

		LTRACE( _T( "Playing track %s (file %d)" ), strFileName, nCurrentFile );

		pDlg->SetThreadCommand( THREAD_PLAY_NEXT_TRACK );

		// Delete the old stream if it does exist
		if ( pDlg->m_pInStream )
		{
			delete pDlg->m_pInStream; pDlg->m_pInStream = NULL;
		}


		// create proper input stream
		pDlg->m_pInStream = ICreateStream( CUString( strFileName ) ); 

		pDlg->m_dwSeekOffset = 0;

		// Open the MPEG stream
		if (pDlg->m_pInStream->OpenStream( CUString( strFileName ) ) )
		{
			DWORD	dwInBufferSize = pDlg->m_pInStream->GetBufferSize();
			int		nMPEGBytes=0;

			// Create a play stream object
			pDlg->m_pPlayStream=new PlayWavStream;

			pDlg->m_pPlayStream->CopyStreamInfo( *pDlg->m_pInStream );

			// Initialize play stream object
			if ( FALSE == pDlg->m_pPlayStream->OpenStream( _W( "" ) ) )
			{
				pDlg->m_bAbortThread = TRUE;
			}

			// Allocate stream input buffer
			auto_ptr<BYTE> pStream( new BYTE[ dwInBufferSize  + STREAMBUFFERSIZE ] );
	
			pDlg->m_bAbortCurrent = FALSE;

			// Set status
			pDlg->m_nStatus = PLAYING;

			while ( ( !pDlg->m_bAbortThread ) && 
					( FALSE == pDlg->m_bAbortCurrent ) )
			{

				if ( PLAYING != pDlg->m_nStatus )
				{
					WaitForSingleObject( pDlg->m_ePaused, INFINITE );
					dwStreamIndex = 0;
					pDlg->m_pInStream->Seek( pDlg->m_dwSeekOffset, SEEK_TIME );

				}

				if ( pDlg->m_bAbortThread )
				{
					break;
				}

				if ( (nMPEGBytes = pDlg->m_pInStream->Read( (BYTE*)( pStream.get() ) + dwStreamIndex,dwInBufferSize ) ) >0 )
				{
					// increase current stream index position
					dwStreamIndex += nMPEGBytes ;

					// play the stuff when there is STREAMBUFFERSIZE samples are present
					while ( ( dwStreamIndex >= STREAMBUFFERSIZE ) && 
							( FALSE == pDlg->m_bAbortThread )  &&
							( FALSE == pDlg->m_bAbortCurrent ) )
					{
						if ( PLAYING != pDlg->m_nStatus )
						{
							break;
						}

						pDlg->m_pPlayStream->Write( pStream.get(), STREAMBUFFERSIZE );
						dwStreamIndex-= STREAMBUFFERSIZE;
						memmove( pStream.get() , (BYTE*)pStream.get() + STREAMBUFFERSIZE, dwStreamIndex );
					}

					pDlg->m_dwBitRate=pDlg->m_pInStream->GetBitRate();
					pDlg->m_nTotalTime=pDlg->m_pInStream->GetTotalTime();
				}
				else
				{
					while ( dwStreamIndex )
					{
						DWORD dwBytes = min( STREAMBUFFERSIZE, dwStreamIndex );

						if ( pDlg->m_bAbortThread )
						{
							break;
						}

						if ( dwBytes < STREAMBUFFERSIZE )
						{
							memset( (BYTE*)pStream.get() + dwBytes, 0, STREAMBUFFERSIZE - dwBytes );
						}

						pDlg->m_pPlayStream->Write( pStream.get(), STREAMBUFFERSIZE );

						dwStreamIndex-= dwBytes;

						if ( dwStreamIndex )
						{
							memmove( pStream.get() , (BYTE*)pStream.get() + dwBytes, dwStreamIndex );
						}
					}

					pDlg->m_bAbortCurrent = TRUE;
				}
			}
		}
		else
		{
			pDlg->MessageBox( _T( "Problem opening the file" ) );
		}

		// Close the mpeg stream
		if (pDlg->m_pInStream)
		{
			pDlg->m_pInStream->CloseStream();

			// Don't delete it, since we want to able to get 
			// the file details
		}

		// Close the play stream
		if (pDlg->m_pPlayStream)
		{
			LTRACE( _T( "Closing the output stream !!!!" ) );
			pDlg->m_pPlayStream->CloseStream();
		}


		delete pDlg->m_pPlayStream; pDlg->m_pPlayStream = NULL;

		switch ( pDlg->GetThreadCommand() )
		{
			case THREAD_PLAY_NEXT_TRACK:
				if ( pDlg->GetPlayRandom() )
				{
					int nNewFile = nCurrentFile;

					// randomize until we got a different track
					while ( pDlg->m_vFileNames.size() > 1 &&
							nCurrentFile == nNewFile )
					{
						srand( (unsigned)time( NULL ) );
						nNewFile = rand() % pDlg->m_vFileNames.size();
					}
					nCurrentFile = nNewFile;
				}
				else
				{
					nCurrentFile++;
				}
			break;
			case THREAD_PLAY_PREV_TRACK:
				if ( nCurrentFile > 0 )
				{
					nCurrentFile--;
				}
			break;
			case THREAD_PLAY_FINISH:
				pDlg->m_bAbortThread = TRUE;
			break;
			case THREAD_PLAY_TRACK:
				nCurrentFile = 	pDlg->m_PlayList.GetCurSel( );
			break;
		}
	}

	pDlg->m_nStatus = IDLE;

	pDlg->m_pThread = NULL;

	pDlg->m_eThreadFinished.SetEvent();

	EXIT_TRACE( _T( "CPlayerView::PlayThreadFunc" ) );

	return 0;
}
示例#19
0
/*
 * Read the input file
 */
void *
RecvBlock(void * args) 
{
  config * conf = (config *)args;
  int fd = 0;
  
  int check_count = 0;

  fd = open(conf->infile, O_RDONLY|O_LARGEFILE);
  if (fd < 0) {
    perror("infile open");
    return NULL;
  }

  send_buf_item * item;

  while(1) {  
    item = (send_buf_item*)malloc(sizeof(send_buf_item));

    if (xread(fd, &item->type, sizeof(item->type)) < 0){
      perror("xread:");
      EXIT_TRACE("xread type fails\n");
      return NULL;
    }
    send_body * body;
    send_head * head;

    if (item->type == TYPE_FINISH) {
      break;
    }

    int checkbit;
      
    //get the item
    switch (item->type) {
    case TYPE_FINGERPRINT:
      //if fingerprint, put it into sendcache thread
      body = (send_body *)malloc(sizeof(send_body));
      if (xread(fd, &body->cid, sizeof(body->cid)) < 0){
        EXIT_TRACE("xread body fails\n");
      }
      if (body->cid == check_count) {
        check_count ++;
      } else {
        printf("error check-count %d, body->cid %d\n", check_count, body->cid);
      }
      if (xread(fd, &body->len, sizeof(body->len)) < 0){
        EXIT_TRACE("xread body fails\n");
      }
      item->str = (u_char *)body;
      if (body->len > 0) {        

        item->content = (u_char *)malloc(body->len);
        if (item->content == NULL) {
          printf ("Error: Content is NULL\n");
          perror("malloc");
        }
      
        if (xread(fd, item->content, body->len) < 0){
          perror("xread:");
          EXIT_TRACE("fp xread content fails\n");
        }    
        //send to checkcache
        buf_checkcache[head_checkcache] = item;
        head_checkcache ++;
        if (head_checkcache == NUM_BUF_CHECKCACHE) head_checkcache = 0;
      }
      break;
    case TYPE_COMPRESS:
      //if compressed data, send it to decompress thread
      body = (send_body *)malloc(sizeof(send_body));
      if (xread(fd, &body->cid, sizeof(body->cid)) < 0){
        EXIT_TRACE("xread body fails\n");
      }
      if (body->cid == check_count) {
        check_count ++;
      } else {
        printf("error check-count %d, body->cid %d\n", check_count, body->cid);
      }
      if (xread(fd, &body->len, sizeof(body->len)) < 0){
        EXIT_TRACE("xread body fails\n");
      }
      item->str = (u_char *)body;
      if (body->len > 0) {
        item->content = (u_char *)malloc(body->len*sizeof(u_char));
        if (xread(fd, item->content, body->len) < 0){
          perror("xread");
          EXIT_TRACE("compress: xread content fails\n");
        }
        //send to decompress
        buf_decompress[head_decompress] = item;
        head_decompress ++;
        if (head_decompress == NUM_BUF_DECOMPRESS) head_decompress = 0;
      }
      break;
    case TYPE_HEAD:
      //if file header, initialize
      if (xread(fd, &checkbit, sizeof(int)) < 0){
        EXIT_TRACE("xwrite head fails\n");
      }
      if (checkbit != CHECKBIT) {
        printf("format error!\n");
        exit(1);
      }
      head = (send_head *)malloc(sizeof(send_head));
      if (xread(fd, head, sizeof(send_head)) < 0){
        EXIT_TRACE("xread head fails\n");
      }
      item->str = (u_char *)head;
      buf_reassemble[head_reassemble] = item;
      head_reassemble ++;
      if (head_reassemble == NUM_BUF_REASSEMBLE) head_reassemble = 0;
      break;
    }    
  }

  end_RecvBlock = TRUE;
  close(fd);
  return NULL;
}
示例#20
0
文件: Aspi.cpp 项目: joshlong/libcd
CDEX_ERR InitAspiDll( bool& bUseNtScsi )
{
	CDEX_ERR bReturn = CDEX_OK;
	TCHAR lpszPathName[ MAX_PATH + 1 ] = {'\0',};

	ENTRY_TRACE( _T( "InitAspiDLL( %d )" ), bUseNtScsi );

	if ( FALSE == bUseNtScsi ) 
	{
		LTRACE( _T( "Try to use the ASPI libraries" ) );

		// try to load DLL ( no path )
		_tcscpy( lpszPathName, _T( "wnaspi32.dll" ) );

		hAspiLib = LoadLibrary( lpszPathName );

		LTRACE( _T( "Trying to load DLL: \"%s\", results: %d" ), lpszPathName, hAspiLib );

		// check result
		if ( NULL == hAspiLib )
		{
			// try to load DLL from the system directory
			GetSystemDirectory( lpszPathName, MAX_PATH );

			_tcscat( lpszPathName, _T( "\\wnaspi32.dll" ) );
			
			hAspiLib = LoadLibrary( lpszPathName );

			LTRACE( _T( "Trying to load DLL: \"%s\", results: %d" ), lpszPathName, hAspiLib );

			// if failed, try the windows\system directory
			if ( NULL == hAspiLib )
			{
				// try to load DLL from the system directory
				GetWindowsDirectory( lpszPathName, MAX_PATH );

				_tcscat( lpszPathName, _T( "\\wnaspi32.dll" ) );

				hAspiLib = LoadLibrary( lpszPathName );

				LTRACE( _T( "Trying to load DLL: \"%s\", results: %d" ), lpszPathName, hAspiLib );
			}

			// try to use the ASPI library installed by Nero
			if (NULL == hAspiLib)
			{
				HKEY	ahead;

				if (RegOpenKey( HKEY_LOCAL_MACHINE, _T( "Software\\Ahead\\Shared" ), &ahead ) == ERROR_SUCCESS)
				{
					DWORD	size;
					DWORD	type;

					RegQueryValueEx( ahead, _T( "NeroAPI" ), 0, &type, 0, &size );
					RegQueryValueEx( ahead, _T( "NeroAPI" ), 0, &type, (BYTE *) &lpszPathName, &size );

					RegCloseKey( ahead );

					_tcscpy( lpszPathName,  _T( "\\wnaspi32.dll" ) );

					hAspiLib = LoadLibrary( lpszPathName );
				}
			}
		}

		// check ASPI results
		if ( NULL == hAspiLib )
		{
			OSVERSIONINFO	osVersion;

			memset( &osVersion, 0x00, sizeof( osVersion ) );

			osVersion.dwOSVersionInfoSize = sizeof( osVersion );

			GetVersionEx( &osVersion );

			if ( VER_PLATFORM_WIN32_NT == osVersion.dwPlatformId )
			{
				LTRACE( _T( "Native SCSI supported, but not selected" ) );
				bReturn = CDEX_NATIVEEASPISUPPORTEDNOTSELECTED;
			}
			else
			{
				LTRACE( _T( "Native NOT SCSI supported, platform ID = %d" ), osVersion.dwPlatformId );
				bReturn = CDEX_FAILEDTOLOADASPIDRIVERS;
			}

		}
	}
	else
	{
		LTRACE( _T( "Try to use the Native NT SCSI libraries" ) );

		// Use native NT SCSI library
		if ( NtScsiInit() > 0 )
		{
			LTRACE( _T( "Use of Native NT SCSI libraries supported, return OK" ) );
			bReturn = CDEX_OK;
		}
		else
		{
			LTRACE( _T( "Native NOT SCSI supported" ) );
			bReturn = CDEX_NATIVEEASPINOTSUPPORTED;
		}
	}

	if ( CDEX_OK == bReturn )
	{
		if ( FALSE == bUseNtScsi )
		{
			GetASPI32SupportInfo	=(GETASPI32SUPPORTINFO)GetProcAddress(hAspiLib,TEXT_GETASPI32SUPPORTINFO);
			SendASPI32Command		=(SENDASPI32COMMAND)GetProcAddress(hAspiLib,TEXT_SENDASPI32COMMAND);
			//	GetASPI32Buffer			=(GETASPI32BUFFER)GetProcAddress(hAspiLib,TEXT_GETASPI32BUFFER);
			//	FreeASPI32Buffer		=(FREEASPI32BUFFER)GetProcAddress(hAspiLib,TEXT_FREEASPI32BUFFER);
			//	GetASPI32DLLVersion		=(GETASPI32DLLVERSION)GetProcAddress(hAspiLib,TEXT_GETASPI32DLLVERSION);
			//	TranslateASPI32Address	=(TRANSLATEASPI32ADDRESS)GetProcAddress(hAspiLib,TEXT_TRANSLATEASPI32ADDRESS);
		}
		else
		{
			GetASPI32SupportInfo	= NtScsiGetASPI32SupportInfo;
			SendASPI32Command		= NtScsiSendASPI32Command;
		}

		if (	GetASPI32SupportInfo	==NULL	|| 
				SendASPI32Command		==NULL
	//			GetASPI32Buffer			==NULL	||
	//			FreeASPI32Buffer		==NULL	
	//			|| TRUE
	//			GetASPI32DLLVersion		==NULL	|| 
	//			TranslateASPI32Address	==NULL
				)
		{
			LTRACE( _T( "InitAspiDLL::Invalid Pointer: GetASPI32SupportInfo=%p, SendASPI32Command=%p"), GetASPI32SupportInfo, SendASPI32Command );

			FreeLibrary( hAspiLib );
			hAspiLib = NULL;

			GetASPI32SupportInfo = NULL;
			SendASPI32Command = NULL;

			bReturn = CDEX_FAILEDTOLOADASPIDRIVERS;
		}
	}

	EXIT_TRACE( _T( "InitAspiDLL, return value %d" ), bReturn );
	
	return bReturn;
}
示例#21
0
UINT CCDPlayDigital::RipAndPlay( PVOID pParams )
{
	CDEX_ERR	bReturn = CDEX_OK;
	long		nBufferSize = 0;
	BOOL		bPause = FALSE;

	// tracing info
	ENTRY_TRACE( _T( "CCDPlayDigital::RipAndPlay" ) );
	
	// get pointer to active CCDPlayDigital object
	CCDPlayDigital* pParent= (CCDPlayDigital*)pParams ;

	pParent->m_bAbort = FALSE;

	auto_ptr<PlayWavStream> pPlayStream( new PlayWavStream );

	if ( NULL == pPlayStream.get() )
	{
		bReturn = CDEX_ERROR;
	}
	else
	{
		pPlayStream->SetSampleRate( 44100 );
		pPlayStream->SetChannels( 2 );
		pPlayStream->SetBytesPerSample( sizeof( SHORT ) );
	}

	// Initialize play stream object
	if ( FALSE == pPlayStream->OpenStream( _W("") ) )
	{
		bReturn = CDEX_ERROR;
	}
	else
	{
	}

	DWORD dwSampleBufferSize = pPlayStream->GetBufferSize() / sizeof( SHORT );


	if ( CDEX_OK == bReturn )
	{
		bReturn = CR_OpenRipper(	&nBufferSize,
									pParent->GetBeginSector(),
									pParent->GetEndSector(),
                                    FALSE );
	}

	if ( CDEX_OK == bReturn )
	{
		LONG			nNumBytesRead = 0;
		LONG			nOffset = 0;
		
		// create the stream buffer, allocate on enocder frame additional memory
		auto_ptr<BYTE> pbtBufferStream( new BYTE[ nBufferSize + pPlayStream->GetBufferSize() + 16383 ] );

		// Get a pointer to the buffer
		BYTE* pbtStream = pbtBufferStream.get();

		CDEX_ERR ripErr;

		// Read all chunks
		while (	( CDEX_RIPPING_DONE  != ( ripErr = CR_RipChunk( pbtStream + nOffset, &nNumBytesRead, (BOOL&)pParent->m_bAbort ) ) ) 
				&& !*(volatile BOOL*)&pParent->m_bAbort )
		{
			SHORT*	psEncodeStream=(SHORT*)pbtStream;
			DWORD	dwSamplesToConvert= ( nNumBytesRead + nOffset ) / sizeof( SHORT );

			while ( pParent->m_bPause )
			{
				if ( FALSE == bPause )
				{
					pParent->m_dwCurrentTime = 0;
					pParent->m_dwSeekTimeOffset = pPlayStream->GetCurrentTime();

					bPause = TRUE;
					pPlayStream->Pause();
				}

				::Sleep( 10 );
			}

			if ( bPause )
			{
				pPlayStream->Resume();
				bPause = FALSE;
			}


			// Check for jitter errors
			if ( CDEX_JITTER_ERROR == ripErr )
			{
			}

			// Check if an error did occur
			if ( CDEX_ERROR == ripErr )
			{
				LTRACE( _T( "RipToEncoder::CDEX_ERROR" ) );
				break;
			}

			// Get progress indication
			//nPercent = CR_GetPercentCompleted();

			// Get relative jitter position
			// nJitterPos = CR_GetJitterPosition();

			// Get the number of jitter errors
			// nJitterErrors = CR_GetNumberOfJitterErrors();

			// Get the Peak Value
			// nPeakValue = CR_GetPeakValue();

			// Convert the samples with the encoder
			while ( dwSamplesToConvert >= dwSampleBufferSize )
			{
				if( FALSE == pPlayStream->Write( (BYTE*)psEncodeStream, dwSampleBufferSize * sizeof( SHORT ) ) )
				{
					pParent->m_bAbort = TRUE;
					bReturn = CDEX_ERROR;
				}

				pParent->m_dwCurrentTime = pPlayStream->GetCurrentTime();
				pParent->m_dwBytesWritten += dwSampleBufferSize * sizeof( SHORT );

				// Decrease the number of samples to convert
				dwSamplesToConvert -= dwSampleBufferSize;

				// Increase the sample buffer pointer
				psEncodeStream += dwSampleBufferSize;
			}

			// Copy the remaing bytes up front, if necessary
			if ( dwSamplesToConvert > 0 )
			{
				// Calculate the offset in bytes
				nOffset = dwSamplesToConvert * sizeof( SHORT );

				// Copy up front
				memcpy( pbtStream, psEncodeStream, nOffset );
			}
			else
			{
				nOffset = 0;
			}
		}

		// stop as quickly as possible on when aborting
		if ( pParent->m_bAbort )
		{
			pPlayStream->Pause();
			pPlayStream->Stop();
		}
		else
		{
			if ( nOffset && pParent->m_bAbort )
			{
				if( FALSE == pPlayStream->Write( pbtStream, nOffset ) )
				{
					bReturn = CDEX_ERROR;
				}
				pParent->m_dwBytesWritten += nOffset;
			}

			LTRACE( _T( "Wait for player to Finish" ) );
		}

		// Close the WAV player
		pPlayStream->CloseStream();
	
		LTRACE( _T( "Player finished" ) );

		// Close the Ripper session

		CR_CloseRipper( NULL );

	}
	else
	{
		ASSERT( FALSE );
	}

	pParent->m_pThread = NULL;
	pParent->m_bIsPlaying = FALSE;

	EXIT_TRACE( _T( "RipAndPlay" ) );

	return bReturn;
}
示例#22
0
CCDPlayDigital::~CCDPlayDigital()
{
	ENTRY_TRACE( _T( "CCDPlayDigital::~CCDPlayDigital" ) );
	EXIT_TRACE( _T( "CCDPlayDigital::~CCDPlayDigital" ) );
}
示例#23
0
CDEX_ERR CEncoderLameDll::OpenStream(CUString strOutFileName,DWORD dwSampleRate,WORD nChannels)
{
	CDEX_ERR bReturn = CDEX_OK;

	CUString strLang;
    CUStringConvert strCnv;

	ENTRY_TRACE( _T( "CEncoderLameDll::OpenStream( %s, %ld, %d" ),
				strCnv.ToT( strOutFileName + _W( "." ) + GetExtension() ),
				dwSampleRate,
				nChannels );


	DWORD dwInSampleRate = dwSampleRate;

	m_strStreamFileName = strOutFileName;

	// clear all config settings
	memset( &m_beConfig, 0, sizeof(m_beConfig) );

	// set the number of input channels
	m_nInputChannels = nChannels;

	// Divide sample rate by two for MPEG2
	if ( ( GetVersion() >=1 ) && ( dwInSampleRate >= 32000 ) )
	{
		m_dResampleRatio = 2.0;
		dwSampleRate = dwInSampleRate / 2;
	}

	// mask mode, just to be sure (due to an old hack)
	m_nMode &= 0x0F;

	// Do we have to downmix/upmix ?
	if ( BE_MP3_MODE_MONO == m_nMode )
	{
		if ( 2 == nChannels )
		{
			m_bDownMixToMono = TRUE;
		}
		else
		{
			m_bDownMixToMono = FALSE;
		}
	}
	else 
	{
		if ( 1 == nChannels )
		{
			m_bUpMixToStereo = TRUE;
		}
		else
			m_bUpMixToStereo=FALSE;
	}

	int	nCRC		= m_bCRC;
	int nVBR		= (nCRC>>12)&0x0F;
	int nVbrMethod	= (nCRC>>16)&0x0F;

	m_beConfig.dwConfig						= BE_CONFIG_LAME;
	m_beConfig.format.LHV1.dwStructVersion	= 1;
	m_beConfig.format.LHV1.dwStructSize		= sizeof(m_beConfig);
	m_beConfig.format.LHV1.dwSampleRate		= dwSampleRate;
	m_beConfig.format.LHV1.dwReSampleRate	= m_nOutSampleRate;
	m_beConfig.format.LHV1.nMode			= m_nMode; 
	m_beConfig.format.LHV1.dwBitrate		= m_nBitrate;
	m_beConfig.format.LHV1.dwMaxBitrate		= m_nMaxBitrate;
	m_beConfig.format.LHV1.dwMpegVersion	= (dwSampleRate>=32000)?MPEG1:MPEG2;
	m_beConfig.format.LHV1.dwPsyModel		= 0;
	m_beConfig.format.LHV1.dwEmphasis		= 0;
	m_beConfig.format.LHV1.bCRC				= nCRC&0x01;;
	m_beConfig.format.LHV1.bCopyright		= m_bCopyRight;
	m_beConfig.format.LHV1.bPrivate			= m_bPrivate;
	m_beConfig.format.LHV1.bOriginal		= m_bOriginal;

	// allways write the VBR header, even for CBR file
	m_beConfig.format.LHV1.bWriteVBRHeader	= TRUE;

	if ( nVbrMethod > 0 )
	{
		m_beConfig.format.LHV1.bEnableVBR		= TRUE;
		m_beConfig.format.LHV1.nVbrMethod		= (VBRMETHOD)(nVbrMethod-1) ;

		// is this the ABR method ?
		if ( ( VBR_METHOD_ABR + 1 ) == nVbrMethod )
		{
			// get the average bit rate
			m_beConfig.format.LHV1.dwVbrAbr_bps= LOWORD( GetUserN1() )*1000;
			m_beConfig.format.LHV1.nVBRQuality = 0 ;
		}
		else
		{
			// no ABR selected
			m_beConfig.format.LHV1.dwVbrAbr_bps = 0;
			m_beConfig.format.LHV1.nVBRQuality = nVBR ;
		}
	}

	// Get Quality from third nibble
	m_beConfig.format.LHV1.nPreset=( (nCRC >> 8 ) & 0x0F );

	m_fpOut= CID3Tag::SaveInitialV2Tag( strOutFileName + _W( "." ) + GetExtension(), GetId3V2PadSize() );
    //m_fpOut = CDexOpenFile( strOutFileName + _W( "." ) + GetExtension(), _W( "wb+" ) );

	if ( NULL == m_fpOut )
	{
		CUString strErr;

		strLang = g_language.GetString( IDS_ENCODER_ERROR_COULDNOTOPENFILE );

		strErr.Format( strLang, (LPCWSTR)CUString( strOutFileName + _W( "." ) + GetExtension() ) );

        CDexMessageBox( strErr );

		bReturn  = CDEX_FILEOPEN_ERROR;
	}


	if ( CDEX_OK == bReturn )
	{
		int nReturn = m_InitStream(	&m_beConfig,
									&m_dwInBufferSize,
									&m_dwOutBufferSize,
									&m_hbeStream );

		switch ( nReturn )
		{
			case CDEX_OK:
				// do nothing
			break;
			case -1:
				strLang = g_language.GetString( IDS_ENCODER_ERROR_SAMPLERATEBITRATEMISMATCH );
				CDexMessageBox( strLang );
				bReturn = CDEX_ERROR;
			break;
			case -2:
				strLang = g_language.GetString( IDS_ENCODER_ERROR_INVALIDINPUTSTREAM );
				CDexMessageBox( strLang );
				bReturn = CDEX_ERROR;
			break;
			default:
				strLang = g_language.GetString( IDS_ENCODER_ERROR_INVALIDINPUTSTREAM );
				CDexMessageBox( strLang );
				bReturn = CDEX_ERROR;
			break;

		}
	}

	if ( CDEX_OK == bReturn )
	{

		if ( ( GetVersion() >= 1 ) && ( dwInSampleRate >= 32000 ) )
		{
			// Add multiplcation factor for resampling
			m_dwInBufferSize *= 2;
		}

		if ( m_bDownMixToMono )
		{
			m_dwInBufferSize *= 2;
		}


		// Allocate Output Buffer size
		m_pbOutputStream = new BYTE[ m_dwOutBufferSize ];

		// Only expect halve the number of samples
		// in case we have to upsample
		if ( m_bUpMixToStereo )
		{
			// Allocate upsample Buffer size
			m_psInputStream = new SHORT[ m_dwInBufferSize ];

			m_dwInBufferSize /= 2;

		}
	}

	if ( CDEX_OK == bReturn ) 
	{
		// Initialize the input stream
		bReturn = InitInputStream();
	}


	EXIT_TRACE( _T( "CEncoderLameDll::OpenStream, return value %d" ), bReturn );

	return bReturn;
}
示例#24
0
int main(int argc, char **argv)
{
        char 				infile[100];		
	int				sd;
	struct sockaddr_in 	pin;
	int 				ch;
	
	/* parse the args */
	opterr = 0;
	optind = 1;
	while (-1 != (ch = getopt(argc, argv, "pi:h"))) {
	    switch (ch) {
	    case 'i':
	      strcpy(infile, optarg);
	      break;
	    case 'h':
	      usage(argv[0]);
	      return -1;
	    case '?':
	      fprintf(stdout, "Unknown option `-%c'.\n", optopt);
	      usage(argv[0]);
	      return -1;
	    }
	}

	/* fill in the socket structure with host information */
	memset(&pin, 0, sizeof(pin));
	pin.sin_family = AF_INET;
	pin.sin_addr.s_addr = htonl(SERVER_IP);
	pin.sin_port = htons(PORT);

	/* grab an Internet domain socket */
#ifdef ENABLE_PARSEC_UPTCPIP
	if ((sd = uptcp_socket(AF_INET, SOCK_STREAM, 0)) == -1) {
#else
	if ((sd = socket(AF_INET, SOCK_STREAM, 0)) == -1) {
#endif
		EXIT_TRACE("Socket error: socket()\n");
	}

	/* connect to PORT on HOST */
#ifdef ENABLE_PARSEC_UPTCPIP
	if (uptcp_connect(sd,(struct sockaddr *)  &pin, sizeof(pin)) < 0) {
#else
	if (connect(sd,(struct sockaddr *)  &pin, sizeof(pin)) < 0) {
#endif
		EXIT_TRACE("Socket error: connect()\n");
		
	}

	/* Read data from input file*/
	struct stat filestat;
  	int fd;

	  /* src file stat */
	if (stat(infile, &filestat) < 0) 
	      EXIT_TRACE("stat() %s failed: %s\n",infile, strerror(errno));

	if (!S_ISREG(filestat.st_mode)) 
	    EXIT_TRACE("not a normal file: %s\n", infile);

        /* send file size to server */
#ifdef ENABLE_PARSEC_UPTCPIP
        if (uptcp_send(sd,  &(filestat.st_size), sizeof(filestat.st_size), 0) == -1) {
#else
        if (send(sd,  &(filestat.st_size), sizeof(filestat.st_size), 0) == -1) {
#endif
              EXIT_TRACE("Socket error: cannot send input file size to server\n");
        }


        /* src file open */
	if((fd = open(infile, O_RDONLY)) < 0) 
	    EXIT_TRACE("%s file open error %s\n", infile, strerror(errno));

	  /* Load entire file into memory if requested by user */
	char *preloading_buffer;
	size_t bytes_read=0;
	int r;

	preloading_buffer = (char*)malloc(filestat.st_size);
	if(preloading_buffer == NULL)
	      EXIT_TRACE("Error allocating memory for input buffer.\n");

	    /* Read data until buffer full */
	while(bytes_read < filestat.st_size) {
	    	r = read(fd, preloading_buffer+bytes_read, filestat.st_size-bytes_read);
	      	if(r<0){
			switch(errno) {
	        	case EAGAIN:
	          		EXIT_TRACE("I/O error: No data available\n");break;
		        case EBADF:
		          	EXIT_TRACE("I/O error: Invalid file descriptor\n");break;
		        case EFAULT:
		          	EXIT_TRACE("I/O error: Buffer out of range\n");break;
		        case EINTR:
		          	EXIT_TRACE("I/O error: Interruption\n");break;
		        case EINVAL:
		          	EXIT_TRACE("I/O error: Unable to read from file descriptor\n");break;
		        case EIO:
		          	EXIT_TRACE("I/O error: Generic I/O error\n");break;
		        case EISDIR:
		          	EXIT_TRACE("I/O error: Cannot read from a directory\n");break;
		        default:
		          	EXIT_TRACE("I/O error: Unrecognized error\n");break;
		      }
	      }
	      if(r==0) break;
	      bytes_read += r;
	}


	/* Send data to server*/
	int bytes_left = filestat.st_size;
	int bytes_tosend = 0;
	char	*send_ptr = preloading_buffer;
	while(bytes_left >0){
		bytes_tosend = bytes_left; //BUFSIZE <  bytes_left ? BUFSIZE: bytes_left;
#ifdef ENABLE_PARSEC_UPTCPIP
		if (uptcp_send(sd, send_ptr, bytes_tosend, 0) == -1) {
#else
		if (send(sd, send_ptr, bytes_tosend, 0) == -1) {
#endif
			EXIT_TRACE("Socket error: send input file data error\n");
		}
		bytes_left -= bytes_tosend;
		send_ptr += bytes_tosend;
	        /* wait for a message to come back from the server */
	}

	printf("[netdedup.client]: Send data to server ok!\n");

	free(preloading_buffer);
	close(fd);
#ifdef ENABLE_PARSEC_UPTCPIP
	uptcp_close(sd);
#else
	close(sd);
#endif
	return 0;
}
示例#25
0
/*
 * Reassemble the chunks together, and write it to the file
 */
void * 
Reassemble(void * args) {
  int chunkcount = 0;

  int fd = -1;
  struct chunk_list * list_head, * p;
  list_head = NULL;

  if (args != NULL) {
    fd = open((char *)args, O_CREAT|O_WRONLY|O_TRUNC, S_IRUSR|S_IWUSR);
    if (fd < 0) 
      perror("Reassemble open");
    fchmod(fd, ~(S_ISUID | S_ISGID |S_IXGRP | S_IXUSR | S_IXOTH));
  }

  while (1) {
    int f = 0;
    f = 0;
    send_buf_item * item;
    if (tail_reassemble == head_reassemble) {
      break;     
    }
    item = buf_reassemble[tail_reassemble];
    tail_reassemble ++;
    if (tail_reassemble == NUM_BUF_REASSEMBLE) tail_reassemble = 0;

    send_body * body = NULL;
    send_head * head;
    
    switch (item->type) {
    case TYPE_FINGERPRINT:
    case TYPE_COMPRESS:
      body = (send_body *)item->str;
      if (fd == -1) {
        //if havn't get the file header, insert current chunk into the queue
        p = list_insert(list_head, body->cid);
        if (list_head ==NULL || list_head->cid > body->cid) {
          list_head = p;
        }
        p->content = item->content;
        p->cid = body->cid;
        p->len = body->len;
        MEM_FREE(body);
      } else {
          if (body->cid == chunkcount) {
            //if this chunk is in the right order, write it into the file
                          
            if (0 > xwrite(fd, item->content, body->len)) {
              perror("xwrite");
              EXIT_TRACE("xwrite\n");
            }
            chunkcount ++;
            p = list_head;
            while (p != NULL && p->cid == chunkcount) {
              if (0 > xwrite(fd, p->content, p->len)) {
                perror("xwrite");
                EXIT_TRACE("xwrite\n");
              }
              chunkcount ++;
              p = p->next;
            }
            list_head = p;
          } else {
            //if this chunk is out of order, insert it into the list
            p = list_insert(list_head, body->cid);
            if (list_head ==NULL || list_head->cid > body->cid) {
              list_head = p;
            }
            p->content = item->content;
            p->cid = body->cid;
            p->len = body->len;
          }        
          // }
      }
      break;
    case TYPE_HEAD:
      //get file header
      head = (send_head *)item->str;
      if (fd == -1) {
        fd = open(head->filename, O_CREAT|O_WRONLY|O_TRUNC, S_IRUSR|S_IWUSR);
        if (fd < 0)
          perror("head_open");
      }

      MEM_FREE(head);
      chunkcount = 0;

      p = list_head;
      while (p != NULL && p->cid == chunkcount) {
        if (0 > xwrite(fd, p->content, p->len)) {
          EXIT_TRACE("xwrite\n");
        }
        if (p->content) MEM_FREE(p->content);
        chunkcount ++;
        p = p->next;
      }
      list_head = p;
      
      break;
    }
    
    MEM_FREE(item);
  }

  //write the remaining chunks into the file
  p = list_head;
  while (p != NULL) {
    if (0 > xwrite(fd, p->content, p->len)) {
      EXIT_TRACE("xwrite\n");
    }

    if (p->cid == chunkcount) 
      chunkcount ++;
    else {
      chunkcount = p->cid+1;
    }
    p = p->next;    
  }

  close(fd);
  return NULL;
}