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

📄 pindevice.cpp.svn-base

📁 PXA270 平台 Windows Mobile 5 摄像头驱动
💻 SVN-BASE
📖 第 1 页 / 共 3 页
字号:
/**************************************************************************

** INTEL CONFIDENTIAL
** Copyright 2000-2004 Intel Corporation. All Rights Reserved.
**
** The source code contained or described herein and all documents
** related to the source code (Material) are owned by Intel Corporation
** or its suppliers or licensors.  Title to the Material remains with
** Intel Corporation or its suppliers and licensors. The Material contains
** trade secrets and proprietary and confidential information of Intel
** or its suppliers and licensors. The Material is protected by worldwide
** copyright and trade secret laws and treaty provisions. No part of the
** Material may be used, copied, reproduced, modified, published, uploaded,
** posted, transmitted, distributed, or disclosed in any way without Intel抯
** prior express written permission.

** No license under any patent, copyright, trade secret or other intellectual
** property right is granted to or conferred upon you by disclosure or
** delivery of the Materials, either expressly, by implication, inducement,
** estoppel or otherwise. Any license under such intellectual property rights
** must be express and approved by Intel in writing.

********************************************************************************/

//
// Copyright (c) Microsoft Corporation.  All rights reserved.
//
//
// Use of this source code is subject to the terms of the Microsoft end-user
// license agreement (EULA) under which you licensed this SOFTWARE PRODUCT.
// If you did not accept the terms of the EULA, you are not authorized to use
// this source code. For a copy of the EULA, please see the LICENSE.RTF on your
// install media.
//
#define PININTERFACE
#include <windows.h>
#include <Msgqueue.h>
#include <pwinbase.h>
#include <camera.h>
#include "CameraDriver.h"
#include "adapterprops.h"
#include "PinDriver.h"
#include "wchar.h"


CPinDevice :: CPinDevice( )
{
    m_dwMemoryModel             = CSPROPERTY_BUFFER_CLIENT_LIMITED;
    m_fDiscontinuity            = true;
    m_ulPinId                   = -1; // Invalid Pin Id
    m_ulMaxNumOfBuffers         = BUFFER_COUNT;
    m_ulFrameSize               = 0;
    m_RtAveTimePerFrame         = 0;
    m_ulFramesDropped           = 0;
    m_ulPictureNumber           = 0;
    m_hMsgQ                     = NULL;
    m_CsState                   = CSSTATE_STOP;
    m_msStart                   = 0xFFFFFFFF;
    m_msLastPT                  = 0;
    m_pStreamDescriptorList     = NULL;
    m_dwBufferCount             = 0;

    InitializeCriticalSection( &m_csStreamBuffer );
}

CPinDevice :: ~CPinDevice( )
{
    ResetBufferList( );
    
    if ( NULL != m_hMsgQ )
    {
        CloseMsgQueue( m_hMsgQ );
    }

    if ( NULL != m_pStreamDescriptorList )
    {
        LocalFree( m_pStreamDescriptorList );
        m_pStreamDescriptorList = NULL;
    }

    m_CsState = CSSTATE_STOP;
    DeleteCriticalSection( &m_csStreamBuffer );
}

bool CPinDevice :: InitializeSubDevice( PCAMERADEVICE pCamDevice )
{
    m_pCamAdapter = pCamDevice ;
    if (NULL == m_pCamAdapter)
        return false ;

    // Let's retrieve the pin model from the registry. If none is provided, 
    // the default model will be APPLICATION_LIMITED
    ReadMemoryModelFromRegistry();   

    return true ;
}

bool CPinDevice :: CloseSubDevice()
{
    m_pCamAdapter->DecrCInstances( m_ulPinId ) ;
  
    return true ;
}

ULONG CPinDevice :: PictureNumber( ) const
{
    return m_ulPictureNumber;
}

ULONG CPinDevice :: FramesDropped( ) const
{
    return m_ulFramesDropped;
}

ULONG CPinDevice :: FrameSize( ) const
{
    return m_ulFrameSize;
}

DWORD CPinDevice :: StreamInstantiate( PCSPROPERTY_STREAMEX_S pCsPropStreamEx, PUCHAR pOutBuf, DWORD  OutBufLen, PDWORD pdwBytesTransferred )
{
    PCS_DATARANGE_VIDEO pCsDataRangeVid = NULL;
    DWORD               dwError         = ERROR_INVALID_PARAMETER;
  
    if ( -1 != m_ulPinId )
    {
        DEBUGMSG(ZONE_IOCTL|ZONE_ERROR, (_T("PIN_IOControl(%08x): Pin %d is already instantiated.\r\n"), this, m_ulPinId )) ;
        return dwError ;
    }

    if ( false == m_pCamAdapter->IsValidPin( pCsPropStreamEx->CsPin.PinId ) )
    {
        DEBUGMSG(ZONE_IOCTL|ZONE_ERROR, (_T("PIN_IOControl(%08x): Invalid Pin Id\r\n"), this)) ;
        return dwError ;
    }
    
    m_ulPinId = pCsPropStreamEx->CsPin.PinId ;
    
    // Let us set a default format for this pin

    if ( false == m_pCamAdapter->GetPinFormat( m_ulPinId, 1, &pCsDataRangeVid ) )
    {
        DEBUGMSG(ZONE_IOCTL|ZONE_ERROR, (_T("PIN_IOControl(%08x): No Pin Format provided for pin\r\n"), this)) ;
        return dwError ;
    }
    
    memcpy(&m_CsDataRangeVideo,pCsDataRangeVid, sizeof(CS_DATARANGE_VIDEO) ) ;

    if ( NULL == pCsPropStreamEx->hMsgQueue )
    {
        DEBUGMSG(ZONE_IOCTL|ZONE_ERROR, (_T("PIN_IOControl(%08x): NULL Handle provided for msgqueue\r\n"), this)) ;
        return dwError ;
    }   

    if ( false == m_pCamAdapter->IncrCInstances( m_ulPinId, this ) )
    {
        DEBUGMSG(ZONE_IOCTL|ZONE_ERROR, (_T("PIN_IOControl(%08x): Pin %d is already instantiated.\r\n"), this, m_ulPinId)) ;
        return dwError ;
    }

    //TODO : Check whether the client created msgqueue with enough buffersize and number of buffers.
    MSGQUEUEOPTIONS msgQueueOptions;
    msgQueueOptions.bReadAccess = FALSE; // we need write-access to msgqueue
    msgQueueOptions.dwSize      = sizeof(MSGQUEUEOPTIONS);

    if ( NULL == (m_hMsgQ = OpenMsgQueue( GetCallerProcess(),pCsPropStreamEx->hMsgQueue, &msgQueueOptions ) ) )
    {
        DEBUGMSG(ZONE_IOCTL|ZONE_ERROR, (_T("PIN_IOControl(%08x): Failed to open MsgQueue\r\n"), this)) ;
        m_pCamAdapter->DecrCInstances( m_ulPinId ) ;
        return dwError ;
    }

    return ERROR_SUCCESS ;
}

void CPinDevice :: SetState( CSSTATE CsState, CSSTATE *CsPrevState )
{
    if ( NULL != CsPrevState )
        *CsPrevState = m_CsState ;
    
    m_CsState = CsState ;

    DEBUGMSG(ZONE_IOCTL, (_T("PIN_IOControl(%08x): SetState into %d.\r\n"), this, m_CsState)) ;

    // Client set trigger event to run still image pin
    if (STILL == m_ulPinId && CSSTATE_RUN == CsState)
    {
        m_pCamAdapter->CaptureHWStillImage();
    }

    return ;
}

CSSTATE
CPinDevice :: GetState()
{
    return m_CsState;
}

DWORD CPinDevice::StreamBufferFill(
        PUCHAR pImage
        )
{
    CAMERA_DMA_BUFFER_INFO CamDmaBuffer;

    if ( !m_pCamAdapter->GetCurrentHWBuffer(m_ulPinId, &CamDmaBuffer) )
    {
        DEBUGMSG(ZONE_FUNCTION|ZONE_ERROR, (_T("StreamBufferFill: can't GetCurrentHWBuffer for %s pin.\r\n"), STILL == m_ulPinId ? L"Still" : L"Preview/Capture"));
        return 0;
    }

    // Mainstone II: copy date from h/w buffer to stream buffer or videoport
    memcpy( pImage, reinterpret_cast<void *>(CamDmaBuffer.VirtAddr), m_CsDataRangeVideo.VideoInfoHeader.bmiHeader.biSizeImage);
    
    DEBUGMSG(ZONE_FUNCTION, (_T("StreamBufferFill: (0x%x, %d bytes) for %s pin.\r\n"), pImage, m_CsDataRangeVideo.VideoInfoHeader.bmiHeader.biSizeImage,
                                                                                    STILL == m_ulPinId ? L"Still" : L"Preview/Capture")) ;

    return m_CsDataRangeVideo.VideoInfoHeader.bmiHeader.biSizeImage;
}

BOOL CPinDevice::InitMsgQueueDescriptor (PCS_MSGQUEUE_BUFFER pCsMsgQBuff, PCS_STREAM_DESCRIPTOR pCsStreamDesc,
                                         PVOID pMappedData, PVOID pUnmappedData, BOOL bBufferFill)
{
    PCSSTREAM_HEADER pCsStreamHeader = reinterpret_cast<PCSSTREAM_HEADER>(pCsStreamDesc);
    PCS_FRAME_INFO   pCsFrameInfo    = reinterpret_cast<PCS_FRAME_INFO>(pCsStreamHeader + 1);

    if(( pCsStreamHeader == NULL ) || ( pCsFrameInfo == NULL ))
    {
        DEBUGMSG(ZONE_FUNCTION|ZONE_ERROR, (_T("InitMsgQueueDescriptor(%08x): Invalid Stream Descriptor\r\n"), this));
        return false;
    }

    // The buffer fill function must use the pointer that's been mapped into this process.
    pCsStreamHeader->Data = pMappedData;

    EnterCriticalSection(&m_csStreamBuffer) ;

    pCsStreamHeader->DataUsed = StreamBufferFill((PUCHAR) pCsStreamHeader->Data);
   
    LeaveCriticalSection(&m_csStreamBuffer) ;

    pCsFrameInfo->PictureNumber = (LONGLONG)++m_ulPictureNumber;
    pCsFrameInfo->DropCount     = (LONGLONG)m_ulFramesDropped;


    // The message queue requires the original pointer value.
    pCsStreamHeader->Data = pUnmappedData;

    // Init the flags to zero
    pCsStreamHeader->OptionsFlags = 0;

    // Set the discontinuity flag if frames have been previously
    // dropped, and then reset our internal flag

    if ( true == m_fDiscontinuity ) 
    {
        pCsStreamHeader->OptionsFlags |= CSSTREAM_HEADER_OPTIONSF_DATADISCONTINUITY;
        m_fDiscontinuity = false;
    }

    DWORD msNow = GetTickCount();

    if (m_msStart == 0xFFFFFFFF)
    {
        m_msStart = msNow;
    }

    //
    // Return the timestamp for the frame
    //
    pCsStreamHeader->PresentationTime.Numerator   = 1;
    pCsStreamHeader->PresentationTime.Denominator = 1;
    pCsStreamHeader->Duration                     = m_RtAveTimePerFrame;
    DWORD prevPT = m_msLastPT;
    if (bBufferFill)
    {
        m_msLastPT = msNow - m_msStart;

        pCsStreamHeader->PresentationTime.Time        = (LONGLONG) m_msLastPT * 10000;  // presentation time stamp in 100s of ns

    }
    else
    {
        pCsStreamHeader->PresentationTime.Time        = 0;
    }

    DEBUGMSG(ZONE_FUNCTION, (_T("InitMsgQueueDescriptor: LastPT = %d, elapsed = %d\n"), m_msLastPT, m_msLastPT - prevPT));

    // clear the timestamp valid flags
    pCsStreamHeader->OptionsFlags &= ~( CSSTREAM_HEADER_OPTIONSF_TIMEVALID | CSSTREAM_HEADER_OPTIONSF_DURATIONVALID );

    // Every frame we generate is a key frame (aka SplicePoint)
    // Delta frames (B or P) should not set this flag

    pCsStreamHeader->OptionsFlags |= CSSTREAM_HEADER_OPTIONSF_SPLICEPOINT;

    pCsMsgQBuff->CsMsgQueueHeader.Size    = sizeof(CS_MSGQUEUE_HEADER);
    pCsMsgQBuff->CsMsgQueueHeader.Flags   = FLAG_MSGQ_FRAME_BUFFER;
    pCsMsgQBuff->CsMsgQueueHeader.Context = NULL;
    pCsMsgQBuff->pStreamDescriptor        = pCsStreamDesc;

    DEBUGMSG(ZONE_FUNCTION, (_T("InitMsgQueueDescriptor(%08x): Frame buf queued: %d (dropped %d), start %d, time %d\n"), 
        this,
        (LONG)pCsFrameInfo->PictureNumber, 
        (LONG)pCsFrameInfo->DropCount, 
        (LONG)m_msStart,
        (LONG)(pCsStreamHeader->PresentationTime.Time / 10000)));

    return TRUE;
   
}

void  CPinDevice::FlushBufferQueue()
{
    PCS_STREAM_DESCRIPTOR pCsStreamDesc = NULL;
    PVOID                 pMappedData   = NULL;
    PVOID                 pUnmappedData = NULL;
    CS_MSGQUEUE_BUFFER    CsMsgQBuff ;

    DWORD dwSavedPermissions = SetProcPermissions( (DWORD)-1 ) ;

    while (( true == RemoveBufferFromList( &pCsStreamDesc, &pMappedData, &pUnmappedData )) && ( NULL != pCsStreamDesc ) && ( m_hMsgQ != NULL ))
    {
        if (!InitMsgQueueDescriptor (&CsMsgQBuff, pCsStreamDesc, NULL, pUnmappedData, FALSE))
        {
            continue;
        }

        if ( false == WriteMsgQueue( m_hMsgQ, reinterpret_cast<LPVOID>(&CsMsgQBuff),  sizeof(CS_MSGQUEUE_BUFFER), PIN_TIMEOUT, 0 ) )
        {
            DEBUGMSG(ZONE_FUNCTION|ZONE_ERROR, (_T("PIN_Function(%08x): WriteMsgQueue returned false\r\n"), this));
        }
    }

    SetProcPermissions( dwSavedPermissions );

    return;
}

void CPinDevice :: HandlePinIO()
{
    DWORD event_id = -1;

    if ( CSSTATE_RUN != m_CsState ) 
    {
        DEBUGMSG(ZONE_FUNCTION, (_T("PIN_Function(%08x): Pin state isn't RUN - abort HandlePinIO\r\n"), this));
        return;
    }

    DWORD dwSavedPermissions = SetProcPermissions( (DWORD)-1 ) ;
    
    PCS_STREAM_DESCRIPTOR pCsStreamDesc = NULL;
    PVOID                 pMappedData   = NULL;
    PVOID                 pUnmappedData = NULL;
    CS_MSGQUEUE_BUFFER    CsMsgQBuff ;

    if ( false == RemoveBufferFromList( &pCsStreamDesc, &pMappedData, &pUnmappedData ) || NULL == pCsStreamDesc )
    {
        // We dropped a frame
        m_ulFramesDropped++;
        m_fDiscontinuity = true;
        SetProcPermissions( dwSavedPermissions  );
 
        DEBUGMSG(ZONE_FUNCTION, (_T("PIN_Function(%08x): RemoveBufferFromList failed - drop frame\r\n"), this));

        return;
    }

    if (!InitMsgQueueDescriptor (&CsMsgQBuff, pCsStreamDesc, pMappedData, pUnmappedData, TRUE))
    {
        SetProcPermissions( dwSavedPermissions  );
        return;
    }

    if ( NULL == m_hMsgQ )
    {
        DEBUGMSG(ZONE_FUNCTION|ZONE_ERROR, (_T("PIN_Function(%08x): MsgQueue is not opened\r\n"), this)) ;
        SetProcPermissions( dwSavedPermissions  ) ;
        return ;
    }

    if ( false == WriteMsgQueue( m_hMsgQ, reinterpret_cast<LPVOID>(&CsMsgQBuff),  sizeof(CS_MSGQUEUE_BUFFER), PIN_TIMEOUT, 0 ) )
    {
        DEBUGMSG(ZONE_FUNCTION|ZONE_ERROR, (_T("PIN_Function(%08x): WriteMsgQueue returned false\r\n"), this));
    }
  
    SetProcPermissions( dwSavedPermissions );
    return;
}


DWORD CPinDevice :: PinHandleConnectionRequests( 
        PCSPROPERTY pCsProp, 
        PUCHAR pOutBuf,                 // Unsafe, use with caution
        DWORD  OutBufLen, 
        PDWORD pdwBytesTransferred      // Unsafe, use with caution
        )
{
    DEBUGMSG( ZONE_IOCTL, (_T("PIN_IOControl(%08x): PinHandleConnectionRequests\r\n"), this));
    
    DWORD                           dwError                 = ERROR_INVALID_PARAMETER; 
    PCSALLOCATOR_FRAMING            pCsAllocatorFraming     = NULL;
    PCS_DATAFORMAT_VIDEOINFOHEADER  pCsDataFormatVidInfoHdr = NULL;
    PCS_DATAFORMAT_VIDEOINFOHEADER  pCsDataFormatVidInfoHdrCopy = NULL;
    
    if ( NULL == pCsProp )
    {
        return dwError;
    }
    
    __try
    {
        *pdwBytesTransferred = 0 ;
    }
    __except( EXCEPTION_EXECUTE_HANDLER )
    {

⌨️ 快捷键说明

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