⭐ 欢迎来到虫虫下载站! | 📦 资源下载 📁 资源专辑 ℹ️ 关于我们
⭐ 虫虫下载站

📄 macasyncfile.cpp

📁 著名的 helix realplayer 基于手机 symbian 系统的 播放器全套源代码
💻 CPP
📖 第 1 页 / 共 3 页
字号:
/* ***** BEGIN LICENSE BLOCK ***** 
 * Version: RCSL 1.0/RPSL 1.0 
 *  
 * Portions Copyright (c) 1995-2002 RealNetworks, Inc. All Rights Reserved. 
 *      
 * The contents of this file, and the files included with this file, are 
 * subject to the current version of the RealNetworks Public Source License 
 * Version 1.0 (the "RPSL") available at 
 * http://www.helixcommunity.org/content/rpsl unless you have licensed 
 * the file under the RealNetworks Community Source License Version 1.0 
 * (the "RCSL") available at http://www.helixcommunity.org/content/rcsl, 
 * in which case the RCSL will apply. You may also obtain the license terms 
 * directly from RealNetworks.  You may not use this file except in 
 * compliance with the RPSL or, if you have a valid RCSL with RealNetworks 
 * applicable to this file, the RCSL.  Please see the applicable RPSL or 
 * RCSL for the rights, obligations and limitations governing use of the 
 * contents of the file.  
 *  
 * This file is part of the Helix DNA Technology. RealNetworks is the 
 * developer of the Original Code and owns the copyrights in the portions 
 * it created. 
 *  
 * This file, and the files included with this file, is distributed and made 
 * available on an 'AS IS' basis, WITHOUT WARRANTY OF ANY KIND, EITHER 
 * EXPRESS OR IMPLIED, AND REALNETWORKS HEREBY DISCLAIMS ALL SUCH WARRANTIES, 
 * INCLUDING WITHOUT LIMITATION, ANY WARRANTIES OF MERCHANTABILITY, FITNESS 
 * FOR A PARTICULAR PURPOSE, QUIET ENJOYMENT OR NON-INFRINGEMENT. 
 * 
 * Technology Compatibility Kit Test Suite(s) Location: 
 *    http://www.helixcommunity.org/content/tck 
 * 
 * Contributor(s): 
 *  
 * ***** END LICENSE BLOCK ***** */ 

/*

   Macintosh File buffer

   This is a class which pretends to be a file, yet that reads from the file asynchronously.

   It makes the file async calls which read the file, the callback of which spews into a 
   buffer. This is done by using a timer callback which gets called every 1/2 second to 
   spew more data into the buffer. 

   The global list is meant to be used for storage of all the different file objects
   which will get processed each time through the loop.  

   This will significantly enhance the Macintosh when it comes to local playback of files. 
 */

#include "macasyncfile.h"
#include "hxmm.h"
#include "hxslist.h"
#include "hxcore.h"
#include "hxbuffer.h"
#include "hxstrutl.h"

//#include "../dcondev/dcon.h"

//#define _LOG_DATA	1

// ULONG32 HXAsyncQueueBuffer::msAllocatedBufferCount = 0;

//#define LOG_MULTIPLE_DEFERRED_TASKS 1

#if defined(_DEBUG) && defined (_LOG_DATA)
#define DEBUGSTR(x)	DebugStr(x)
#else
#define DEBUGSTR(x)
#endif

CMacAsyncFile::CMacAsyncFile() :
     mReadQueue(NULL)
    ,mSeekFromWhere(0)
    ,mSeekPos(0)
    ,mFilePos(0)
    ,m_ulReadPositionInFile(0)
    ,m_pResponse(NULL)
    ,m_bFileDone(FALSE)
    ,m_bReadPending(FALSE)
    ,m_bSeekPending(FALSE)
    ,m_ulPendingReadCount(FALSE)
    ,mAsyncQueue(NULL)
    ,mOutStandingCallbacks(0)
    ,m_bSettingSeekState(FALSE)    
    ,m_bCheckFromPQ(FALSE)
    ,m_bInternalSeekNeeded(FALSE)
    ,m_pPendingCallbackList(NULL)
    ,m_pTimedPQList(NULL)
    ,m_pLocationPQList(NULL)
    ,m_ulTotalPQSize(0)
    ,m_bDeferredTaskPending(FALSE)
    ,m_bIsQuitting(FALSE)
    ,m_bInEnqueueAsyncBuffers(FALSE)
    ,m_bPendingAsyncSeekCompleted(FALSE)
    ,m_bAllCallbacksCompleted(FALSE)
    ,m_bInProcessPendingCallbacks(FALSE)
    ,m_pMutex(NULL)
    ,m_lRefCount(0)
{
    mAsyncQueue = new CHXSimpleList();
    m_pPendingCallbackList = new CHXSimpleList;
    m_pTimedPQList	      = new CHXSimpleList;
    m_pLocationPQList	      = new CHXSimpleList;
    mReadQueue	= new CBigByteQueue(kMacAsyncBuffer, 1);
    
    m_DeferredTaskStruct.dtReserved = 0;
    m_DeferredTaskStruct.dtFlags = 0;
#ifdef _CARBON
    m_DeferredTaskStruct.dtAddr = NewDeferredTaskUPP(CMacAsyncFile::DeferredTaskProc);
#else
    m_DeferredTaskStruct.dtAddr = NewDeferredTaskProc(CMacAsyncFile::DeferredTaskProc);
#endif
    m_DeferredTaskStruct.dtParam = (long) this; 	
    m_DeferredTaskStruct.qType = dtQType;
    
    m_uNumDeferredTask = 0;

#if defined(THREADS_SUPPORTED)
    HXMutex::MakeMutex(m_pMutex);
#else
    HXMutex::MakeStubMutex(m_pMutex);
    
    HX_ASSERT(m_pMutex);
#endif // defined(THREADS_SUPPORTED) 
}

CMacAsyncFile::~CMacAsyncFile()
{
    if (m_DeferredTaskStruct.dtAddr != NULL)
    {
#ifdef _CARBON
	DisposeDeferredTaskUPP(m_DeferredTaskStruct.dtAddr);
#else
	DisposeRoutineDescriptor(m_DeferredTaskStruct.dtAddr);
#endif
	m_DeferredTaskStruct.dtAddr = NULL;
    }    

    Close();

    HX_DELETE(mAsyncQueue);
    HX_DELETE(m_pPendingCallbackList);
    HX_DELETE(m_pTimedPQList);
    HX_DELETE(m_pLocationPQList);
    HX_DELETE(mReadQueue);
#if defined(_DEBUG) && defined(LOG_MULTIPLE_DEFERRED_TASKS)
    BOOL bWaitedForDeferred = FALSE;
    if ( m_bDeferredTaskPending )
    {
	bWaitedForDeferred = TRUE;
	DebugStr("\pCMacAsyncFile dtor -- a deferred task is pending!;g");
    }
#endif
    
    UINT32 timeout = TickCount() + 300L;
    m_bIsQuitting = TRUE;
    while ( m_bDeferredTaskPending && timeout - TickCount() > 0 )
    {
	// sit-n-spin, awaiting completion of callbacks.
    }
    
#if defined(_DEBUG) && defined(LOG_MULTIPLE_DEFERRED_TASKS)
    if ( bWaitedForDeferred )
    {
	if ( m_bDeferredTaskPending )
	{
	    DebugStr("\pdeferred task STILL pending! This is gonna hurt;g");
	}
	else
	{
	    DebugStr( "\pDeferred tasks were successfully purged;g" );
	}
    }
#endif

    HX_DELETE(m_pMutex);
}

STDMETHODIMP_(ULONG32) CMacAsyncFile::AddRef()
{
    return InterlockedIncrement(&m_lRefCount);
}

STDMETHODIMP_(ULONG32) CMacAsyncFile::Release()
{
    if (InterlockedDecrement(&m_lRefCount) > 0)
    {
	return m_lRefCount;
    }
    
    delete this;
    return 0;
}

void CMacAsyncFile::EmptyAsyncQueue()
{    
    m_pMutex->Lock();

    while(mAsyncQueue && mAsyncQueue->GetCount() > 0)
    {
        HXAsyncQueueBuffer* x = (HXAsyncQueueBuffer*) mAsyncQueue->RemoveHead();
        
        HX_DELETE(x);
    }
    
    while(m_pTimedPQList && m_pTimedPQList->GetCount() > 0)
    {
        HXAsyncQueueBuffer* x = (HXAsyncQueueBuffer*) m_pTimedPQList->RemoveHead();
        
        HX_DELETE(x);
    }  
    
    if (m_pLocationPQList)
    {
        m_pLocationPQList->RemoveAll();
    }
    
    m_ulTotalPQSize = 0;
    
    while(m_pPendingCallbackList && m_pPendingCallbackList->GetCount() > 0)
    {
        HXParamBlockRec* pb = (HXParamBlockRec*) m_pPendingCallbackList->RemoveHead();
        
        HX_DELETE(pb);
    }

    m_pMutex->Unlock();
}

void
CMacAsyncFile::DeleteAsyncQueueBuffer(HXAsyncQueueBuffer* x, LISTPOSITION pos)
{
    m_pMutex->Lock();

    BOOL bInserted;
    
    mAsyncQueue->RemoveAt(pos);
    
    /* we only keep full buffers around*/
    if (x->state != AB_STATE_FULL)
    {
        goto discard;
    }
    
    x->current_size    = x->size;
    x->current_buf_ptr = x->buffer;

    // insert in location list
    pos = m_pLocationPQList->GetTailPosition();
    bInserted = FALSE;
    while (pos)
    {
         HXAsyncQueueBuffer* pNode  = (HXAsyncQueueBuffer*) m_pLocationPQList->GetAt(pos);
         if (x->position_in_file >= pNode->position_in_file+pNode->size)
         {
             m_pLocationPQList->InsertAfter(pos, x);
             bInserted = TRUE;
             break;
         }
         
         m_pLocationPQList->GetPrev(pos);
    }
    
    if (!bInserted)
    {
        m_pLocationPQList->AddHead(x);
    }
    
    m_pTimedPQList->AddTail(x);
    m_ulTotalPQSize += x->size;
    
    //dfprintf("mem","PQ Add: %p %lu, %lu, %lu\n", this, x->position_in_file, x->size, m_ulTotalPQSize);
    // time to expire some -- keep a max of 4*48K in memory?
    if (m_ulTotalPQSize > 4*kMacAsyncBuffer)
    {
        x = (HXAsyncQueueBuffer*) m_pTimedPQList->RemoveHead();
        
        // remove from location list
        pos = m_pLocationPQList->Find((void*)x);
        HX_ASSERT(pos != NULL);
        m_pLocationPQList->RemoveAt(pos);
        
        m_ulTotalPQSize -= x->size;
        //dfprintf("mem", "PQ Remove: %lu, %lu, %lu\n", x->position_in_file, x->size, m_ulTotalPQSize);
    }
    else
    {
        // early exit
        m_pMutex->Unlock();
        return;
    }
discard:    
    delete x;

    m_pMutex->Unlock();
}


BOOL
CMacAsyncFile::FillBufferFromPQ(UINT32 ulFillPosition)
{
    m_pMutex->Lock();

    BOOL bFilled = FALSE;
    
    LISTPOSITION pos = m_pLocationPQList->GetHeadPosition();
    UINT32 ulEmptyCount = mReadQueue->GetAvailableElements();
    UINT32 ulOrigFillPosition = ulFillPosition;
    while(pos && ulEmptyCount > 0)
    {
        HXAsyncQueueBuffer* x = (HXAsyncQueueBuffer*) m_pLocationPQList->GetAt(pos);
        
        // find the starting byte
        if (x->position_in_file <= ulFillPosition && 
            x->position_in_file+x->size > ulFillPosition)
        {
            UINT32 ulBytesToCopy = x->position_in_file+x->size - ulFillPosition;
            if (ulBytesToCopy > ulEmptyCount)
            {
                ulBytesToCopy = ulEmptyCount;
            }
            
            HX_ASSERT(ulBytesToCopy > 0);
            HX_VERIFY(mReadQueue->EnQueue(x->buffer+ulFillPosition-x->position_in_file, 
            				ulBytesToCopy) == ulBytesToCopy);
            ulEmptyCount -= ulBytesToCopy;
            bFilled = TRUE;
            ulFillPosition += ulBytesToCopy;
            LISTPOSITION timedPos = m_pTimedPQList->Find((void*) x);
            HX_ASSERT(timedPos != NULL);
            m_pTimedPQList->RemoveAt(timedPos);
            m_pTimedPQList->AddTail(x);
            
            m_ulReadPositionInFile = ulFillPosition;
            
    //dfprintf("mem","FillNoSeek: %lu, %lu, %lu %lu\n", x->position_in_file, x->size, ulOrigFillPosition, ulEmptyCount);
        }
        else if (x->position_in_file > ulFillPosition)
        {
            break;
        }
        
        (void) m_pLocationPQList->GetNext(pos);
    }
    
    // continue to read data form stores buffers if we were succesfully able
    // to fill buffers this time
    m_bCheckFromPQ = bFilled;

    m_pMutex->Unlock();
    return bFilled;
}

//
//      Pump as many of the Asynchronous buffers into the mReadQueue
//      as is possible.
//
void CMacAsyncFile::EnqueueAsyncBuffers()
{
    LISTPOSITION pos = NULL;
    
    m_pMutex->Lock();
    if (m_bInEnqueueAsyncBuffers)
    {
        m_pMutex->Unlock();
        return;
    }
    
    m_bInEnqueueAsyncBuffers = TRUE;

    /* See if there are any pending callbacks */
    ProcessPendingCallbacks();
    
    pos = mAsyncQueue->GetHeadPosition();

    while(pos)
    {
	HXAsyncQueueBuffer *x =(HXAsyncQueueBuffer *) mAsyncQueue->GetAt(pos);
	if(x)
	{
	    if(x->state == AB_STATE_IGNORED)
	    {
		//
		//      Due to a seek this buffer has now become out of context
		//      So dispose of it and then check the next buffer.
		//
		DeleteAsyncQueueBuffer(x, pos);

		pos = mAsyncQueue->GetHeadPosition();
		continue;
	    }

	    if(x->state == AB_STATE_FULL)
	    {
	        UINT32 ulEmptyCount = mReadQueue->GetAvailableElements();
	        
	        /* This assumes that the pending count can NEVER be greater than
	         * the total size of the byte queue i.e. the size of the
	         * byte queue is the max read size we allow
	         * currently it is set to 48K (odd number eh?)
	         */
	        
	        if (m_bReadPending && ulEmptyCount > 0)
	        {
	            if (ulEmptyCount > x->current_size)
	            {
	                ulEmptyCount = x->current_size;
	            }
	            
	            HX_ASSERT(ulEmptyCount > 0);

	            // This used to have a HX_VERIFY on the result. After the
	            // most recent change, though, where the "m_bReadPending"
	            // if statement was changed, the assert started yelling.
	            // Nobody's very comfortable about forcibly ignoring the
	            // verify, but it seems to function.
	            HX_VERIFY(mReadQueue->EnQueue(x->current_buf_ptr, ulEmptyCount) == ulEmptyCount);
	            
	            x->current_size    -= ulEmptyCount;
	            x->current_buf_ptr += ulEmptyCount;
	            
	            if (x->current_size == 0)
	            {
			//dfprintf("mem","Done with buffer\n");
			DeleteAsyncQueueBuffer(x, pos);
		    }
		    else
		    {
		        break;
		    }
		}
		else
		{
		    break;
		}
	    }
	    else
	    {
		//
		//      In this case we have to break, because there isn't a buffer available.
		//
		break;
	    }
	}

	pos = mAsyncQueue->GetHeadPosition();
    }

    m_bInEnqueueAsyncBuffers = FALSE;
    m_pMutex->Unlock();
}

CHXDataFile *CMacAsyncFile::Construct()
{
    CMacAsyncFile *result = new CMacAsyncFile();
    
    result->AddRef();

    return result;
}

HX_RESULT CMacAsyncFile::Open(const char *filename, UINT16 mode, BOOL textflag)
{
    return HXR_NOTIMPL;
}

HX_RESULT CMacAsyncFile::SafeOpen (const char *filename, UINT16 mode, BOOL textflag, BOOL bAtInterrupt)
{
#if defined(_DEBUG) && defined (_LOG_DATA)
    char str[255]; /* Flawfinder: ignore */
   ::sprintf(str, "SafeOpen %d;g", (int) bAtInterrupt); /* Flawfinder: ignore */
    DEBUGSTR(c2pstr(str));
#endif
 
   m_pMutex->Lock();
   HX_RESULT result = CMacFile::Open(filename, mode, textflag);
   ULONG32 count = 0;

    mFilePos = 0;

⌨️ 快捷键说明

复制代码 Ctrl + C
搜索代码 Ctrl + F
全屏模式 F11
切换主题 Ctrl + Shift + D
显示快捷键 ?
增大字号 Ctrl + =
减小字号 Ctrl + -