text
stringlengths
6
1.35M
/* this ALWAYS GENERATED file contains the definitions for the interfaces */ /* File created by MIDL compiler version 8.01.0622 */ /* @@MIDL_FILE_HEADING( ) */ /* verify that the <rpcndr.h> version is high enough to compile this file*/ #ifndef __REQUIRED_RPCNDR_H_VERSION__ #define __REQUIRED_RPCNDR_H_VERSION__ 500 #endif /* verify that the <rpcsal.h> version is high enough to compile this file*/ #ifndef __REQUIRED_RPCSAL_H_VERSION__ #define __REQUIRED_RPCSAL_H_VERSION__ 100 #endif #include "rpc.h" #include "rpcndr.h" #ifndef __RPCNDR_H_VERSION__ #error this stub requires an updated version of <rpcndr.h> #endif /* __RPCNDR_H_VERSION__ */ #ifndef COM_NO_WINDOWS_H #include "windows.h" #include "ole2.h" #endif /*COM_NO_WINDOWS_H*/ #ifndef __openservice_h__ #define __openservice_h__ #if defined(_MSC_VER) && (_MSC_VER >= 1020) #pragma once #endif /* Forward Declarations */ #ifndef __IOpenServiceActivityInput_FWD_DEFINED__ #define __IOpenServiceActivityInput_FWD_DEFINED__ typedef interface IOpenServiceActivityInput IOpenServiceActivityInput; #endif /* __IOpenServiceActivityInput_FWD_DEFINED__ */ #ifndef __IOpenServiceActivityOutputContext_FWD_DEFINED__ #define __IOpenServiceActivityOutputContext_FWD_DEFINED__ typedef interface IOpenServiceActivityOutputContext IOpenServiceActivityOutputContext; #endif /* __IOpenServiceActivityOutputContext_FWD_DEFINED__ */ #ifndef __IOpenService_FWD_DEFINED__ #define __IOpenService_FWD_DEFINED__ typedef interface IOpenService IOpenService; #endif /* __IOpenService_FWD_DEFINED__ */ #ifndef __IOpenServiceManager_FWD_DEFINED__ #define __IOpenServiceManager_FWD_DEFINED__ typedef interface IOpenServiceManager IOpenServiceManager; #endif /* __IOpenServiceManager_FWD_DEFINED__ */ #ifndef __OpenServiceManager_FWD_DEFINED__ #define __OpenServiceManager_FWD_DEFINED__ #ifdef __cplusplus typedef class OpenServiceManager OpenServiceManager; #else typedef struct OpenServiceManager OpenServiceManager; #endif /* __cplusplus */ #endif /* __OpenServiceManager_FWD_DEFINED__ */ #ifndef __OpenServiceActivityManager_FWD_DEFINED__ #define __OpenServiceActivityManager_FWD_DEFINED__ #ifdef __cplusplus typedef class OpenServiceActivityManager OpenServiceActivityManager; #else typedef struct OpenServiceActivityManager OpenServiceActivityManager; #endif /* __cplusplus */ #endif /* __OpenServiceActivityManager_FWD_DEFINED__ */ #ifndef __IOpenServiceActivity_FWD_DEFINED__ #define __IOpenServiceActivity_FWD_DEFINED__ typedef interface IOpenServiceActivity IOpenServiceActivity; #endif /* __IOpenServiceActivity_FWD_DEFINED__ */ #ifndef __IEnumOpenServiceActivity_FWD_DEFINED__ #define __IEnumOpenServiceActivity_FWD_DEFINED__ typedef interface IEnumOpenServiceActivity IEnumOpenServiceActivity; #endif /* __IEnumOpenServiceActivity_FWD_DEFINED__ */ #ifndef __IOpenServiceActivityCategory_FWD_DEFINED__ #define __IOpenServiceActivityCategory_FWD_DEFINED__ typedef interface IOpenServiceActivityCategory IOpenServiceActivityCategory; #endif /* __IOpenServiceActivityCategory_FWD_DEFINED__ */ #ifndef __IEnumOpenServiceActivityCategory_FWD_DEFINED__ #define __IEnumOpenServiceActivityCategory_FWD_DEFINED__ typedef interface IEnumOpenServiceActivityCategory IEnumOpenServiceActivityCategory; #endif /* __IEnumOpenServiceActivityCategory_FWD_DEFINED__ */ #ifndef __IOpenServiceActivityManager_FWD_DEFINED__ #define __IOpenServiceActivityManager_FWD_DEFINED__ typedef interface IOpenServiceActivityManager IOpenServiceActivityManager; #endif /* __IOpenServiceActivityManager_FWD_DEFINED__ */ /* header files for imported files */ #include "objidl.h" #include "oleidl.h" #include "mshtml.h" #include "exdisp.h" #ifdef __cplusplus extern "C"{ #endif /* interface __MIDL_itf_openservice_0000_0000 */ /* [local] */ //=--------------------------------------------------------------------------= // openservice.h //=--------------------------------------------------------------------------= // (C) Copyright Microsoft Corporation. All Rights Reserved. // // THIS CODE AND INFORMATION IS PROVIDED "AS IS" WITHOUT WARRANTY OF // ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING BUT NOT LIMITED TO // THE IMPLIED WARRANTIES OF MERCHANTABILITY AND/OR FITNESS FOR A // PARTICULAR PURPOSE. //=--------------------------------------------------------------------------= #include <winapifamily.h> #pragma region Desktop Family #if WINAPI_FAMILY_PARTITION(WINAPI_PARTITION_DESKTOP) typedef enum OpenServiceErrors { OS_E_NOTFOUND = 0x80030002, OS_E_NOTSUPPORTED = 0x80004021, OS_E_CANCELLED = 0x80002ef1, OS_E_GPDISABLED = 0xc00d0bdc } OpenServiceErrors; typedef enum OpenServiceActivityContentType { ActivityContentNone = -1, ActivityContentDocument = ( ActivityContentNone + 1 ) , ActivityContentSelection = ( ActivityContentDocument + 1 ) , ActivityContentLink = ( ActivityContentSelection + 1 ) , ActivityContentCount = ( ActivityContentLink + 1 ) } OpenServiceActivityContentType; extern RPC_IF_HANDLE __MIDL_itf_openservice_0000_0000_v0_0_c_ifspec; extern RPC_IF_HANDLE __MIDL_itf_openservice_0000_0000_v0_0_s_ifspec; #ifndef __IOpenServiceActivityInput_INTERFACE_DEFINED__ #define __IOpenServiceActivityInput_INTERFACE_DEFINED__ /* interface IOpenServiceActivityInput */ /* [unique][uuid][object] */ EXTERN_C const IID IID_IOpenServiceActivityInput; #if defined(__cplusplus) && !defined(CINTERFACE) MIDL_INTERFACE("75cb4db9-6da0-4da3-83ce-422b6a433346") IOpenServiceActivityInput : public IUnknown { public: virtual HRESULT STDMETHODCALLTYPE GetVariable( /* [in] */ __RPC__in LPCWSTR pwzVariableName, /* [unique][in] */ __RPC__in_opt LPCWSTR pwzVariableType, /* [out] */ __RPC__deref_out_opt BSTR *pbstrVariableContent) = 0; virtual HRESULT STDMETHODCALLTYPE HasVariable( /* [in] */ __RPC__in LPCWSTR pwzVariableName, /* [unique][in] */ __RPC__in_opt LPCWSTR pwzVariableType, /* [out] */ __RPC__out BOOL *pfHasVariable) = 0; virtual HRESULT STDMETHODCALLTYPE GetType( /* [out] */ __RPC__out OpenServiceActivityContentType *pType) = 0; }; #else /* C style interface */ typedef struct IOpenServiceActivityInputVtbl { BEGIN_INTERFACE HRESULT ( STDMETHODCALLTYPE *QueryInterface )( __RPC__in IOpenServiceActivityInput * This, /* [in] */ __RPC__in REFIID riid, /* [annotation][iid_is][out] */ _COM_Outptr_ void **ppvObject); ULONG ( STDMETHODCALLTYPE *AddRef )( __RPC__in IOpenServiceActivityInput * This); ULONG ( STDMETHODCALLTYPE *Release )( __RPC__in IOpenServiceActivityInput * This); HRESULT ( STDMETHODCALLTYPE *GetVariable )( __RPC__in IOpenServiceActivityInput * This, /* [in] */ __RPC__in LPCWSTR pwzVariableName, /* [unique][in] */ __RPC__in_opt LPCWSTR pwzVariableType, /* [out] */ __RPC__deref_out_opt BSTR *pbstrVariableContent); HRESULT ( STDMETHODCALLTYPE *HasVariable )( __RPC__in IOpenServiceActivityInput * This, /* [in] */ __RPC__in LPCWSTR pwzVariableName, /* [unique][in] */ __RPC__in_opt LPCWSTR pwzVariableType, /* [out] */ __RPC__out BOOL *pfHasVariable); HRESULT ( STDMETHODCALLTYPE *GetType )( __RPC__in IOpenServiceActivityInput * This, /* [out] */ __RPC__out OpenServiceActivityContentType *pType); END_INTERFACE } IOpenServiceActivityInputVtbl; interface IOpenServiceActivityInput { CONST_VTBL struct IOpenServiceActivityInputVtbl *lpVtbl; }; #ifdef COBJMACROS #define IOpenServiceActivityInput_QueryInterface(This,riid,ppvObject) \ ( (This)->lpVtbl -> QueryInterface(This,riid,ppvObject) ) #define IOpenServiceActivityInput_AddRef(This) \ ( (This)->lpVtbl -> AddRef(This) ) #define IOpenServiceActivityInput_Release(This) \ ( (This)->lpVtbl -> Release(This) ) #define IOpenServiceActivityInput_GetVariable(This,pwzVariableName,pwzVariableType,pbstrVariableContent) \ ( (This)->lpVtbl -> GetVariable(This,pwzVariableName,pwzVariableType,pbstrVariableContent) ) #define IOpenServiceActivityInput_HasVariable(This,pwzVariableName,pwzVariableType,pfHasVariable) \ ( (This)->lpVtbl -> HasVariable(This,pwzVariableName,pwzVariableType,pfHasVariable) ) #define IOpenServiceActivityInput_GetType(This,pType) \ ( (This)->lpVtbl -> GetType(This,pType) ) #endif /* COBJMACROS */ #endif /* C style interface */ #endif /* __IOpenServiceActivityInput_INTERFACE_DEFINED__ */ #ifndef __IOpenServiceActivityOutputContext_INTERFACE_DEFINED__ #define __IOpenServiceActivityOutputContext_INTERFACE_DEFINED__ /* interface IOpenServiceActivityOutputContext */ /* [unique][uuid][object] */ EXTERN_C const IID IID_IOpenServiceActivityOutputContext; #if defined(__cplusplus) && !defined(CINTERFACE) MIDL_INTERFACE("e289deab-f709-49a9-b99e-282364074571") IOpenServiceActivityOutputContext : public IUnknown { public: virtual HRESULT STDMETHODCALLTYPE Navigate( /* [in] */ __RPC__in LPCWSTR pwzUri, /* [unique][in] */ __RPC__in_opt LPCWSTR pwzMethod, /* [unique][in] */ __RPC__in_opt LPCWSTR pwzHeaders, /* [unique][in] */ __RPC__in_opt IStream *pPostData) = 0; virtual HRESULT STDMETHODCALLTYPE CanNavigate( /* [in] */ __RPC__in LPCWSTR pwzUri, /* [unique][in] */ __RPC__in_opt LPCWSTR pwzMethod, /* [unique][in] */ __RPC__in_opt LPCWSTR pwzHeaders, /* [unique][in] */ __RPC__in_opt IStream *pPostData, /* [out] */ __RPC__out BOOL *pfCanNavigate) = 0; }; #else /* C style interface */ typedef struct IOpenServiceActivityOutputContextVtbl { BEGIN_INTERFACE HRESULT ( STDMETHODCALLTYPE *QueryInterface )( __RPC__in IOpenServiceActivityOutputContext * This, /* [in] */ __RPC__in REFIID riid, /* [annotation][iid_is][out] */ _COM_Outptr_ void **ppvObject); ULONG ( STDMETHODCALLTYPE *AddRef )( __RPC__in IOpenServiceActivityOutputContext * This); ULONG ( STDMETHODCALLTYPE *Release )( __RPC__in IOpenServiceActivityOutputContext * This); HRESULT ( STDMETHODCALLTYPE *Navigate )( __RPC__in IOpenServiceActivityOutputContext * This, /* [in] */ __RPC__in LPCWSTR pwzUri, /* [unique][in] */ __RPC__in_opt LPCWSTR pwzMethod, /* [unique][in] */ __RPC__in_opt LPCWSTR pwzHeaders, /* [unique][in] */ __RPC__in_opt IStream *pPostData); HRESULT ( STDMETHODCALLTYPE *CanNavigate )( __RPC__in IOpenServiceActivityOutputContext * This, /* [in] */ __RPC__in LPCWSTR pwzUri, /* [unique][in] */ __RPC__in_opt LPCWSTR pwzMethod, /* [unique][in] */ __RPC__in_opt LPCWSTR pwzHeaders, /* [unique][in] */ __RPC__in_opt IStream *pPostData, /* [out] */ __RPC__out BOOL *pfCanNavigate); END_INTERFACE } IOpenServiceActivityOutputContextVtbl; interface IOpenServiceActivityOutputContext { CONST_VTBL struct IOpenServiceActivityOutputContextVtbl *lpVtbl; }; #ifdef COBJMACROS #define IOpenServiceActivityOutputContext_QueryInterface(This,riid,ppvObject) \ ( (This)->lpVtbl -> QueryInterface(This,riid,ppvObject) ) #define IOpenServiceActivityOutputContext_AddRef(This) \ ( (This)->lpVtbl -> AddRef(This) ) #define IOpenServiceActivityOutputContext_Release(This) \ ( (This)->lpVtbl -> Release(This) ) #define IOpenServiceActivityOutputContext_Navigate(This,pwzUri,pwzMethod,pwzHeaders,pPostData) \ ( (This)->lpVtbl -> Navigate(This,pwzUri,pwzMethod,pwzHeaders,pPostData) ) #define IOpenServiceActivityOutputContext_CanNavigate(This,pwzUri,pwzMethod,pwzHeaders,pPostData,pfCanNavigate) \ ( (This)->lpVtbl -> CanNavigate(This,pwzUri,pwzMethod,pwzHeaders,pPostData,pfCanNavigate) ) #endif /* COBJMACROS */ #endif /* C style interface */ #endif /* __IOpenServiceActivityOutputContext_INTERFACE_DEFINED__ */ #ifndef __IOpenService_INTERFACE_DEFINED__ #define __IOpenService_INTERFACE_DEFINED__ /* interface IOpenService */ /* [unique][uuid][object] */ EXTERN_C const IID IID_IOpenService; #if defined(__cplusplus) && !defined(CINTERFACE) MIDL_INTERFACE("C2952ED1-6A89-4606-925F-1ED8B4BE0630") IOpenService : public IUnknown { public: virtual HRESULT STDMETHODCALLTYPE IsDefault( /* [out] */ __RPC__out BOOL *pfIsDefault) = 0; virtual HRESULT STDMETHODCALLTYPE SetDefault( /* [in] */ BOOL fDefault, /* [in] */ __RPC__in HWND hwnd) = 0; virtual HRESULT STDMETHODCALLTYPE GetID( /* [out] */ __RPC__deref_out_opt BSTR *pbstrID) = 0; }; #else /* C style interface */ typedef struct IOpenServiceVtbl { BEGIN_INTERFACE HRESULT ( STDMETHODCALLTYPE *QueryInterface )( __RPC__in IOpenService * This, /* [in] */ __RPC__in REFIID riid, /* [annotation][iid_is][out] */ _COM_Outptr_ void **ppvObject); ULONG ( STDMETHODCALLTYPE *AddRef )( __RPC__in IOpenService * This); ULONG ( STDMETHODCALLTYPE *Release )( __RPC__in IOpenService * This); HRESULT ( STDMETHODCALLTYPE *IsDefault )( __RPC__in IOpenService * This, /* [out] */ __RPC__out BOOL *pfIsDefault); HRESULT ( STDMETHODCALLTYPE *SetDefault )( __RPC__in IOpenService * This, /* [in] */ BOOL fDefault, /* [in] */ __RPC__in HWND hwnd); HRESULT ( STDMETHODCALLTYPE *GetID )( __RPC__in IOpenService * This, /* [out] */ __RPC__deref_out_opt BSTR *pbstrID); END_INTERFACE } IOpenServiceVtbl; interface IOpenService { CONST_VTBL struct IOpenServiceVtbl *lpVtbl; }; #ifdef COBJMACROS #define IOpenService_QueryInterface(This,riid,ppvObject) \ ( (This)->lpVtbl -> QueryInterface(This,riid,ppvObject) ) #define IOpenService_AddRef(This) \ ( (This)->lpVtbl -> AddRef(This) ) #define IOpenService_Release(This) \ ( (This)->lpVtbl -> Release(This) ) #define IOpenService_IsDefault(This,pfIsDefault) \ ( (This)->lpVtbl -> IsDefault(This,pfIsDefault) ) #define IOpenService_SetDefault(This,fDefault,hwnd) \ ( (This)->lpVtbl -> SetDefault(This,fDefault,hwnd) ) #define IOpenService_GetID(This,pbstrID) \ ( (This)->lpVtbl -> GetID(This,pbstrID) ) #endif /* COBJMACROS */ #endif /* C style interface */ #endif /* __IOpenService_INTERFACE_DEFINED__ */ #ifndef __IOpenServiceManager_INTERFACE_DEFINED__ #define __IOpenServiceManager_INTERFACE_DEFINED__ /* interface IOpenServiceManager */ /* [unique][uuid][object] */ EXTERN_C const IID IID_IOpenServiceManager; #if defined(__cplusplus) && !defined(CINTERFACE) MIDL_INTERFACE("5664125f-4e10-4e90-98e4-e4513d955a14") IOpenServiceManager : public IUnknown { public: virtual HRESULT STDMETHODCALLTYPE InstallService( /* [in] */ __RPC__in LPCWSTR pwzServiceUrl, /* [out] */ __RPC__deref_out_opt IOpenService **ppService) = 0; virtual HRESULT STDMETHODCALLTYPE UninstallService( /* [in] */ __RPC__in_opt IOpenService *pService) = 0; virtual HRESULT STDMETHODCALLTYPE GetServiceByID( /* [in] */ __RPC__in LPCWSTR pwzID, /* [out] */ __RPC__deref_out_opt IOpenService **ppService) = 0; }; #else /* C style interface */ typedef struct IOpenServiceManagerVtbl { BEGIN_INTERFACE HRESULT ( STDMETHODCALLTYPE *QueryInterface )( __RPC__in IOpenServiceManager * This, /* [in] */ __RPC__in REFIID riid, /* [annotation][iid_is][out] */ _COM_Outptr_ void **ppvObject); ULONG ( STDMETHODCALLTYPE *AddRef )( __RPC__in IOpenServiceManager * This); ULONG ( STDMETHODCALLTYPE *Release )( __RPC__in IOpenServiceManager * This); HRESULT ( STDMETHODCALLTYPE *InstallService )( __RPC__in IOpenServiceManager * This, /* [in] */ __RPC__in LPCWSTR pwzServiceUrl, /* [out] */ __RPC__deref_out_opt IOpenService **ppService); HRESULT ( STDMETHODCALLTYPE *UninstallService )( __RPC__in IOpenServiceManager * This, /* [in] */ __RPC__in_opt IOpenService *pService); HRESULT ( STDMETHODCALLTYPE *GetServiceByID )( __RPC__in IOpenServiceManager * This, /* [in] */ __RPC__in LPCWSTR pwzID, /* [out] */ __RPC__deref_out_opt IOpenService **ppService); END_INTERFACE } IOpenServiceManagerVtbl; interface IOpenServiceManager { CONST_VTBL struct IOpenServiceManagerVtbl *lpVtbl; }; #ifdef COBJMACROS #define IOpenServiceManager_QueryInterface(This,riid,ppvObject) \ ( (This)->lpVtbl -> QueryInterface(This,riid,ppvObject) ) #define IOpenServiceManager_AddRef(This) \ ( (This)->lpVtbl -> AddRef(This) ) #define IOpenServiceManager_Release(This) \ ( (This)->lpVtbl -> Release(This) ) #define IOpenServiceManager_InstallService(This,pwzServiceUrl,ppService) \ ( (This)->lpVtbl -> InstallService(This,pwzServiceUrl,ppService) ) #define IOpenServiceManager_UninstallService(This,pService) \ ( (This)->lpVtbl -> UninstallService(This,pService) ) #define IOpenServiceManager_GetServiceByID(This,pwzID,ppService) \ ( (This)->lpVtbl -> GetServiceByID(This,pwzID,ppService) ) #endif /* COBJMACROS */ #endif /* C style interface */ #endif /* __IOpenServiceManager_INTERFACE_DEFINED__ */ #ifndef __IEOpenServiceObjects_LIBRARY_DEFINED__ #define __IEOpenServiceObjects_LIBRARY_DEFINED__ /* library IEOpenServiceObjects */ /* [uuid] */ EXTERN_C const IID LIBID_IEOpenServiceObjects; EXTERN_C const CLSID CLSID_OpenServiceManager; #ifdef __cplusplus class DECLSPEC_UUID("098870b6-39ea-480b-b8b5-dd0167c4db59") OpenServiceManager; #endif EXTERN_C const CLSID CLSID_OpenServiceActivityManager; #ifdef __cplusplus class DECLSPEC_UUID("c5efd803-50f8-43cd-9ab8-aafc1394c9e0") OpenServiceActivityManager; #endif #endif /* __IEOpenServiceObjects_LIBRARY_DEFINED__ */ #ifndef __IOpenServiceActivity_INTERFACE_DEFINED__ #define __IOpenServiceActivity_INTERFACE_DEFINED__ /* interface IOpenServiceActivity */ /* [unique][uuid][object] */ EXTERN_C const IID IID_IOpenServiceActivity; #if defined(__cplusplus) && !defined(CINTERFACE) MIDL_INTERFACE("13645c88-221a-4905-8ed1-4f5112cfc108") IOpenServiceActivity : public IOpenService { public: virtual HRESULT STDMETHODCALLTYPE Execute( /* [in] */ __RPC__in_opt IOpenServiceActivityInput *pInput, /* [in] */ __RPC__in_opt IOpenServiceActivityOutputContext *pOutput) = 0; virtual HRESULT STDMETHODCALLTYPE CanExecute( /* [in] */ __RPC__in_opt IOpenServiceActivityInput *pInput, /* [in] */ __RPC__in_opt IOpenServiceActivityOutputContext *pOutput, /* [out] */ __RPC__out BOOL *pfCanExecute) = 0; virtual HRESULT STDMETHODCALLTYPE CanExecuteType( /* [in] */ OpenServiceActivityContentType type, /* [out] */ __RPC__out BOOL *pfCanExecute) = 0; virtual HRESULT STDMETHODCALLTYPE Preview( /* [in] */ __RPC__in_opt IOpenServiceActivityInput *pInput, /* [in] */ __RPC__in_opt IOpenServiceActivityOutputContext *pOutput) = 0; virtual HRESULT STDMETHODCALLTYPE CanPreview( /* [in] */ __RPC__in_opt IOpenServiceActivityInput *pInput, /* [in] */ __RPC__in_opt IOpenServiceActivityOutputContext *pOutput, /* [out] */ __RPC__out BOOL *pfCanPreview) = 0; virtual HRESULT STDMETHODCALLTYPE CanPreviewType( /* [in] */ OpenServiceActivityContentType type, /* [out] */ __RPC__out BOOL *pfCanPreview) = 0; virtual HRESULT STDMETHODCALLTYPE GetStatusText( /* [in] */ __RPC__in_opt IOpenServiceActivityInput *pInput, /* [out] */ __RPC__deref_out_opt BSTR *pbstrStatusText) = 0; virtual HRESULT STDMETHODCALLTYPE GetHomepageUrl( /* [out] */ __RPC__deref_out_opt BSTR *pbstrHomepageUrl) = 0; virtual HRESULT STDMETHODCALLTYPE GetDisplayName( /* [out] */ __RPC__deref_out_opt BSTR *pbstrDisplayName) = 0; virtual HRESULT STDMETHODCALLTYPE GetDescription( /* [out] */ __RPC__deref_out_opt BSTR *pbstrDescription) = 0; virtual HRESULT STDMETHODCALLTYPE GetCategoryName( /* [out] */ __RPC__deref_out_opt BSTR *pbstrCategoryName) = 0; virtual HRESULT STDMETHODCALLTYPE GetIconPath( /* [out] */ __RPC__deref_out_opt BSTR *pbstrIconPath) = 0; virtual HRESULT STDMETHODCALLTYPE GetIcon( /* [in] */ BOOL fSmallIcon, /* [out] */ __RPC__deref_out_opt HICON *phIcon) = 0; virtual HRESULT STDMETHODCALLTYPE GetDescriptionFilePath( /* [out] */ __RPC__deref_out_opt BSTR *pbstrXmlPath) = 0; virtual HRESULT STDMETHODCALLTYPE GetDownloadUrl( /* [out] */ __RPC__deref_out_opt BSTR *pbstrXmlUri) = 0; virtual HRESULT STDMETHODCALLTYPE GetInstallUrl( /* [out] */ __RPC__deref_out_opt BSTR *pbstrInstallUri) = 0; virtual HRESULT STDMETHODCALLTYPE IsEnabled( /* [out] */ __RPC__out BOOL *pfIsEnabled) = 0; virtual HRESULT STDMETHODCALLTYPE SetEnabled( /* [in] */ BOOL fEnable) = 0; }; #else /* C style interface */ typedef struct IOpenServiceActivityVtbl { BEGIN_INTERFACE HRESULT ( STDMETHODCALLTYPE *QueryInterface )( __RPC__in IOpenServiceActivity * This, /* [in] */ __RPC__in REFIID riid, /* [annotation][iid_is][out] */ _COM_Outptr_ void **ppvObject); ULONG ( STDMETHODCALLTYPE *AddRef )( __RPC__in IOpenServiceActivity * This); ULONG ( STDMETHODCALLTYPE *Release )( __RPC__in IOpenServiceActivity * This); HRESULT ( STDMETHODCALLTYPE *IsDefault )( __RPC__in IOpenServiceActivity * This, /* [out] */ __RPC__out BOOL *pfIsDefault); HRESULT ( STDMETHODCALLTYPE *SetDefault )( __RPC__in IOpenServiceActivity * This, /* [in] */ BOOL fDefault, /* [in] */ __RPC__in HWND hwnd); HRESULT ( STDMETHODCALLTYPE *GetID )( __RPC__in IOpenServiceActivity * This, /* [out] */ __RPC__deref_out_opt BSTR *pbstrID); HRESULT ( STDMETHODCALLTYPE *Execute )( __RPC__in IOpenServiceActivity * This, /* [in] */ __RPC__in_opt IOpenServiceActivityInput *pInput, /* [in] */ __RPC__in_opt IOpenServiceActivityOutputContext *pOutput); HRESULT ( STDMETHODCALLTYPE *CanExecute )( __RPC__in IOpenServiceActivity * This, /* [in] */ __RPC__in_opt IOpenServiceActivityInput *pInput, /* [in] */ __RPC__in_opt IOpenServiceActivityOutputContext *pOutput, /* [out] */ __RPC__out BOOL *pfCanExecute); HRESULT ( STDMETHODCALLTYPE *CanExecuteType )( __RPC__in IOpenServiceActivity * This, /* [in] */ OpenServiceActivityContentType type, /* [out] */ __RPC__out BOOL *pfCanExecute); HRESULT ( STDMETHODCALLTYPE *Preview )( __RPC__in IOpenServiceActivity * This, /* [in] */ __RPC__in_opt IOpenServiceActivityInput *pInput, /* [in] */ __RPC__in_opt IOpenServiceActivityOutputContext *pOutput); HRESULT ( STDMETHODCALLTYPE *CanPreview )( __RPC__in IOpenServiceActivity * This, /* [in] */ __RPC__in_opt IOpenServiceActivityInput *pInput, /* [in] */ __RPC__in_opt IOpenServiceActivityOutputContext *pOutput, /* [out] */ __RPC__out BOOL *pfCanPreview); HRESULT ( STDMETHODCALLTYPE *CanPreviewType )( __RPC__in IOpenServiceActivity * This, /* [in] */ OpenServiceActivityContentType type, /* [out] */ __RPC__out BOOL *pfCanPreview); HRESULT ( STDMETHODCALLTYPE *GetStatusText )( __RPC__in IOpenServiceActivity * This, /* [in] */ __RPC__in_opt IOpenServiceActivityInput *pInput, /* [out] */ __RPC__deref_out_opt BSTR *pbstrStatusText); HRESULT ( STDMETHODCALLTYPE *GetHomepageUrl )( __RPC__in IOpenServiceActivity * This, /* [out] */ __RPC__deref_out_opt BSTR *pbstrHomepageUrl); HRESULT ( STDMETHODCALLTYPE *GetDisplayName )( __RPC__in IOpenServiceActivity * This, /* [out] */ __RPC__deref_out_opt BSTR *pbstrDisplayName); HRESULT ( STDMETHODCALLTYPE *GetDescription )( __RPC__in IOpenServiceActivity * This, /* [out] */ __RPC__deref_out_opt BSTR *pbstrDescription); HRESULT ( STDMETHODCALLTYPE *GetCategoryName )( __RPC__in IOpenServiceActivity * This, /* [out] */ __RPC__deref_out_opt BSTR *pbstrCategoryName); HRESULT ( STDMETHODCALLTYPE *GetIconPath )( __RPC__in IOpenServiceActivity * This, /* [out] */ __RPC__deref_out_opt BSTR *pbstrIconPath); HRESULT ( STDMETHODCALLTYPE *GetIcon )( __RPC__in IOpenServiceActivity * This, /* [in] */ BOOL fSmallIcon, /* [out] */ __RPC__deref_out_opt HICON *phIcon); HRESULT ( STDMETHODCALLTYPE *GetDescriptionFilePath )( __RPC__in IOpenServiceActivity * This, /* [out] */ __RPC__deref_out_opt BSTR *pbstrXmlPath); HRESULT ( STDMETHODCALLTYPE *GetDownloadUrl )( __RPC__in IOpenServiceActivity * This, /* [out] */ __RPC__deref_out_opt BSTR *pbstrXmlUri); HRESULT ( STDMETHODCALLTYPE *GetInstallUrl )( __RPC__in IOpenServiceActivity * This, /* [out] */ __RPC__deref_out_opt BSTR *pbstrInstallUri); HRESULT ( STDMETHODCALLTYPE *IsEnabled )( __RPC__in IOpenServiceActivity * This, /* [out] */ __RPC__out BOOL *pfIsEnabled); HRESULT ( STDMETHODCALLTYPE *SetEnabled )( __RPC__in IOpenServiceActivity * This, /* [in] */ BOOL fEnable); END_INTERFACE } IOpenServiceActivityVtbl; interface IOpenServiceActivity { CONST_VTBL struct IOpenServiceActivityVtbl *lpVtbl; }; #ifdef COBJMACROS #define IOpenServiceActivity_QueryInterface(This,riid,ppvObject) \ ( (This)->lpVtbl -> QueryInterface(This,riid,ppvObject) ) #define IOpenServiceActivity_AddRef(This) \ ( (This)->lpVtbl -> AddRef(This) ) #define IOpenServiceActivity_Release(This) \ ( (This)->lpVtbl -> Release(This) ) #define IOpenServiceActivity_IsDefault(This,pfIsDefault) \ ( (This)->lpVtbl -> IsDefault(This,pfIsDefault) ) #define IOpenServiceActivity_SetDefault(This,fDefault,hwnd) \ ( (This)->lpVtbl -> SetDefault(This,fDefault,hwnd) ) #define IOpenServiceActivity_GetID(This,pbstrID) \ ( (This)->lpVtbl -> GetID(This,pbstrID) ) #define IOpenServiceActivity_Execute(This,pInput,pOutput) \ ( (This)->lpVtbl -> Execute(This,pInput,pOutput) ) #define IOpenServiceActivity_CanExecute(This,pInput,pOutput,pfCanExecute) \ ( (This)->lpVtbl -> CanExecute(This,pInput,pOutput,pfCanExecute) ) #define IOpenServiceActivity_CanExecuteType(This,type,pfCanExecute) \ ( (This)->lpVtbl -> CanExecuteType(This,type,pfCanExecute) ) #define IOpenServiceActivity_Preview(This,pInput,pOutput) \ ( (This)->lpVtbl -> Preview(This,pInput,pOutput) ) #define IOpenServiceActivity_CanPreview(This,pInput,pOutput,pfCanPreview) \ ( (This)->lpVtbl -> CanPreview(This,pInput,pOutput,pfCanPreview) ) #define IOpenServiceActivity_CanPreviewType(This,type,pfCanPreview) \ ( (This)->lpVtbl -> CanPreviewType(This,type,pfCanPreview) ) #define IOpenServiceActivity_GetStatusText(This,pInput,pbstrStatusText) \ ( (This)->lpVtbl -> GetStatusText(This,pInput,pbstrStatusText) ) #define IOpenServiceActivity_GetHomepageUrl(This,pbstrHomepageUrl) \ ( (This)->lpVtbl -> GetHomepageUrl(This,pbstrHomepageUrl) ) #define IOpenServiceActivity_GetDisplayName(This,pbstrDisplayName) \ ( (This)->lpVtbl -> GetDisplayName(This,pbstrDisplayName) ) #define IOpenServiceActivity_GetDescription(This,pbstrDescription) \ ( (This)->lpVtbl -> GetDescription(This,pbstrDescription) ) #define IOpenServiceActivity_GetCategoryName(This,pbstrCategoryName) \ ( (This)->lpVtbl -> GetCategoryName(This,pbstrCategoryName) ) #define IOpenServiceActivity_GetIconPath(This,pbstrIconPath) \ ( (This)->lpVtbl -> GetIconPath(This,pbstrIconPath) ) #define IOpenServiceActivity_GetIcon(This,fSmallIcon,phIcon) \ ( (This)->lpVtbl -> GetIcon(This,fSmallIcon,phIcon) ) #define IOpenServiceActivity_GetDescriptionFilePath(This,pbstrXmlPath) \ ( (This)->lpVtbl -> GetDescriptionFilePath(This,pbstrXmlPath) ) #define IOpenServiceActivity_GetDownloadUrl(This,pbstrXmlUri) \ ( (This)->lpVtbl -> GetDownloadUrl(This,pbstrXmlUri) ) #define IOpenServiceActivity_GetInstallUrl(This,pbstrInstallUri) \ ( (This)->lpVtbl -> GetInstallUrl(This,pbstrInstallUri) ) #define IOpenServiceActivity_IsEnabled(This,pfIsEnabled) \ ( (This)->lpVtbl -> IsEnabled(This,pfIsEnabled) ) #define IOpenServiceActivity_SetEnabled(This,fEnable) \ ( (This)->lpVtbl -> SetEnabled(This,fEnable) ) #endif /* COBJMACROS */ #endif /* C style interface */ #endif /* __IOpenServiceActivity_INTERFACE_DEFINED__ */ #ifndef __IEnumOpenServiceActivity_INTERFACE_DEFINED__ #define __IEnumOpenServiceActivity_INTERFACE_DEFINED__ /* interface IEnumOpenServiceActivity */ /* [unique][uuid][object] */ typedef IOpenServiceActivity *EnumActivityType; EXTERN_C const IID IID_IEnumOpenServiceActivity; #if defined(__cplusplus) && !defined(CINTERFACE) MIDL_INTERFACE("a436d7d2-17c3-4ef4-a1e8-5c86faff26c0") IEnumOpenServiceActivity : public IUnknown { public: virtual HRESULT STDMETHODCALLTYPE Next( /* [in] */ ULONG celt, /* [length_is][size_is][out] */ __RPC__out_ecount_part(celt, *pceltFetched) EnumActivityType *rgelt, /* [out] */ __RPC__out ULONG *pceltFetched) = 0; virtual HRESULT STDMETHODCALLTYPE Skip( /* [in] */ ULONG celt) = 0; virtual HRESULT STDMETHODCALLTYPE Reset( void) = 0; virtual HRESULT STDMETHODCALLTYPE Clone( /* [out] */ __RPC__deref_out_opt IEnumOpenServiceActivity **ppenum) = 0; }; #else /* C style interface */ typedef struct IEnumOpenServiceActivityVtbl { BEGIN_INTERFACE HRESULT ( STDMETHODCALLTYPE *QueryInterface )( __RPC__in IEnumOpenServiceActivity * This, /* [in] */ __RPC__in REFIID riid, /* [annotation][iid_is][out] */ _COM_Outptr_ void **ppvObject); ULONG ( STDMETHODCALLTYPE *AddRef )( __RPC__in IEnumOpenServiceActivity * This); ULONG ( STDMETHODCALLTYPE *Release )( __RPC__in IEnumOpenServiceActivity * This); HRESULT ( STDMETHODCALLTYPE *Next )( __RPC__in IEnumOpenServiceActivity * This, /* [in] */ ULONG celt, /* [length_is][size_is][out] */ __RPC__out_ecount_part(celt, *pceltFetched) EnumActivityType *rgelt, /* [out] */ __RPC__out ULONG *pceltFetched); HRESULT ( STDMETHODCALLTYPE *Skip )( __RPC__in IEnumOpenServiceActivity * This, /* [in] */ ULONG celt); HRESULT ( STDMETHODCALLTYPE *Reset )( __RPC__in IEnumOpenServiceActivity * This); HRESULT ( STDMETHODCALLTYPE *Clone )( __RPC__in IEnumOpenServiceActivity * This, /* [out] */ __RPC__deref_out_opt IEnumOpenServiceActivity **ppenum); END_INTERFACE } IEnumOpenServiceActivityVtbl; interface IEnumOpenServiceActivity { CONST_VTBL struct IEnumOpenServiceActivityVtbl *lpVtbl; }; #ifdef COBJMACROS #define IEnumOpenServiceActivity_QueryInterface(This,riid,ppvObject) \ ( (This)->lpVtbl -> QueryInterface(This,riid,ppvObject) ) #define IEnumOpenServiceActivity_AddRef(This) \ ( (This)->lpVtbl -> AddRef(This) ) #define IEnumOpenServiceActivity_Release(This) \ ( (This)->lpVtbl -> Release(This) ) #define IEnumOpenServiceActivity_Next(This,celt,rgelt,pceltFetched) \ ( (This)->lpVtbl -> Next(This,celt,rgelt,pceltFetched) ) #define IEnumOpenServiceActivity_Skip(This,celt) \ ( (This)->lpVtbl -> Skip(This,celt) ) #define IEnumOpenServiceActivity_Reset(This) \ ( (This)->lpVtbl -> Reset(This) ) #define IEnumOpenServiceActivity_Clone(This,ppenum) \ ( (This)->lpVtbl -> Clone(This,ppenum) ) #endif /* COBJMACROS */ #endif /* C style interface */ #endif /* __IEnumOpenServiceActivity_INTERFACE_DEFINED__ */ #ifndef __IOpenServiceActivityCategory_INTERFACE_DEFINED__ #define __IOpenServiceActivityCategory_INTERFACE_DEFINED__ /* interface IOpenServiceActivityCategory */ /* [unique][uuid][object] */ EXTERN_C const IID IID_IOpenServiceActivityCategory; #if defined(__cplusplus) && !defined(CINTERFACE) MIDL_INTERFACE("850AF9D6-7309-40b5-BDB8-786C106B2153") IOpenServiceActivityCategory : public IUnknown { public: virtual HRESULT STDMETHODCALLTYPE HasDefaultActivity( /* [out] */ __RPC__out BOOL *pfHasDefaultActivity) = 0; virtual HRESULT STDMETHODCALLTYPE GetDefaultActivity( /* [out] */ __RPC__deref_out_opt IOpenServiceActivity **ppDefaultActivity) = 0; virtual HRESULT STDMETHODCALLTYPE SetDefaultActivity( /* [in] */ __RPC__in_opt IOpenServiceActivity *pActivity, /* [in] */ __RPC__in HWND hwnd) = 0; virtual HRESULT STDMETHODCALLTYPE GetName( /* [out] */ __RPC__deref_out_opt BSTR *pbstrName) = 0; virtual HRESULT STDMETHODCALLTYPE GetActivityEnumerator( /* [in] */ __RPC__in_opt IOpenServiceActivityInput *pInput, /* [in] */ __RPC__in_opt IOpenServiceActivityOutputContext *pOutput, /* [out] */ __RPC__deref_out_opt IEnumOpenServiceActivity **ppEnumActivity) = 0; }; #else /* C style interface */ typedef struct IOpenServiceActivityCategoryVtbl { BEGIN_INTERFACE HRESULT ( STDMETHODCALLTYPE *QueryInterface )( __RPC__in IOpenServiceActivityCategory * This, /* [in] */ __RPC__in REFIID riid, /* [annotation][iid_is][out] */ _COM_Outptr_ void **ppvObject); ULONG ( STDMETHODCALLTYPE *AddRef )( __RPC__in IOpenServiceActivityCategory * This); ULONG ( STDMETHODCALLTYPE *Release )( __RPC__in IOpenServiceActivityCategory * This); HRESULT ( STDMETHODCALLTYPE *HasDefaultActivity )( __RPC__in IOpenServiceActivityCategory * This, /* [out] */ __RPC__out BOOL *pfHasDefaultActivity); HRESULT ( STDMETHODCALLTYPE *GetDefaultActivity )( __RPC__in IOpenServiceActivityCategory * This, /* [out] */ __RPC__deref_out_opt IOpenServiceActivity **ppDefaultActivity); HRESULT ( STDMETHODCALLTYPE *SetDefaultActivity )( __RPC__in IOpenServiceActivityCategory * This, /* [in] */ __RPC__in_opt IOpenServiceActivity *pActivity, /* [in] */ __RPC__in HWND hwnd); HRESULT ( STDMETHODCALLTYPE *GetName )( __RPC__in IOpenServiceActivityCategory * This, /* [out] */ __RPC__deref_out_opt BSTR *pbstrName); HRESULT ( STDMETHODCALLTYPE *GetActivityEnumerator )( __RPC__in IOpenServiceActivityCategory * This, /* [in] */ __RPC__in_opt IOpenServiceActivityInput *pInput, /* [in] */ __RPC__in_opt IOpenServiceActivityOutputContext *pOutput, /* [out] */ __RPC__deref_out_opt IEnumOpenServiceActivity **ppEnumActivity); END_INTERFACE } IOpenServiceActivityCategoryVtbl; interface IOpenServiceActivityCategory { CONST_VTBL struct IOpenServiceActivityCategoryVtbl *lpVtbl; }; #ifdef COBJMACROS #define IOpenServiceActivityCategory_QueryInterface(This,riid,ppvObject) \ ( (This)->lpVtbl -> QueryInterface(This,riid,ppvObject) ) #define IOpenServiceActivityCategory_AddRef(This) \ ( (This)->lpVtbl -> AddRef(This) ) #define IOpenServiceActivityCategory_Release(This) \ ( (This)->lpVtbl -> Release(This) ) #define IOpenServiceActivityCategory_HasDefaultActivity(This,pfHasDefaultActivity) \ ( (This)->lpVtbl -> HasDefaultActivity(This,pfHasDefaultActivity) ) #define IOpenServiceActivityCategory_GetDefaultActivity(This,ppDefaultActivity) \ ( (This)->lpVtbl -> GetDefaultActivity(This,ppDefaultActivity) ) #define IOpenServiceActivityCategory_SetDefaultActivity(This,pActivity,hwnd) \ ( (This)->lpVtbl -> SetDefaultActivity(This,pActivity,hwnd) ) #define IOpenServiceActivityCategory_GetName(This,pbstrName) \ ( (This)->lpVtbl -> GetName(This,pbstrName) ) #define IOpenServiceActivityCategory_GetActivityEnumerator(This,pInput,pOutput,ppEnumActivity) \ ( (This)->lpVtbl -> GetActivityEnumerator(This,pInput,pOutput,ppEnumActivity) ) #endif /* COBJMACROS */ #endif /* C style interface */ #endif /* __IOpenServiceActivityCategory_INTERFACE_DEFINED__ */ #ifndef __IEnumOpenServiceActivityCategory_INTERFACE_DEFINED__ #define __IEnumOpenServiceActivityCategory_INTERFACE_DEFINED__ /* interface IEnumOpenServiceActivityCategory */ /* [unique][uuid][object] */ typedef IOpenServiceActivityCategory *EnumActivityVerbType; EXTERN_C const IID IID_IEnumOpenServiceActivityCategory; #if defined(__cplusplus) && !defined(CINTERFACE) MIDL_INTERFACE("33627a56-8c9a-4430-8fd1-b5f5c771afb6") IEnumOpenServiceActivityCategory : public IUnknown { public: virtual HRESULT STDMETHODCALLTYPE Next( /* [in] */ ULONG celt, /* [length_is][size_is][out] */ __RPC__out_ecount_part(celt, *pceltFetched) EnumActivityVerbType *rgelt, /* [out] */ __RPC__out ULONG *pceltFetched) = 0; virtual HRESULT STDMETHODCALLTYPE Skip( /* [in] */ ULONG celt) = 0; virtual HRESULT STDMETHODCALLTYPE Reset( void) = 0; virtual HRESULT STDMETHODCALLTYPE Clone( /* [out] */ __RPC__deref_out_opt IEnumOpenServiceActivityCategory **ppenum) = 0; }; #else /* C style interface */ typedef struct IEnumOpenServiceActivityCategoryVtbl { BEGIN_INTERFACE HRESULT ( STDMETHODCALLTYPE *QueryInterface )( __RPC__in IEnumOpenServiceActivityCategory * This, /* [in] */ __RPC__in REFIID riid, /* [annotation][iid_is][out] */ _COM_Outptr_ void **ppvObject); ULONG ( STDMETHODCALLTYPE *AddRef )( __RPC__in IEnumOpenServiceActivityCategory * This); ULONG ( STDMETHODCALLTYPE *Release )( __RPC__in IEnumOpenServiceActivityCategory * This); HRESULT ( STDMETHODCALLTYPE *Next )( __RPC__in IEnumOpenServiceActivityCategory * This, /* [in] */ ULONG celt, /* [length_is][size_is][out] */ __RPC__out_ecount_part(celt, *pceltFetched) EnumActivityVerbType *rgelt, /* [out] */ __RPC__out ULONG *pceltFetched); HRESULT ( STDMETHODCALLTYPE *Skip )( __RPC__in IEnumOpenServiceActivityCategory * This, /* [in] */ ULONG celt); HRESULT ( STDMETHODCALLTYPE *Reset )( __RPC__in IEnumOpenServiceActivityCategory * This); HRESULT ( STDMETHODCALLTYPE *Clone )( __RPC__in IEnumOpenServiceActivityCategory * This, /* [out] */ __RPC__deref_out_opt IEnumOpenServiceActivityCategory **ppenum); END_INTERFACE } IEnumOpenServiceActivityCategoryVtbl; interface IEnumOpenServiceActivityCategory { CONST_VTBL struct IEnumOpenServiceActivityCategoryVtbl *lpVtbl; }; #ifdef COBJMACROS #define IEnumOpenServiceActivityCategory_QueryInterface(This,riid,ppvObject) \ ( (This)->lpVtbl -> QueryInterface(This,riid,ppvObject) ) #define IEnumOpenServiceActivityCategory_AddRef(This) \ ( (This)->lpVtbl -> AddRef(This) ) #define IEnumOpenServiceActivityCategory_Release(This) \ ( (This)->lpVtbl -> Release(This) ) #define IEnumOpenServiceActivityCategory_Next(This,celt,rgelt,pceltFetched) \ ( (This)->lpVtbl -> Next(This,celt,rgelt,pceltFetched) ) #define IEnumOpenServiceActivityCategory_Skip(This,celt) \ ( (This)->lpVtbl -> Skip(This,celt) ) #define IEnumOpenServiceActivityCategory_Reset(This) \ ( (This)->lpVtbl -> Reset(This) ) #define IEnumOpenServiceActivityCategory_Clone(This,ppenum) \ ( (This)->lpVtbl -> Clone(This,ppenum) ) #endif /* COBJMACROS */ #endif /* C style interface */ #endif /* __IEnumOpenServiceActivityCategory_INTERFACE_DEFINED__ */ #ifndef __IOpenServiceActivityManager_INTERFACE_DEFINED__ #define __IOpenServiceActivityManager_INTERFACE_DEFINED__ /* interface IOpenServiceActivityManager */ /* [unique][uuid][object] */ EXTERN_C const IID IID_IOpenServiceActivityManager; #if defined(__cplusplus) && !defined(CINTERFACE) MIDL_INTERFACE("8a2d0a9d-e920-4bdc-a291-d30f650bc4f1") IOpenServiceActivityManager : public IUnknown { public: virtual HRESULT STDMETHODCALLTYPE GetCategoryEnumerator( /* [in] */ OpenServiceActivityContentType eType, /* [out] */ __RPC__deref_out_opt IEnumOpenServiceActivityCategory **ppEnum) = 0; virtual HRESULT STDMETHODCALLTYPE GetActivityByID( /* [in] */ __RPC__in LPCWSTR pwzActivityID, /* [out] */ __RPC__deref_out_opt IOpenServiceActivity **ppActivity) = 0; virtual HRESULT STDMETHODCALLTYPE GetActivityByHomepageAndCategory( /* [in] */ __RPC__in LPCWSTR pwzHomepage, /* [in] */ __RPC__in LPCWSTR pwzCategory, /* [out] */ __RPC__deref_out_opt IOpenServiceActivity **ppActivity) = 0; virtual HRESULT STDMETHODCALLTYPE GetVersionCookie( /* [out] */ __RPC__out DWORD *pdwVersionCookie) = 0; }; #else /* C style interface */ typedef struct IOpenServiceActivityManagerVtbl { BEGIN_INTERFACE HRESULT ( STDMETHODCALLTYPE *QueryInterface )( __RPC__in IOpenServiceActivityManager * This, /* [in] */ __RPC__in REFIID riid, /* [annotation][iid_is][out] */ _COM_Outptr_ void **ppvObject); ULONG ( STDMETHODCALLTYPE *AddRef )( __RPC__in IOpenServiceActivityManager * This); ULONG ( STDMETHODCALLTYPE *Release )( __RPC__in IOpenServiceActivityManager * This); HRESULT ( STDMETHODCALLTYPE *GetCategoryEnumerator )( __RPC__in IOpenServiceActivityManager * This, /* [in] */ OpenServiceActivityContentType eType, /* [out] */ __RPC__deref_out_opt IEnumOpenServiceActivityCategory **ppEnum); HRESULT ( STDMETHODCALLTYPE *GetActivityByID )( __RPC__in IOpenServiceActivityManager * This, /* [in] */ __RPC__in LPCWSTR pwzActivityID, /* [out] */ __RPC__deref_out_opt IOpenServiceActivity **ppActivity); HRESULT ( STDMETHODCALLTYPE *GetActivityByHomepageAndCategory )( __RPC__in IOpenServiceActivityManager * This, /* [in] */ __RPC__in LPCWSTR pwzHomepage, /* [in] */ __RPC__in LPCWSTR pwzCategory, /* [out] */ __RPC__deref_out_opt IOpenServiceActivity **ppActivity); HRESULT ( STDMETHODCALLTYPE *GetVersionCookie )( __RPC__in IOpenServiceActivityManager * This, /* [out] */ __RPC__out DWORD *pdwVersionCookie); END_INTERFACE } IOpenServiceActivityManagerVtbl; interface IOpenServiceActivityManager { CONST_VTBL struct IOpenServiceActivityManagerVtbl *lpVtbl; }; #ifdef COBJMACROS #define IOpenServiceActivityManager_QueryInterface(This,riid,ppvObject) \ ( (This)->lpVtbl -> QueryInterface(This,riid,ppvObject) ) #define IOpenServiceActivityManager_AddRef(This) \ ( (This)->lpVtbl -> AddRef(This) ) #define IOpenServiceActivityManager_Release(This) \ ( (This)->lpVtbl -> Release(This) ) #define IOpenServiceActivityManager_GetCategoryEnumerator(This,eType,ppEnum) \ ( (This)->lpVtbl -> GetCategoryEnumerator(This,eType,ppEnum) ) #define IOpenServiceActivityManager_GetActivityByID(This,pwzActivityID,ppActivity) \ ( (This)->lpVtbl -> GetActivityByID(This,pwzActivityID,ppActivity) ) #define IOpenServiceActivityManager_GetActivityByHomepageAndCategory(This,pwzHomepage,pwzCategory,ppActivity) \ ( (This)->lpVtbl -> GetActivityByHomepageAndCategory(This,pwzHomepage,pwzCategory,ppActivity) ) #define IOpenServiceActivityManager_GetVersionCookie(This,pdwVersionCookie) \ ( (This)->lpVtbl -> GetVersionCookie(This,pdwVersionCookie) ) #endif /* COBJMACROS */ #endif /* C style interface */ #endif /* __IOpenServiceActivityManager_INTERFACE_DEFINED__ */ /* interface __MIDL_itf_openservice_0000_0010 */ /* [local] */ #endif /* WINAPI_FAMILY_PARTITION(WINAPI_PARTITION_DESKTOP) */ #pragma endregion extern RPC_IF_HANDLE __MIDL_itf_openservice_0000_0010_v0_0_c_ifspec; extern RPC_IF_HANDLE __MIDL_itf_openservice_0000_0010_v0_0_s_ifspec; /* Additional Prototypes for ALL interfaces */ unsigned long __RPC_USER BSTR_UserSize( __RPC__in unsigned long *, unsigned long , __RPC__in BSTR * ); unsigned char * __RPC_USER BSTR_UserMarshal( __RPC__in unsigned long *, __RPC__inout_xcount(0) unsigned char *, __RPC__in BSTR * ); unsigned char * __RPC_USER BSTR_UserUnmarshal(__RPC__in unsigned long *, __RPC__in_xcount(0) unsigned char *, __RPC__out BSTR * ); void __RPC_USER BSTR_UserFree( __RPC__in unsigned long *, __RPC__in BSTR * ); unsigned long __RPC_USER HICON_UserSize( __RPC__in unsigned long *, unsigned long , __RPC__in HICON * ); unsigned char * __RPC_USER HICON_UserMarshal( __RPC__in unsigned long *, __RPC__inout_xcount(0) unsigned char *, __RPC__in HICON * ); unsigned char * __RPC_USER HICON_UserUnmarshal(__RPC__in unsigned long *, __RPC__in_xcount(0) unsigned char *, __RPC__out HICON * ); void __RPC_USER HICON_UserFree( __RPC__in unsigned long *, __RPC__in HICON * ); unsigned long __RPC_USER HWND_UserSize( __RPC__in unsigned long *, unsigned long , __RPC__in HWND * ); unsigned char * __RPC_USER HWND_UserMarshal( __RPC__in unsigned long *, __RPC__inout_xcount(0) unsigned char *, __RPC__in HWND * ); unsigned char * __RPC_USER HWND_UserUnmarshal(__RPC__in unsigned long *, __RPC__in_xcount(0) unsigned char *, __RPC__out HWND * ); void __RPC_USER HWND_UserFree( __RPC__in unsigned long *, __RPC__in HWND * ); unsigned long __RPC_USER BSTR_UserSize64( __RPC__in unsigned long *, unsigned long , __RPC__in BSTR * ); unsigned char * __RPC_USER BSTR_UserMarshal64( __RPC__in unsigned long *, __RPC__inout_xcount(0) unsigned char *, __RPC__in BSTR * ); unsigned char * __RPC_USER BSTR_UserUnmarshal64(__RPC__in unsigned long *, __RPC__in_xcount(0) unsigned char *, __RPC__out BSTR * ); void __RPC_USER BSTR_UserFree64( __RPC__in unsigned long *, __RPC__in BSTR * ); unsigned long __RPC_USER HICON_UserSize64( __RPC__in unsigned long *, unsigned long , __RPC__in HICON * ); unsigned char * __RPC_USER HICON_UserMarshal64( __RPC__in unsigned long *, __RPC__inout_xcount(0) unsigned char *, __RPC__in HICON * ); unsigned char * __RPC_USER HICON_UserUnmarshal64(__RPC__in unsigned long *, __RPC__in_xcount(0) unsigned char *, __RPC__out HICON * ); void __RPC_USER HICON_UserFree64( __RPC__in unsigned long *, __RPC__in HICON * ); unsigned long __RPC_USER HWND_UserSize64( __RPC__in unsigned long *, unsigned long , __RPC__in HWND * ); unsigned char * __RPC_USER HWND_UserMarshal64( __RPC__in unsigned long *, __RPC__inout_xcount(0) unsigned char *, __RPC__in HWND * ); unsigned char * __RPC_USER HWND_UserUnmarshal64(__RPC__in unsigned long *, __RPC__in_xcount(0) unsigned char *, __RPC__out HWND * ); void __RPC_USER HWND_UserFree64( __RPC__in unsigned long *, __RPC__in HWND * ); /* end of Additional Prototypes */ #ifdef __cplusplus } #endif #endif
/* * This header is generated by classdump-dyld 1.5 * on Wednesday, April 14, 2021 at 2:38:26 PM Mountain Standard Time * Operating System: Version 14.4 (Build 18K802) * Image Source: /System/Library/PrivateFrameworks/VideosUI.framework/VideosUI * classdump-dyld is licensed under GPLv3, Copyright © 2013-2016 by Elias Limneos. Updated by Kevin Bradley. */ #import <VideosUI/VUIMediaItem.h> #import <libobjc.A.dylib/VUIPlistMediaEntityImageLoadParamsCreating.h> @class VUIPlistMediaDatabaseItem; @interface VUIPlistMediaItem : VUIMediaItem <VUIPlistMediaEntityImageLoadParamsCreating> { VUIPlistMediaDatabaseItem* _databaseItem; } @property (nonatomic,retain) VUIPlistMediaDatabaseItem * databaseItem; //@synthesize databaseItem=_databaseItem - In the implementation block -(id)isLocal; -(id)assetType; -(id)showTitle; -(id)seasonNumber; -(id)showIdentifier; -(id)playedState; -(id)seasonIdentifier; -(id)imageLoadParamsWithImageType:(unsigned long long)arg1 ; -(id)initWithMediaLibrary:(id)arg1 identifier:(id)arg2 requestedProperties:(id)arg3 kind:(id)arg4 ; -(id)initWithMediaLibrary:(id)arg1 databaseItem:(id)arg2 requestedProperties:(id)arg3 ; -(id)previewFrameImageIdentifier; -(id)seasonTitle; -(id)coverArtImageIdentifier; -(id)_valueForPropertyDescriptor:(id)arg1 ; -(VUIPlistMediaDatabaseItem *)databaseItem; -(void)setDatabaseItem:(VUIPlistMediaDatabaseItem *)arg1 ; @end
// // Weeks.h // JodaTime // // Created by Christian Fruth on 28.04.14. // Copyright (c) 2014 Boxx IT Solutions GmbH. All rights reserved. // # import "Period.h" @class LocalDate; @interface Weeks : Period @property (nonatomic, readonly) NSInteger weeks; + (instancetype)ZERO; + (instancetype)ONE; + (instancetype)weeks:(NSInteger)weeks; + (instancetype)weeksBetween:(LocalDate *)startDate and:(LocalDate *)stopDate; - (Weeks *)plus:(Weeks *)aWeeks; - (Weeks *)minus:(Weeks *)aWeeks; - (BOOL)isEqualToWeeks:(Weeks *)aDays; - (NSComparisonResult)compare:(Weeks *)aDays; @end
// // files.h // // classes and functions for dealing with files // // Copyright Peter Andrews 2015 @ CSHL // #ifndef LONGMEM_FILES_H_ #define LONGMEM_FILES_H_ #include <stdio.h> #include <sys/mman.h> #include <sys/stat.h> #include <unistd.h> #include <fcntl.h> #include <string> // Placed before cstring, no error, why? #include <algorithm> #include <cstring> #include <cstdio> #include <iostream> #include <fstream> #include <limits> #include <map> #include <sstream> #include <thread> #include <utility> #include <vector> #include "error.h" #ifndef MAP_POPULATE #define MAP_POPULATE 0 #endif namespace paa { extern bool read_ahead; extern bool memory_mapped; // A safe file name inline std::string safe_file_name(const std::string & name) { if (name.empty()) return ""; std::istringstream stream{name.c_str()}; char c; std::string result{""}; while (stream.get(c)) if (isalnum(c) || c == '.') result += c; return result; } // Get file extension, if exists inline std::string extension(const std::string & file_name) { const size_t pos{file_name.find_last_of('.')}; if (pos == std::string::npos) return ""; return file_name.substr(pos); } // Grab file contents as a string inline std::string file_string(const std::string & name) { std::ifstream css{name.c_str()}; std::string result; char c; while (css.get(c)) result += c; return result; } // Files and directories inline uint64_t file_size(const std::string & file_name) { struct stat st; if (stat(file_name.c_str(), &st)) { return 0; } return static_cast<uint64_t>(st.st_size); } inline void mkdir(const std::string & dir_name) { if (::mkdir(dir_name.c_str(), S_IRWXU | S_IRGRP | S_IXGRP | S_IROTH | S_IXOTH) && errno != EEXIST) throw Error("Problem creating directory") << dir_name; } inline std::string get_cwd() { constexpr uint64_t Ksize{1024}; char buffer[Ksize]; if (getcwd(buffer, Ksize) == nullptr) throw Error("Problem getting current working directory"); return std::string(buffer); } inline void symlink(const std::string & target, const std::string & linkpath) { #ifdef __CYGWIN__ throw Error("Cannot do symlink under cygwin"); #else if (::symlink(target.c_str(), linkpath.c_str()) && errno != EEXIST) throw Error("Problem creating symbilic link") << linkpath << "to" << target; #endif } inline bool readable(const std::string & file) { return !access(file.c_str(), R_OK); } inline void unlink(const std::string & file, const bool complain = false) { if (::unlink(file.c_str()) && complain) { throw Error("Could not unlink file") << file; } } inline uint64_t get_block_size(const std::string name) { struct stat sb; if (stat(name.c_str(), &sb) == -1) { perror("stat"); throw Error("stat call failure for") << name; } return sb.st_blksize; } inline std::string get_next_file(const std::string & name, const std::string ext) { static std::map<std::string, unsigned int> last_indexes; for (unsigned int i{last_indexes[name + ext] + 1}; ; ++i) { const std::string test{name + "." + std::to_string(i) + "." + ext}; if (!readable(test)) { last_indexes[name] = i; return test; } } } // Read Specific columns from disk class Columns { public: Columns(const std::string & file_name, const uint64_t size_hint, const std::string & columns, const bool header) { // Get list of desired column names or numbers std::istringstream column_input{columns.c_str()}; std::string column_spec; while (getline(column_input, column_spec, ',')) { // column spec is either name or name:type std::istringstream spec_stream{column_spec.c_str()}; std::string column_name{}; std::string column_type{}; getline(spec_stream, column_name, ':'); if (spec_stream) { spec_stream >> column_type; } column_names.push_back(column_name); column_types.push_back(column_type); } // Input file name std::ifstream input{file_name.c_str()}; if (!input) throw Error("Could not open input file") << file_name; // Process header, or just use column numbers passed using ColumnLookup = std::pair<unsigned int, unsigned int>; const std::vector<ColumnLookup> column_numbers{ [this, header, columns, &input] () { std::vector<ColumnLookup> result; if (header) { // Column names are strings std::string header_line; getline(input, header_line); std::string column_name; std::istringstream header_stream{header_line.c_str()}; unsigned int column{0}; while (header_stream >> column_name) { const std::vector<std::string>::const_iterator found{ find(column_names.begin(), column_names.end(), column_name)}; if (found != column_names.end()) result.emplace_back(column, found - column_names.begin()); ++column; } } else { // Column names are numbers, starting with 1 for (unsigned int c{0}; c != column_names.size(); ++c) { result.emplace_back(static_cast<unsigned int>( stoul(column_names[c]) - 1), c); column_names[c] = std::string(header ? "" : "column ") + column_names[c]; } sort(result.begin(), result.end(), [](const ColumnLookup & lhs, const ColumnLookup & rhs) { return lhs.first < rhs.first; }); } if (column_names.size() != result.size()) { throw Error("Could not find all columns specified in") << columns; } return result; }()}; if (0) { std::cerr << "Parse:" << std::endl; for (const std::pair<unsigned int, unsigned int> & lu : column_numbers) { std::cerr << column_names[lu.second] << " " << lu.first << " " << lu.second << std::endl; } } // Reserve space for data data.resize(column_names.size()); for (unsigned int c{0}; c != data.size(); ++c) { data.reserve(size_hint); } // Read in data line by line std::string line; std::string text; double value{0}; while (getline(input, line)) { std::istringstream stream{line.c_str()}; std::vector<ColumnLookup>::const_iterator nc{column_numbers.begin()}; unsigned int c{0}; while (stream) { if (nc != column_numbers.end() && nc->first == c) { if (stream >> value) data[nc++->second].push_back(value); } else { stream >> text; } ++c; } } if (0) std::cerr << "Read " << data[0].size() << " lines from " << file_name << std::endl; } const std::string & name(unsigned int c) const { return column_names[c]; } const std::string & type(unsigned int c) const { return column_types[c]; } uint64_t n_rows() const { return n_cols() ? data[0].size() : 0; } unsigned int n_cols() const { return static_cast<unsigned int>(data.size()); } const std::vector<double> & operator[](const unsigned int c) const { return data[c]; } private: std::vector<std::string> column_names{}; std::vector<std::string> column_types{}; std::vector<std::vector<double>> data{}; }; // class FileVector {}; // Iterator for file-based vector template<class Type, template <class ...> class Container> class VectorIterator { public: // iterator properties using value_type = Type; using difference_type = std::ptrdiff_t; using pointer = void; using reference = void; using iterator_category = std::random_access_iterator_tag; // constructor VectorIterator(const Container<Type> & file_, const uint64_t current_) : file{&file_}, current{current_} { } // null iterator construction explicit VectorIterator(const void *) : file{nullptr}, current{static_cast<uint64_t>(-1)} { } // value access const Type operator*() const { return (*file)[current]; } const Type operator[](const uint64_t offset) const { return (*file)[current + offset]; } // const Type operator->() const { return (*file)[current]; } // iterator comparison bool operator!=(const VectorIterator & rhs) const { return current != rhs.current; } bool operator==(const VectorIterator & rhs) const { return current == rhs.current; } bool operator<(const VectorIterator & rhs) const { return current < rhs.current; } int64_t operator-(const VectorIterator & rhs) const { return static_cast<int64_t>(current) - static_cast<int64_t>(rhs.current); } // iteration and random access VectorIterator & operator++() { ++current; return *this; } VectorIterator & operator--() { --current; return *this; } VectorIterator & operator+=(const uint64_t offset) { current += offset; return *this; } VectorIterator & operator-=(const uint64_t offset) { current -= offset; return *this; } VectorIterator operator+(const uint64_t offset) const { VectorIterator advanced = *this; advanced.current += offset; return advanced; } VectorIterator operator-(const uint64_t offset) const { VectorIterator advanced = *this; advanced.current -= offset; return advanced; } private: const Container<Type> * file; uint64_t current{0}; }; // Make an on-disk file (not in memory) act like a read-only vector template<class Type> class FileVector { public: using const_iterator = VectorIterator<Type, paa::FileVector>; // deleted FileVector(const FileVector &) = delete; FileVector & operator=(const FileVector &) = delete; FileVector & operator=(FileVector &&) = delete; // construction explicit FileVector(const std::string & file_name, const bool warn_empty = true) : file{fopen(file_name.c_str(), "rb")} { // Try a few times - sometimes nfs is malfunctioning temporarily if (file == nullptr) { sleep(2); file = fopen(file_name.c_str(), "rb"); if (file == nullptr) { sleep(5); file = fopen(file_name.c_str(), "rb"); if (file == nullptr) { perror("Open File"); throw Error("Could not open file in FileVector") << file_name; } } } n_elem = file_size(file_name) / sizeof(Type); if (warn_empty && n_elem == 0) { std::cerr << "Empty file opened " << file_name << std::endl; } // fileno is not available on cygwin and is not posix #if 0 const int fd{fileno(file)}; if (fd == -1) { throw Error("Could not get file descriptor for file") << file_name; } struct stat buf; if (fstat(fd, &buf) == -1) { throw Error("Could not get status for file") << file_name; } const uint64_t file_size{static_cast<uint64_t>(buf.st_size)}; if (warn_empty && file_size == 0) { std::cerr << "Empty file opened " << file_name << std::endl; } n_elem = file_size / sizeof(Type); #endif } FileVector(FileVector && other) noexcept : file{other.file}, n_elem{other.n_elem} { other.file = nullptr; other.n_elem = 0; } // size uint64_t size() const { return n_elem; } uint64_t bytes() const { return size() * sizeof(Type); } // iteration const_iterator begin() const { return const_iterator{*this, 0}; } const_iterator end() const { return const_iterator{*this, size()}; } // Just a memory location to read into union FakeType { uint64_t dummy; // to assure proper alignment char data[sizeof(Type)]; }; // access Type operator[](const uint64_t index) const { FakeType entry; if (fseek(file, index * sizeof(Type), SEEK_SET) != 0) { throw Error("Problem seeking in file"); } if (fread(&entry, sizeof(Type), 1, file) != 1) { throw Error("Problem reading from file"); } return reinterpret_cast<Type&>(entry); } Type back() const { return (*this)[size() - 1]; } // destruction ~FileVector() { if (file != nullptr) { fclose(file); } } private: FILE * file{}; uint64_t n_elem{}; }; // Memory or Memory-Mapped read-only vector base class template<class Type> class MemoryVectorBase { public: typedef const Type * const_iterator; typedef Type * iterator; // deleted MemoryVectorBase(const MemoryVectorBase &) = delete; MemoryVectorBase & operator=(const MemoryVectorBase &) = delete; MemoryVectorBase & operator=(MemoryVectorBase &&) = delete; // construction MemoryVectorBase() { } MemoryVectorBase(MemoryVectorBase && other) noexcept : data{other.data}, n_elem{other.n_elem} { other.data = nullptr; other.n_elem = 0; } // size uint64_t size() const { return n_elem; } uint64_t bytes() const { return size() * sizeof(Type); } // iteration const_iterator begin() const { return data; } const_iterator end() const { return data + n_elem; } iterator begin() { return data; } iterator end() { return data + n_elem; } // access Type operator[](const uint64_t index) const { return data[index]; } Type & operator[](const uint64_t index) { return data[index]; } protected: Type * data{nullptr}; uint64_t n_elem{0}; }; // In-Memory read-only vector template<class Type> class MemoryVector : public MemoryVectorBase<Type> { public: // typedefs using Base = MemoryVectorBase<Type>; using Base::data; using Base::n_elem; // construction MemoryVector(MemoryVector && other) noexcept : Base{std::move(other)} { } explicit MemoryVector(const std::string & file_name, const bool warn_empty = true) { const int input{open(file_name.c_str(), O_RDONLY)}; if (input == -1) throw Error("could not open input") << file_name << "for reading"; struct stat buf; if (fstat(input, &buf) == -1) throw Error("Could not get status for file") << file_name; const uint64_t file_size{static_cast<uint64_t>(buf.st_size)}; n_elem = file_size / sizeof(Type); if (file_size == 0) { if (warn_empty) std::cerr << "Empty file in MemoryVector " << file_name << std::endl; } else { data = static_cast<Type *>(::operator new(sizeof(Type) * n_elem)); if (data == nullptr) throw Error("Could not allocate memory for") << file_name; char * cdata{reinterpret_cast<char *>(data)}; uint64_t bytes_read{0}; unsigned int error_count{0}; while (bytes_read < file_size) { const uint64_t bytes_to_read{file_size - bytes_read}; const int64_t read_result{ read(input, cdata + bytes_read, bytes_to_read)}; if (read_result == -1) { if (++error_count > 10) { perror("System error"); throw Error("Problem reading file in Memory Vector") << file_name << file_size << bytes_to_read; } } else { bytes_read += read_result; } } } close(input); } // destruction ~MemoryVector() { if (data != nullptr) delete data; } }; // Memory-mapped read-only vector template<class Type, bool ReadAhead> class TMappedVector : public MemoryVectorBase<Type> { public: // typedefs using Base = MemoryVectorBase<Type>; using Base::data; using Base::n_elem; using Base::bytes; // construction TMappedVector() : Base{} { } TMappedVector(TMappedVector && other) noexcept : Base{std::move(other)} { } TMappedVector(const std::string & file_name, const uint64_t expected) : TMappedVector{file_name, false} { if (this->size() != expected) throw Error("Unexpected size in MappedVector") << file_name; } explicit TMappedVector(const std::string & file_name, const bool warn_empty = true) { const int input{open(file_name.c_str(), O_RDONLY)}; if (input == -1) throw Error("could not open input") << file_name << "for reading"; struct stat buf; if (fstat(input, &buf) == -1) throw Error("Could not get status for file") << file_name; const uint64_t file_size{static_cast<uint64_t>(buf.st_size)}; if (file_size == 0) { if (warn_empty) std::cerr << "Empty file in TMappedVector " << file_name << std::endl; } else { data = static_cast<Type *>( mmap(nullptr, file_size, PROT_READ, MAP_SHARED | (ReadAhead ? MAP_POPULATE : 0), input, 0)); if (data == MAP_FAILED) { // Need PRIVATE on newer kernels with MAP_POPULATE data = static_cast<Type *>( mmap(nullptr, file_size, PROT_READ, MAP_PRIVATE | (ReadAhead ? MAP_POPULATE : 0), input, 0)); if (data == MAP_FAILED) { perror("System Error in mmap"); throw Error("Memory mapping error for mapped file") << file_name << file_size; } } } n_elem = file_size / sizeof(Type); close(input); } // destruction ~TMappedVector() { if (n_elem && munmap(data, bytes())) perror("munmap error in TMappedVector"); } }; // PreMapped loads slowly, but is used quickly template <class Type> using PreMappedVector = TMappedVector<Type, true>; // UnMapped loads instantly, but is used slowly at first template <class Type> using UnMappedVector = TMappedVector<Type, false>; // Use UnMapped as default template <class Type> using MappedVector = UnMappedVector<Type>; #if 0 // Only works for char Type template <class Type> class ZippedVector { public: ZippedVector(const std::string & unzipped_name, const uint64_t expected) { const std::string unzip{"zcat " + unzipped_name + ".gz"}; redi::ipstream input{unzip.c_str()}; if (!input) throw Error("Problem executing command") << unzip; input >> data; if (data.size() != expected) throw Error("Unexpected size in ZippedVector") << unzipped_name << data.size() << expected; } uint64_t size() const { return data.size(); } const Type & operator[](const uint64_t index) const { return data[index]; } private: std::string data{}; }; #endif // // Class that loads data from text file the first time, // and saves binary cache for later use of file // template <class Data> class BinaryCache { public: class NormalFileEnd {}; template <class ParseStreamFun> BinaryCache(const std::string & input_file_name, ParseStreamFun parse_line, std::string binary_file_name = "") { if (binary_file_name.empty()) { binary_file_name = input_file_name + ".bin"; } if (!readable(binary_file_name)) { try { std::ifstream in_stream{input_file_name.c_str()}; std::ofstream out_stream{binary_file_name.c_str(), std::ios::binary}; if (!in_stream) throw Error("Could not open input file in BinaryCache") << input_file_name; while (in_stream) { const Data item{parse_line(in_stream)}; out_stream.write(reinterpret_cast<const char *>(&item), sizeof(Data)); } } catch (NormalFileEnd &) { if (false) std::cerr << "File end" << std::endl; } } new (this) BinaryCache<Data>{binary_file_name}; } explicit BinaryCache(const std::string & binary_file_name) : data{binary_file_name} { } uint64_t size() const { return data.size(); } const Data & operator[](const uint64_t index) const { return data[index]; } const Data * begin() const { return data.begin(); } const Data * end() const { return data.end(); } private: const PreMappedVector<Data> data{"/dev/null", false}; }; template <class Type> void write_one(FILE * out, const Type & value, const char * name) { const uint64_t written = fwrite(&value, sizeof(Type), 1, out); if (written != 1) { perror(nullptr); throw Error("problem writing") << name; } } template <class Type> void read_one(FILE * in, Type & value, const char * name) { const uint64_t read_in = fread(&value, sizeof(Type), 1, in); if (read_in != 1) { perror(nullptr); throw Error("problem reading") << name; } } inline void bwritec(FILE * output, const void * data, const std::string & name, const uint64_t count) { const uint64_t written = fwrite(data, 1, count, output); if (written != count) { perror(nullptr); throw Error("problem writing") << count << "bytes at" << name << "only wrote" << written; } } inline void bwritec(const std::string & filename, const void * data, const std::string & name, const uint64_t count) { FILE * output = fopen(filename.c_str(), "wb"); if (output == nullptr) throw Error("could not open output") << filename << "for writing"; bwritec(output, data, name, count); if (fclose(output) != 0) throw Error("problem closing output file") << filename; } // Flexible Memory or Mapped vector // memory - read / write / change size // mapped - read only template<class Type> class FlexVector : public MemoryVectorBase<Type> { public: // typedefs using Base = MemoryVectorBase<Type>; using Base::data; using Base::n_elem; using Base::bytes; // construction FlexVector(const FlexVector &) = delete; FlexVector & operator=(const FlexVector &) = delete; FlexVector & operator=(FlexVector &&) = delete; FlexVector() : Base{} { } FlexVector(FlexVector && other) noexcept : Base{std::move(other)}, mapped_{other.mapped_} { other.mapped_ = false; } explicit FlexVector(const uint64_t new_n_elem) : Base{} { clear_and_resize(new_n_elem); } explicit FlexVector(const std::string & file_name, const bool mapped__ = true, const bool read_ahead_ = false, const bool warn_empty = true) : mapped_{mapped__} { if (mapped_) { read_mapped(file_name, read_ahead_, warn_empty); } else { read_memory(file_name); } } // destruction ~FlexVector() { // std::cerr << "Destroy FlexVector " << n_elem << " " << data << " " // << mapped_ << std::endl; free(); } // Common functions void free() { if (data) { if (mapped_) { if (munmap(data, bytes())) { perror("munmap error in FlexVector"); } } else { delete[] data; } } } void save(const std::string & file_name) const { bwritec(file_name, data, "FlexVector", n_elem * sizeof(Type)); } // Memory only functions void clear_and_resize(const uint64_t new_n_elem) { if (new_n_elem != n_elem) { free(); n_elem = new_n_elem; data = new Type[n_elem](); } else { for (uint64_t i{0}; i != n_elem; ++i) { data[i] = Type(); } } } void read_memory(const std::string &) { throw Error("read_memory not implemented yet"); } // Mapped only functions void read_mapped(const std::string & file_name, const bool read_ahead_ = true, const bool warn_empty = true) { free(); mapped_ = true; const int fid{open(file_name.c_str(), O_RDONLY)}; if (fid == -1) { throw Error("could not open input") << file_name << "for reading"; } struct stat buf; if (fstat(fid, &buf) == -1) { throw Error("Could not get status for file") << file_name; } const uint64_t file_size{static_cast<uint64_t>(buf.st_size)}; if (file_size == 0) { if (warn_empty) { std::cerr << "Empty file in FlexVector " << file_name << std::endl; } data = nullptr; } else { data = static_cast<Type *>( mmap(nullptr, file_size, PROT_READ, MAP_SHARED | (read_ahead_ ? MAP_POPULATE : 0), fid, 0)); if (data == MAP_FAILED) { // Need PRIVATE on newer kernels with MAP_POPULATE data = static_cast<Type *>( mmap(nullptr, file_size, PROT_READ, MAP_PRIVATE | (read_ahead_ ? MAP_POPULATE : 0), fid, 0)); if (data == MAP_FAILED) { perror("System Error in mmap"); throw Error("Memory mapping error for mapped file") << file_name << file_size; } } } n_elem = file_size / sizeof(Type); close(fid); } private: bool mapped_{false}; }; template<class T> void bwrite(FILE * output, const T & data, const std::string & name, const uint64_t count = 1) { bwritec(output, &data, name, sizeof(T) * count); } // void bwritec(const std::string & filename, const void * data, // const std::string & name, const uint64_t count); template<class T> void bwrite(const std::string & filename, const T & data, const std::string & name, const uint64_t count = 1) { bwritec(filename, &data, name, sizeof(T) * count); } void breadc(FILE * input, void * data, const std::string & name, const uint64_t count); template<class T> void bread(FILE * input, T & data, const std::string & name, const uint64_t count = 1) { breadc(input, &data, name, sizeof(T) * count); } void breadc(const std::string & filename, void * & data, const std::string & name, const uint64_t count); template<class T> void bread(const std::string & filename, T * & data, const std::string & name, const uint64_t count = 1) { breadc(filename, reinterpret_cast<void*&>(data), name, count * sizeof(T)); } template<class Type> class GrowingVector { public: typedef Type * iterator; typedef const Type * const_iterator; // deleted GrowingVector(const GrowingVector &) = delete; GrowingVector & operator=(const GrowingVector &) = delete; // construction, etc GrowingVector() noexcept(false) : GrowingVector{initial_size} {} explicit GrowingVector(const uint64_t start_size) noexcept(false) : capacity{start_size}, data{static_cast<Type *>(::operator new(sizeof(Type) * capacity))} { } GrowingVector(GrowingVector && other) noexcept : n_elem{other.n_elem}, capacity{other.capacity}, data{other.data} { other.n_elem = 0; other.capacity = 0; other.data = nullptr; } GrowingVector & operator=(GrowingVector && other) noexcept { if (capacity) delete data; n_elem = other.n_elem; capacity = other.capacity; data = other.data; other.n_elem = 0; other.capacity = 0; other.data = nullptr; return *this; } // expansion template<typename... VArgs> void emplace_back(VArgs && ... args) { expand_if_needed(); new (data + n_elem++) Type(std::forward<VArgs>(args) ...); } void push_back(const Type val) { expand_if_needed(); data[n_elem++] = val; } template <class P> void insert_back(P b, P e) { while (b != e) { push_back(*(b++)); } } // info uint64_t bytes() const { return capacity * sizeof(Type); } uint64_t size() const { return n_elem; } // read only access const Type * begin() const { return data; } const Type * end() const { return data + n_elem; } Type operator[](const uint64_t index) const { return data[index]; } const Type back() const { return data[n_elem - 1]; } // write access Type * begin() { return data; } Type * end() { return data + n_elem; } Type & operator[](const uint64_t index) { return data[index]; } Type & back() { return data[n_elem - 1]; } // shrinking void clear() { n_elem = 0; } void reduce_size(const uint64_t new_size) { n_elem = new_size; } // saving void save(const std::string & file_name) const { bwritec(file_name, data, "GrowingVector", n_elem * sizeof(Type)); } void write(std::FILE * out_file) const { bwritec(out_file, data, "GrowingVector", n_elem * sizeof(Type)); } void write_n(std::FILE * out_file, const uint64_t n) const { bwritec(out_file, data, "GrowingVector", n * sizeof(Type)); } // destruction ~GrowingVector() { if (capacity) delete data; } private: void expand_if_needed() { if (n_elem + 1 > capacity) { capacity *= 2; Type * new_data_location = static_cast<Type *>(::operator new(sizeof(Type) * capacity)); memcpy(new_data_location, data, n_elem * sizeof(Type)); delete data; data = new_data_location; } } static constexpr uint64_t initial_size{1024}; uint64_t n_elem{0}; uint64_t capacity{0}; Type * data{nullptr}; }; class MappedFile { public: // deleted MappedFile(const MappedFile &) = delete; MappedFile operator=(const MappedFile &) = delete; MappedFile & operator=(MappedFile &&) = delete; MappedFile(); explicit MappedFile(const std::string & file_name_, const bool warn_empty = true); MappedFile(MappedFile && other) noexcept; ~MappedFile(); void load(const std::string & file_name_, const bool warn_empty = true); const std::string & name() const { return file_name; } void unmap(); int advise(const char * start, uint64_t length, const int advice) const; void sequential(const char * start = nullptr, const uint64_t length = 0) const; void random(const char * start = nullptr, const uint64_t length = 0) const; void unneeded(const char * start = nullptr, const uint64_t length = 0) const; void needed(const char * start = nullptr, const uint64_t length = 0) const; char * begin() { return file_begin; } char * end() { return file_end; } const char * begin() const { return file_begin; } const char * end() const { return file_end; } const char * cbegin() const { return file_begin; } const char * cend() const { return file_end; } uint64_t size() const { return static_cast<uint64_t>(file_end - file_begin); } uint64_t page_size() const { return page; } private: std::string file_name{}; char * file_begin{nullptr}; char * file_end{nullptr}; uint64_t page{0}; }; class BinWriter { public: explicit BinWriter(const std::string & filename) : outfile{fopen(filename.c_str(), "wb")} { if (outfile == nullptr) throw Error("could not open outfile") << filename << "for writing"; } BinWriter(const BinWriter &) = delete; BinWriter operator=(const BinWriter &) = delete; ~BinWriter() { if (fclose(outfile) != 0) std::cerr << "problem closing BinWriter outfile" << std::endl; } FILE * outfile; }; template <class Out> BinWriter & operator<<(BinWriter & writer, const Out out) { bwrite(writer.outfile, out, "some binary value", 1); return writer; } // // FileMerger // // Keeps list of file names // merges the objects in them // // keeps sorted list (1) of objects from front of files // no objects elsewhere are lower than highest object in list (A) // // higher objects are still in files or in a separate sorted array (2) // // Merger opens and reads from files at current position // then sorts objects in (2) // // when (1) is empty, (2) is transferred to (1) so that (A) is satisfied // // Buffered Closed File // // Read a stream from many thousands of files at once // but can only have open 1000 or so at a time // how to handle? // // Want to limit file open/close operations // Want to limit read operations // Want data from all files to be accessible quickly // this means buffering, while attempting to keep // all soon-to-be-used data in cache if possible, // and maybe read-aheads to limit wait times for file access // // open file, read into big buffer, close file, // copy section into small buffer // read from small buffer until exhausted // copy from big buffer into small buffer // When big buffer exhausted, open thread to replenish // // keep small buffers in cache! // Files are intended to be stored in an array! // picture 4096 files // 16 cores * 32 KB = 512 KB // 512 KB / 4096 = 128 bytes // if 24 bytes per record // small buffer is 5.3 objects only! // // Similar reasoning gives for 20 MB shared cache // big buffer is 10248 bytes and holds 426.6 objects // // ~15 Million objects chr 1 per file // 30,000 file opens and reads per file // // 16 cores on wigclust 17-24 // 32 KB / core L1 cache // 256 KB / core L2 cache // 20 MB L3 cache x 2 processors // // Designed for sequential access // using next() // but can do initial binary search while open to find good starting point? // template <class Type, unsigned int small_buffer_bytes = 128, unsigned int big_buffer_bytes = 10240> class BufferedClosedFile { }; template<class Type> class OldMappedVector { public: typedef Type * iterator; typedef const Type * const_iterator; // deleted OldMappedVector(const OldMappedVector &) = delete; OldMappedVector & operator=(const OldMappedVector &) = delete; OldMappedVector & operator=(OldMappedVector &&) = delete; // use these member functions during building only OldMappedVector() : OldMappedVector{initial_size} {} explicit OldMappedVector(const uint64_t start_size) : capacity{start_size}, data{static_cast<Type *>(::operator new(sizeof(Type) * capacity))} { } OldMappedVector(OldMappedVector && old) noexcept : file{std::move(old.file)}, mapped{old.mapped}, n_elem{old.n_elem}, capacity{old.capacity}, data{old.data} { old.mapped = false; old.capacity = 0; } template<typename... VArgs> void emplace_back(VArgs && ... args) { expand_if_needed(); new (data + n_elem++) Type(std::forward<VArgs>(args) ...); } void push_back(const Type val) { expand_if_needed(); data[n_elem++] = val; } template <class P> void insert_back(P b, P e) { while (b != e) { push_back(*(b++)); } } Type * begin() { return data; } Type * end() { return data + n_elem; } void clear() { n_elem = 0; } void reduce_size(const uint64_t new_size) { n_elem = new_size; } void save(const std::string & file_name) const { bwritec(file_name, data, "OldMappedVector", n_elem * sizeof(Type)); } void write(std::FILE * out_file) const { bwritec(out_file, data, "OldMappedVector", n_elem * sizeof(Type)); } void write_n(std::FILE * out_file, const uint64_t n) const { bwritec(out_file, data, "OldMappedVector", n * sizeof(Type)); } // use these member function during reading only explicit OldMappedVector(const std::string & file_name, const bool warn_empty = true) : file{file_name, warn_empty}, mapped{file.begin() == nullptr ? false : true}, n_elem{file.size() / sizeof(Type)}, capacity{n_elem}, data{reinterpret_cast<Type *>(file.begin())} { } const std::string & name() const { return file.name(); } // these member functions can be used anytime uint64_t bytes() const { return capacity * sizeof(Type); } uint64_t size() const { return n_elem; } const Type * begin() const { return data; } const Type * end() const { return data + n_elem; } Type operator[](const uint64_t index) const { return data[index]; } Type & operator[](const uint64_t index) { return data[index]; } const Type back() const { return data[n_elem - 1]; } Type & back() { return data[n_elem - 1]; } ~OldMappedVector() { if (!mapped && capacity) delete data; } private: void expand_if_needed() { if (n_elem + 1 > capacity) { capacity *= 2; Type * new_data_location = static_cast<Type *>(::operator new(sizeof(Type) * capacity)); memcpy(new_data_location, data, n_elem * sizeof(Type)); delete data; data = new_data_location; } } static constexpr uint64_t initial_size{1000}; MappedFile file{}; bool mapped{false}; uint64_t n_elem{0}; uint64_t capacity{0}; Type * data{nullptr}; }; // // a potentially dangerous class - exists in a build state or a read state // and some member functions can only be used in one of the states // template<class Type> class OlderMappedVector { public: typedef Type * iterator; typedef const Type * const_iterator; // deleted OlderMappedVector(const OlderMappedVector &) = delete; OlderMappedVector & operator=(const OlderMappedVector &) = delete; OlderMappedVector & operator=(OlderMappedVector &&) = delete; // use these member functions during building only OlderMappedVector() : OlderMappedVector{initial_size} {} explicit OlderMappedVector(const uint64_t start_size) : capacity{start_size}, data{static_cast<Type *>(::operator new(sizeof(Type) * capacity))} { } OlderMappedVector(OlderMappedVector && old) noexcept : file{std::move(old.file)}, mapped{old.mapped}, n_elem{old.n_elem}, capacity{old.capacity}, data{old.data} { old.mapped = false; old.capacity = 0; } template<typename... VArgs> void emplace_back(VArgs && ... args) { expand_if_needed(); new (data + n_elem++) Type(std::forward<VArgs>(args) ...); } void push_back(const Type val) { expand_if_needed(); data[n_elem++] = val; } template <class P> void insert_back(P b, P e) { while (b != e) { push_back(*(b++)); } } Type * begin() { return data; } Type * end() { return data + n_elem; } void clear() { n_elem = 0; } void reduce_size(const uint64_t new_size) { n_elem = new_size; } void save(const std::string & file_name) const { bwritec(file_name, data, "OlderMappedVector", n_elem * sizeof(Type)); } void write(std::FILE * out_file) const { bwritec(out_file, data, "OlderMappedVector", n_elem * sizeof(Type)); } void write_n(std::FILE * out_file, const uint64_t n) const { bwritec(out_file, data, "OlderMappedVector", n * sizeof(Type)); } // use these member function during reading only explicit OlderMappedVector(const std::string & file_name, const bool warn_empty = true) : file{file_name, warn_empty}, mapped{file.begin() == nullptr ? false : true}, n_elem{file.size() / sizeof(Type)}, capacity{n_elem}, data{reinterpret_cast<Type *>(file.begin())} { } const std::string & name() const { return file.name(); } void load(const std::string & file_name_, const bool warn_empty = true) { file.load(file_name_, warn_empty); mapped = file.begin() == nullptr ? false : true; n_elem = file.size() / sizeof(Type); data = reinterpret_cast<Type *>(file.begin()); } // these member functions can be used anytime uint64_t bytes() const { return capacity * sizeof(Type); } uint64_t size() const { return n_elem; } const Type * begin() const { return data; } const Type * end() const { return data + n_elem; } Type operator[](const uint64_t index) const { return data[index]; } Type & operator[](const uint64_t index) { return data[index]; } const Type back() const { return data[n_elem - 1]; } Type & back() { return data[n_elem - 1]; } ~OlderMappedVector() { if (!mapped && capacity) delete data; } private: void expand_if_needed() { if (n_elem + 1 > capacity) { capacity *= 2; Type * new_data_location = static_cast<Type *>(::operator new(sizeof(Type) * capacity)); memcpy(new_data_location, data, n_elem * sizeof(Type)); delete data; data = new_data_location; } } static constexpr uint64_t initial_size{1000}; MappedFile file{}; bool mapped{false}; uint64_t n_elem{0}; uint64_t capacity{0}; Type * data{nullptr}; }; template<class BigInt, class SmallInt> class CompressedInts { public: explicit CompressedInts(const uint64_t capacity = 0, const uint64_t n_lookup = 0) : lookup{n_lookup}, small{capacity} { } explicit CompressedInts(const std::string & dir, const unsigned int small_start = 0, const unsigned int lookup_start = 0) : lookup{dir + "/lookup.bin"}, small{dir + "/counts.bin"}, big{dir + "/over.bin"}, small_position{small_start}, big_position{lookup[lookup_start]} {} #if 0 CompressedInts(CompressedInts && other) noexcept { lookup = move(other.lookup); small = move(other.small); big = move(other.big); small_position = other.small_position; big_position = other.big_position; } #endif BigInt next_int() const { if (small_position == small.size()) { throw Error("Tried to read past end of CompressedInts"); return std::numeric_limits<BigInt>::max(); } else { const SmallInt s = small[small_position++]; if (s == std::numeric_limits<SmallInt>::max()) { return big[big_position++]; } else { return s; } } } void add_int(unsigned int b) { if (b > std::numeric_limits<BigInt>::max()) { std::cerr << "add_int encountered big int " << b << std::endl; b = std::numeric_limits<BigInt>::max(); } if (b >= std::numeric_limits<SmallInt>::max()) { small.push_back(std::numeric_limits<SmallInt>::max()); big.push_back(static_cast<BigInt>(b)); } else { small.push_back(static_cast<SmallInt>(b)); } } void print_savings() const { std::cerr << "Saved " << small.size() * (sizeof(BigInt)-sizeof(SmallInt)) - big.size() * sizeof(BigInt) << " bytes" << std::endl; } void add_lookup_entry() { lookup.push_back(static_cast<unsigned int>(big.size())); } void save(const std::string & dir_name) const { mkdir(dir_name); std::ostringstream counts_filename; counts_filename << dir_name << "/counts.bin"; std::FILE * counts_file = fopen(counts_filename.str().c_str(), "wb"); if (counts_file == nullptr) throw Error("Problem opening counts file") << counts_filename.str(); if (fwrite(small.begin(), sizeof(SmallInt), small.size(), counts_file) != small.size()) throw Error("Problem writing in counts file") << counts_filename.str(); if (fclose(counts_file)) throw Error("Problem closing counts file") << counts_filename.str(); std::ostringstream over_filename; over_filename << dir_name << "/over.bin"; std::FILE * over_file = fopen(over_filename.str().c_str(), "wb"); if (over_file == nullptr) throw Error("Problem opening over file") << over_filename.str(); if (fwrite(big.begin(), sizeof(BigInt), big.size(), over_file) != big.size()) throw Error("Problem writing in over file") << over_filename.str(); if (fclose(over_file)) throw Error("Problem closing over file") << over_filename.str(); std::ostringstream lookup_filename; lookup_filename << dir_name << "/lookup.bin"; std::FILE * lookup_file = fopen(lookup_filename.str().c_str(), "wb"); if (lookup_file == nullptr) throw Error("Problem opening lookup file") << lookup_filename.str(); if (fwrite(lookup.begin(), sizeof(unsigned int), lookup.size(), lookup_file) != lookup.size()) throw Error("Problem writing in lookup file") << lookup_filename.str(); if (fclose(lookup_file)) throw Error("Problem closing lookup file") << lookup_filename.str(); print_savings(); } void relocate(const uint64_t new_small, const uint64_t new_lookup) const { small_position = new_small; big_position = lookup[new_lookup]; } uint64_t size() const { return small.size(); } SmallInt clipped_result(const uint64_t i) const { return small[i]; } private: OlderMappedVector<unsigned int> lookup; OlderMappedVector<SmallInt> small; OlderMappedVector<BigInt> big{}; mutable uint64_t small_position{0}; mutable uint64_t big_position{0}; }; typedef CompressedInts<uint16_t, uint8_t> Compressed; template <class STREAM> struct Fstream : public STREAM { explicit Fstream(const std::string & file_name, const std::string & description = "") : STREAM{file_name} { if (!*this) { std::ostringstream message; message << "Problem opening"; if (description.size()) message << ' ' << description; message << " file " << file_name; throw Error(message.str()); } } }; using iFstream = Fstream<std::ifstream>; using oFstream = Fstream<std::ofstream>; } // namespace paa #endif // LONGMEM_FILES_H_
/* * i2c.c * * Created on: 26/ott/2015 * Author: nicola */ // Function used to setup I2C1, that is P0.19 and P0.20 on LPC1769 // That's useful because an I2C-E2PROM 24LC64 is already present on evaluation board // #include "lpc1769.h" #include "i2c.h" unsigned char I2Cbuffer[I2C_BUFFER_LEN]; // I2C data buffer unsigned char* I2CbufferPtr; // I2C buffer pointer int I2CbufferCnt; // I2C buffer counter int I2CrptStartPos; // I2C Repeated Start position // I2C1 Interrupt request handler void I2C1_IRQHandler(void) { unsigned int I2C_Status=0; I2C_Status = I2C1STAT; // load I2C1 status register value switch(I2C_Status) { case START: // START condition or I2CbufferPtr = I2Cbuffer; // reset buffer pointer case REP_START: // repeated START condition has been transmitted I2C1DAT = *I2CbufferPtr; // load SLA+R/W to I2C1DAT I2CbufferCnt--; // update buffer counter I2C1CONCLR = (1<<5); // clear I2C STA flag break; ////////////////////// Master transmitter mode case SLA_W_ACK: // SLA+W has been transmitted; ACK has been received case DATA_W_ACK: // Data byte in I2DAT has been transmitted; ACK has been received if(I2CbufferCnt>0) // check buffer counter value { I2CbufferPtr++; // update buffer pointer if(I2CbufferCnt!=I2CrptStartPos) { I2C1DAT = *I2CbufferPtr; // load data byte to I2C1DAT I2CbufferCnt--; // update buffer counter } else I2C1CONSET |= (1<<5); // set I2C START flag (REPEATED START) } else I2C1CONSET = (1<<4); // set I2C STOP flag break; case SLA_W_NACK: // SLA+W has been transmitted; NOT ACK has been received case DATA_W_NACK: // Data byte in I2DAT has been transmitted; NOT ACK has been received I2C1CONSET = (1<<4); // set I2C STOP flag break; //////////////////////////////////// ////////////////////// Master receiver mode case SLA_R_ACK: // SLA+R has been transmitted; ACK has been received I2CbufferPtr++; // update buffer pointer break; case DATA_R_ACK: // Data byte has been received; ACK has been returned if(I2CbufferCnt>1) // check buffer counter value I2C1CONSET = (1<<2); // set I2C AA flag else I2C1CONCLR = (1<<2); // clear I2C AA flag *I2CbufferPtr = I2C1DAT; // load I2C1DAT to data byte I2CbufferCnt--; // update buffer counter break; case DATA_R_NACK: // Data byte has been received; NOT ACK has been returned *I2CbufferPtr = I2C1DAT; // load I2C1DAT to data byte I2CbufferCnt--; // update buffer counter case SLA_R_NACK: // SLA+R has been transmitted; NOT ACK has been received I2C1CONSET = (1<<4); // set I2C STOP flag break; //////////////////////////////////// case NO_RELEVANT: // No relevant information available; SI = 0 break; default: // undefined status I2C1CONSET = (1<<4); // set I2C STOP flag } I2C1CONCLR = (1<<3); // clear I2C interrupt flag return; } // I2C1 setup function int setupI2C1() { PINSEL1 |= (0b1111 << 6); // set bit PINSEL1[9:6] at 0b1111 so that P0.19 act as SDA1 and P0.20 as SCL1 PINMODE1 |= (0b1010 << 6); // set bit PINMODE1[9:6] at 0b1010 so that P0.19 and P0.20 have neither pull-up nor pull-down PINMODE_OD0 |= (0b11 << 19); // set bit PINMODE_OD0[20:19] at 0b11 so that P0.19 and P0.20 are open drain ISER0 |= (0b1 << 11); // set ISER0[11] so that ISE_I2C1 interrupt is enabled IPR2 |= (0b10000 << 27); // set IPR2[31:27] at 0b10000 so that IP_I2C1 has priority 0x10 (middle priority) I2C1SCLH = I2C1SCLL = ((CORE_CLK/4)/I2C_STD_FREQ)/2; // check equation(13) at page 457 of User Manual I2C1CONSET |= (1<<6); // set I2EN to enable I2C1 interface return 0; } // I2C1 start function int startI2C1() { I2C1CONSET |= (1<<5); // set I2C START flag return 0; }
//------------------------------------------------------------------------------ /* This file is part of rippled: https://github.com/ripple/rippled Copyright (c) 2012, 2013 Ripple Labs Inc. Permission to use, copy, modify, and/or distribute this software for any purpose with or without fee is hereby granted, provided that the above copyright notice and this permission notice appear in all copies. THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL , DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. */ //============================================================================== #ifndef RIPPLE_CORE_CONFIG_H_INCLUDED #define RIPPLE_CORE_CONFIG_H_INCLUDED #include <ripple/basics/BasicConfig.h> #include <ripple/basics/base_uint.h> #include <ripple/protocol/SystemParameters.h> // VFALCO Breaks levelization #include <ripple/beast/net/IPEndpoint.h> #include <beast/core/string.hpp> #include <ripple/beast/utility/Journal.h> #include <boost/asio/ip/tcp.hpp> // VFALCO FIX: This include should not be here #include <boost/filesystem.hpp> // VFALCO FIX: This include should not be here #include <boost/lexical_cast.hpp> #include <boost/optional.hpp> #include <cstdint> #include <map> #include <string> #include <type_traits> #include <unordered_set> #include <vector> namespace ripple { using namespace std::chrono_literals; class Rules; //------------------------------------------------------------------------------ enum SizedItemName { siSweepInterval, siNodeCacheSize, siNodeCacheAge, siTreeCacheSize, siTreeCacheAge, siSLECacheSize, siSLECacheAge, siLedgerSize, siLedgerAge, siLedgerFetch, siHashNodeDBCache, siTxnDBCache, siLgrDBCache, }; struct SizedItem { SizedItemName item; int sizes[5]; }; // This entire derived class is deprecated. // For new config information use the style implied // in the base class. For existing config information // try to refactor code to use the new style. // class Config : public BasicConfig { public: // Settings related to the configuration file location and directories static char const* const configFileName; static char const* const databaseDirName; static char const* const validatorsFileName; /** Returns the full path and filename of the debug log file. */ boost::filesystem::path getDebugLogFile () const; /** Returns the full path and filename of the entropy seed file. */ boost::filesystem::path getEntropyFile () const; private: boost::filesystem::path CONFIG_FILE; boost::filesystem::path CONFIG_DIR; boost::filesystem::path DEBUG_LOGFILE; void load (); beast::Journal j_; bool QUIET = false; // Minimize logging verbosity. bool SILENT = false; // No output to console after startup. /** Operate in stand-alone mode. In stand alone mode: - Peer connections are not attempted or accepted - The ledger is not advanced automatically. - If no ledger is loaded, the default ledger with the root account is created. */ bool RUN_STANDALONE = false; public: bool doImport = false; bool valShards = false; bool ELB_SUPPORT = false; std::vector<std::string> IPS; // Peer IPs from rippled.cfg. std::vector<std::string> IPS_FIXED; // Fixed Peer IPs from rippled.cfg. std::vector<std::string> SNTP_SERVERS; // SNTP servers from rippled.cfg. enum StartUpType { FRESH, NORMAL, LOAD, LOAD_FILE, REPLAY, NETWORK }; StartUpType START_UP = NORMAL; bool START_VALID = false; std::string START_LEDGER; // Network parameters int const TRANSACTION_FEE_BASE = 10; // The number of fee units a reference transaction costs // Note: The following parameters do not relate to the UNL or trust at all std::size_t NETWORK_QUORUM = 0; // Minimum number of nodes to consider the network present // Peer networking parameters bool PEER_PRIVATE = false; // True to ask peers not to relay current IP. int PEERS_MAX = 0; std::chrono::seconds WEBSOCKET_PING_FREQ = 5min; // Path searching int PATH_SEARCH_OLD = 7; int PATH_SEARCH = 7; int PATH_SEARCH_FAST = 2; int PATH_SEARCH_MAX = 10; // Validation boost::optional<std::size_t> VALIDATION_QUORUM; // validations to consider ledger authoritative std::uint64_t FEE_DEFAULT = 10; std::uint64_t FEE_ACCOUNT_RESERVE = 200*SYSTEM_CURRENCY_PARTS; std::uint64_t FEE_OWNER_RESERVE = 50*SYSTEM_CURRENCY_PARTS; std::uint64_t FEE_OFFER = 10; // Node storage configuration std::uint32_t LEDGER_HISTORY = 256; std::uint32_t FETCH_DEPTH = 1000000000; int NODE_SIZE = 0; bool SSL_VERIFY = true; std::string SSL_VERIFY_FILE; std::string SSL_VERIFY_DIR; // Thread pool configuration std::size_t WORKERS = 0; // These override the command line client settings boost::optional<boost::asio::ip::address_v4> rpc_ip; boost::optional<std::uint16_t> rpc_port; std::unordered_set<uint256, beast::uhash<>> features; public: Config() = default; int getSize (SizedItemName) const; /* Be very careful to make sure these bool params are in the right order. */ void setup (std::string const& strConf, bool bQuiet, bool bSilent, bool bStandalone); void setupControl (bool bQuiet, bool bSilent, bool bStandalone); /** * Load the config from the contents of the string. * * @param fileContents String representing the config contents. */ void loadFromString (std::string const& fileContents); bool quiet() const { return QUIET; } bool silent() const { return SILENT; } bool standalone() const { return RUN_STANDALONE; } }; } // ripple #endif
// // Copyright (c) 2014-2016 THUNDERBEAST GAMES LLC // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. // #pragma once #include "JSBSourceWriter.h" using namespace Atomic; namespace ToolCore { class JSBPackage; class JSBClass; class JSBPackageWriter : public JSBSourceWriter { public: virtual void GenerateSource(); virtual void PostProcess() {} protected: JSBPackageWriter(JSBPackage* package); JSBPackage* package_; }; }
#ifndef __SUB_TRACK_FILTER_H__ #define __SUB_TRACK_FILTER_H__ #include "abstractreader.h" class SubTrackFilter { public: SubTrackFilter(int pid) : m_srcPID(pid) {} virtual ~SubTrackFilter() {} static int pidToSubPid(int pid, int subPid) { return (pid << 16) + subPid; } static bool isSubTrack(int pid) { return pid >= 65536; } bool isSupportedTrack(int pid) const { return m_srcPID == pid; } virtual int demuxPacket(DemuxedData& demuxedData, const PIDSet& acceptedPIDs, AVPacket& avPacket) = 0; protected: int m_srcPID; }; #endif // __SUB_TRACK_FILTER_H__
// // UIImage+Util.h // iosapp // // Created by ChanAetern on 2/13/15. // Copyright (c) 2015 oschina. All rights reserved. // #import <UIKit/UIKit.h> @interface UIImage (Util) - (UIImage *)imageMaskedWithColor:(UIColor *)maskColor; - (UIImage *)cropToRect:(CGRect)rect; @end
#ifndef STDIO_H #define STDIO_H #include "os_type.h" class STDIO { private: uint8 *screen; public: STDIO(); // 初始化函数 void initialize(); // 打印字符c,颜色color到位置(x,y) void print(uint x, uint y, uint8 c, uint8 color); // 打印字符c,颜色color到光标位置 void print(uint8 c, uint8 color); // 打印字符c,颜色默认到光标位置 void print(uint8 c); // 移动光标到一维位置 void moveCursor(uint position); // 移动光标到二维位置 void moveCursor(uint x, uint y); // 获取光标位置 uint getCursor(); private: // 滚屏 void rollUp(); }; #endif
/* * Microsoft Advanced Streaming Format demuxer * Copyright (c) 2014 Alexandra Hájková * * This file is part of FFmpeg. * * FFmpeg is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * FFmpeg is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with FFmpeg; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ #include "libavutil/attributes.h" #include "libavutil/avstring.h" #include "libavutil/bswap.h" #include "libavutil/common.h" #include "libavutil/dict.h" #include "libavutil/internal.h" #include "libavutil/mathematics.h" #include "libavutil/opt.h" #include "libavutil/time_internal.h" #include "avformat.h" #include "avio_internal.h" #include "avlanguage.h" #include "id3v2.h" #include "internal.h" #include "riff.h" #include "asf.h" #include "asfcrypt.h" #define ASF_BOOL 0x2 #define ASF_WORD 0x5 #define ASF_GUID 0x6 #define ASF_DWORD 0x3 #define ASF_QWORD 0x4 #define ASF_UNICODE 0x0 #define ASF_FLAG_BROADCAST 0x1 #define ASF_BYTE_ARRAY 0x1 #define ASF_TYPE_AUDIO 0x2 #define ASF_TYPE_VIDEO 0x1 #define ASF_STREAM_NUM 0x7F #define ASF_MAX_STREAMS 128 #define BMP_HEADER_SIZE 40 #define ASF_NUM_OF_PAYLOADS 0x3F #define ASF_ERROR_CORRECTION_LENGTH_TYPE 0x60 #define ASF_PACKET_ERROR_CORRECTION_DATA_SIZE 0x2 typedef struct GUIDParseTable { const char *name; ff_asf_guid guid; int (*read_object)(AVFormatContext *, const struct GUIDParseTable *); int is_subobject; } GUIDParseTable; typedef struct ASFPacket { AVPacket avpkt; int64_t dts; uint32_t frame_num; // ASF payloads with the same number are parts of the same frame int flags; int data_size; int duration; int size_left; uint8_t stream_index; } ASFPacket; typedef struct ASFStream { uint8_t stream_index; // from packet header int index; // stream index in AVFormatContext, set in asf_read_stream_properties int type; int indexed; // added index entries from the Simple Index Object or not int8_t span; // for deinterleaving uint16_t virtual_pkt_len; uint16_t virtual_chunk_len; int16_t lang_idx; ASFPacket pkt; } ASFStream; typedef struct ASFStreamData{ char langs[32]; AVDictionary *asf_met; // for storing per-stream metadata AVRational aspect_ratio; } ASFStreamData; typedef struct ASFContext { int data_reached; int is_simple_index; // is simple index present or not 1/0 int is_header; uint64_t preroll; uint64_t nb_packets; // ASF packets uint32_t packet_size; int64_t send_time; int duration; uint32_t b_flags; // flags with broadcast flag uint32_t prop_flags; // file properties object flags uint64_t data_size; // data object size uint64_t unknown_size; // size of the unknown object int64_t offset; // offset of the current object int64_t data_offset; int64_t first_packet_offset; // packet offset int64_t unknown_offset; // for top level header objects or subobjects without specified behavior // ASF file must not contain more than 128 streams according to the specification ASFStream *asf_st[ASF_MAX_STREAMS]; ASFStreamData asf_sd[ASF_MAX_STREAMS]; int nb_streams; int stream_index; // from packet header, for the subpayload case // packet parameters uint64_t sub_header_offset; // offset of subpayload header int64_t sub_dts; uint8_t dts_delta; // for subpayloads uint32_t packet_size_internal; // packet size stored inside ASFPacket, can be 0 int64_t packet_offset; // offset of the current packet inside Data Object uint32_t pad_len; // padding after payload uint32_t rep_data_len; // packet state uint64_t sub_left; // subpayloads left or not unsigned int nb_sub; // number of subpayloads read so far from the current ASF packet uint16_t mult_sub_len; // total length of subpayloads array inside multiple payload uint64_t nb_mult_left; // multiple payloads left int return_subpayload; enum { PARSE_PACKET_HEADER, READ_SINGLE, READ_MULTI, READ_MULTI_SUB } state; } ASFContext; static int detect_unknown_subobject(AVFormatContext *s, int64_t offset, int64_t size); static const GUIDParseTable *find_guid(ff_asf_guid guid); static int asf_probe(AVProbeData *pd) { /* check file header */ if (!ff_guidcmp(pd->buf, &ff_asf_header)) return AVPROBE_SCORE_MAX/2; else return 0; } static void swap_guid(ff_asf_guid guid) { FFSWAP(unsigned char, guid[0], guid[3]); FFSWAP(unsigned char, guid[1], guid[2]); FFSWAP(unsigned char, guid[4], guid[5]); FFSWAP(unsigned char, guid[6], guid[7]); } static void align_position(AVIOContext *pb, int64_t offset, uint64_t size) { if (size < INT64_MAX - offset && avio_tell(pb) != offset + size) avio_seek(pb, offset + size, SEEK_SET); } static int asf_read_unknown(AVFormatContext *s, const GUIDParseTable *g) { ASFContext *asf = s->priv_data; AVIOContext *pb = s->pb; uint64_t size = avio_rl64(pb); int ret; if (size > INT64_MAX) return AVERROR_INVALIDDATA; if (asf->is_header) asf->unknown_size = size; asf->is_header = 0; if (!g->is_subobject) { if (!(ret = strcmp(g->name, "Header Extension"))) avio_skip(pb, 22); // skip reserved fields and Data Size if ((ret = detect_unknown_subobject(s, asf->unknown_offset, asf->unknown_size)) < 0) return ret; } else { if (size < 24) { av_log(s, AV_LOG_ERROR, "Too small size %"PRIu64" (< 24).\n", size); return AVERROR_INVALIDDATA; } avio_skip(pb, size - 24); } return 0; } static int get_asf_string(AVIOContext *pb, int maxlen, char *buf, int buflen) { char *q = buf; int ret = 0; if (buflen <= 0) return AVERROR(EINVAL); while (ret + 1 < maxlen) { uint8_t tmp; uint32_t ch; GET_UTF16(ch, (ret += 2) <= maxlen ? avio_rl16(pb) : 0, break;); PUT_UTF8(ch, tmp, if (q - buf < buflen - 1) *q++ = tmp;) } *q = 0; return ret; } static int asf_read_marker(AVFormatContext *s, const GUIDParseTable *g) { ASFContext *asf = s->priv_data; AVIOContext *pb = s->pb; uint64_t size = avio_rl64(pb); int i, nb_markers, ret; size_t len; char name[1024]; avio_skip(pb, 8); avio_skip(pb, 8); // skip reserved GUID nb_markers = avio_rl32(pb); avio_skip(pb, 2); // skip reserved field len = avio_rl16(pb); for (i = 0; i < len; i++) avio_skip(pb, 1); for (i = 0; i < nb_markers; i++) { int64_t pts; avio_skip(pb, 8); pts = avio_rl64(pb); pts -= asf->preroll * 10000; avio_skip(pb, 2); // entry length avio_skip(pb, 4); // send time avio_skip(pb, 4); // flags len = avio_rl32(pb); if ((ret = avio_get_str16le(pb, len, name, sizeof(name))) < len) avio_skip(pb, len - ret); avpriv_new_chapter(s, i, (AVRational) { 1, 10000000 }, pts, AV_NOPTS_VALUE, name); } align_position(pb, asf->offset, size); return 0; } static int asf_read_metadata(AVFormatContext *s, const char *title, uint16_t len, unsigned char *ch, uint16_t buflen) { AVIOContext *pb = s->pb; avio_get_str16le(pb, len, ch, buflen); if (ch[0]) { if (av_dict_set(&s->metadata, title, ch, 0) < 0) av_log(s, AV_LOG_WARNING, "av_dict_set failed.\n"); } return 0; } static int asf_read_value(AVFormatContext *s, const uint8_t *name, uint16_t val_len, int type, AVDictionary **met) { int ret; uint8_t *value; uint16_t buflen = 2 * val_len + 1; AVIOContext *pb = s->pb; value = av_malloc(buflen); if (!value) return AVERROR(ENOMEM); if (type == ASF_UNICODE) { // get_asf_string reads UTF-16 and converts it to UTF-8 which needs longer buffer if ((ret = get_asf_string(pb, val_len, value, buflen)) < 0) goto failed; if (av_dict_set(met, name, value, 0) < 0) av_log(s, AV_LOG_WARNING, "av_dict_set failed.\n"); } else { char buf[256]; if (val_len > sizeof(buf)) { ret = AVERROR_INVALIDDATA; goto failed; } if ((ret = avio_read(pb, value, val_len)) < 0) goto failed; if (ret < 2 * val_len) value[ret] = '\0'; else value[2 * val_len - 1] = '\0'; snprintf(buf, sizeof(buf), "%s", value); if (av_dict_set(met, name, buf, 0) < 0) av_log(s, AV_LOG_WARNING, "av_dict_set failed.\n"); } av_freep(&value); return 0; failed: av_freep(&value); return ret; } static int asf_read_generic_value(AVIOContext *pb, int type, uint64_t *value) { switch (type) { case ASF_BOOL: *value = avio_rl16(pb); break; case ASF_DWORD: *value = avio_rl32(pb); break; case ASF_QWORD: *value = avio_rl64(pb); break; case ASF_WORD: *value = avio_rl16(pb); break; default: return AVERROR_INVALIDDATA; } return 0; } static int asf_set_metadata(AVFormatContext *s, const uint8_t *name, int type, AVDictionary **met) { AVIOContext *pb = s->pb; uint64_t value; char buf[32]; int ret; ret = asf_read_generic_value(pb, type, &value); if (ret < 0) return ret; snprintf(buf, sizeof(buf), "%"PRIu64, value); if (av_dict_set(met, name, buf, 0) < 0) av_log(s, AV_LOG_WARNING, "av_dict_set failed.\n"); return 0; } /* MSDN claims that this should be "compatible with the ID3 frame, APIC", * but in reality this is only loosely similar */ static int asf_read_picture(AVFormatContext *s, int len) { ASFContext *asf = s->priv_data; AVPacket pkt = { 0 }; const CodecMime *mime = ff_id3v2_mime_tags; enum AVCodecID id = AV_CODEC_ID_NONE; char mimetype[64]; uint8_t *desc = NULL; AVStream *st = NULL; int ret, type, picsize, desc_len; ASFStream *asf_st; /* type + picsize + mime + desc */ if (len < 1 + 4 + 2 + 2) { av_log(s, AV_LOG_ERROR, "Invalid attached picture size: %d.\n", len); return AVERROR_INVALIDDATA; } /* picture type */ type = avio_r8(s->pb); len--; if (type >= FF_ARRAY_ELEMS(ff_id3v2_picture_types) || type < 0) { av_log(s, AV_LOG_WARNING, "Unknown attached picture type: %d.\n", type); type = 0; } /* picture data size */ picsize = avio_rl32(s->pb); len -= 4; /* picture MIME type */ len -= avio_get_str16le(s->pb, len, mimetype, sizeof(mimetype)); while (mime->id != AV_CODEC_ID_NONE) { if (!strncmp(mime->str, mimetype, sizeof(mimetype))) { id = mime->id; break; } mime++; } if (id == AV_CODEC_ID_NONE) { av_log(s, AV_LOG_ERROR, "Unknown attached picture mimetype: %s.\n", mimetype); return 0; } if (picsize >= len) { av_log(s, AV_LOG_ERROR, "Invalid attached picture data size: %d >= %d.\n", picsize, len); return AVERROR_INVALIDDATA; } /* picture description */ desc_len = (len - picsize) * 2 + 1; desc = av_malloc(desc_len); if (!desc) return AVERROR(ENOMEM); len -= avio_get_str16le(s->pb, len - picsize, desc, desc_len); ret = av_get_packet(s->pb, &pkt, picsize); if (ret < 0) goto fail; st = avformat_new_stream(s, NULL); if (!st) { ret = AVERROR(ENOMEM); goto fail; } asf->asf_st[asf->nb_streams] = av_mallocz(sizeof(*asf_st)); asf_st = asf->asf_st[asf->nb_streams]; if (!asf_st) { ret = AVERROR(ENOMEM); goto fail; } st->disposition |= AV_DISPOSITION_ATTACHED_PIC; st->codecpar->codec_type = asf_st->type = AVMEDIA_TYPE_VIDEO; st->codecpar->codec_id = id; st->attached_pic = pkt; st->attached_pic.stream_index = asf_st->index = st->index; st->attached_pic.flags |= AV_PKT_FLAG_KEY; asf->nb_streams++; if (*desc) { if (av_dict_set(&st->metadata, "title", desc, AV_DICT_DONT_STRDUP_VAL) < 0) av_log(s, AV_LOG_WARNING, "av_dict_set failed.\n"); } else av_freep(&desc); if (av_dict_set(&st->metadata, "comment", ff_id3v2_picture_types[type], 0) < 0) av_log(s, AV_LOG_WARNING, "av_dict_set failed.\n"); return 0; fail: av_freep(&desc); av_packet_unref(&pkt); return ret; } static void get_id3_tag(AVFormatContext *s, int len) { ID3v2ExtraMeta *id3v2_extra_meta = NULL; ff_id3v2_read(s, ID3v2_DEFAULT_MAGIC, &id3v2_extra_meta, len); if (id3v2_extra_meta) ff_id3v2_parse_apic(s, &id3v2_extra_meta); ff_id3v2_free_extra_meta(&id3v2_extra_meta); } static int process_metadata(AVFormatContext *s, const uint8_t *name, uint16_t name_len, uint16_t val_len, uint16_t type, AVDictionary **met) { int ret; ff_asf_guid guid; if (val_len) { switch (type) { case ASF_UNICODE: asf_read_value(s, name, val_len, type, met); break; case ASF_BYTE_ARRAY: if (!strcmp(name, "WM/Picture")) // handle cover art asf_read_picture(s, val_len); else if (!strcmp(name, "ID3")) // handle ID3 tag get_id3_tag(s, val_len); else asf_read_value(s, name, val_len, type, met); break; case ASF_GUID: ff_get_guid(s->pb, &guid); break; default: if ((ret = asf_set_metadata(s, name, type, met)) < 0) return ret; break; } } return 0; } static int asf_read_ext_content(AVFormatContext *s, const GUIDParseTable *g) { ASFContext *asf = s->priv_data; AVIOContext *pb = s->pb; uint64_t size = avio_rl64(pb); uint16_t nb_desc = avio_rl16(pb); int i, ret; for (i = 0; i < nb_desc; i++) { uint16_t name_len, type, val_len; uint8_t *name = NULL; name_len = avio_rl16(pb); if (!name_len) return AVERROR_INVALIDDATA; name = av_malloc(name_len); if (!name) return AVERROR(ENOMEM); avio_get_str16le(pb, name_len, name, name_len); type = avio_rl16(pb); // BOOL values are 16 bits long in the Metadata Object // but 32 bits long in the Extended Content Description Object if (type == ASF_BOOL) type = ASF_DWORD; val_len = avio_rl16(pb); ret = process_metadata(s, name, name_len, val_len, type, &s->metadata); av_freep(&name); if (ret < 0) return ret; } align_position(pb, asf->offset, size); return 0; } static AVStream *find_stream(AVFormatContext *s, uint16_t st_num) { AVStream *st = NULL; ASFContext *asf = s->priv_data; int i; for (i = 0; i < asf->nb_streams; i++) { if (asf->asf_st[i]->stream_index == st_num) { st = s->streams[asf->asf_st[i]->index]; break; } } return st; } static int asf_store_aspect_ratio(AVFormatContext *s, uint8_t st_num, uint8_t *name, int type) { ASFContext *asf = s->priv_data; AVIOContext *pb = s->pb; uint64_t value = 0; int ret; ret = asf_read_generic_value(pb, type, &value); if (ret < 0) return ret; if (st_num < ASF_MAX_STREAMS) { if (!strcmp(name, "AspectRatioX")) asf->asf_sd[st_num].aspect_ratio.num = value; else asf->asf_sd[st_num].aspect_ratio.den = value; } return 0; } static int asf_read_metadata_obj(AVFormatContext *s, const GUIDParseTable *g) { ASFContext *asf = s->priv_data; AVIOContext *pb = s->pb; uint64_t size = avio_rl64(pb); uint16_t nb_recs = avio_rl16(pb); // number of records in the Description Records list int i, ret; for (i = 0; i < nb_recs; i++) { uint16_t name_len, buflen, type, val_len, st_num; uint8_t *name = NULL; avio_skip(pb, 2); // skip reserved field st_num = avio_rl16(pb); name_len = avio_rl16(pb); buflen = 2 * name_len + 1; if (!name_len) break; type = avio_rl16(pb); val_len = avio_rl32(pb); name = av_malloc(buflen); if (!name) return AVERROR(ENOMEM); avio_get_str16le(pb, name_len, name, buflen); if (!strcmp(name, "AspectRatioX") || !strcmp(name, "AspectRatioY")) { ret = asf_store_aspect_ratio(s, st_num, name, type); if (ret < 0) { av_freep(&name); break; } } else { if (st_num < ASF_MAX_STREAMS) { if ((ret = process_metadata(s, name, name_len, val_len, type, &asf->asf_sd[st_num].asf_met)) < 0) { av_freep(&name); break; } } } av_freep(&name); } align_position(pb, asf->offset, size); return 0; } static int asf_read_content_desc(AVFormatContext *s, const GUIDParseTable *g) { ASFContext *asf = s->priv_data; AVIOContext *pb = s->pb; int i; static const char *const titles[] = { "Title", "Author", "Copyright", "Description", "Rate" }; uint16_t len[5], buflen[5] = { 0 }; uint8_t *ch; uint64_t size = avio_rl64(pb); for (i = 0; i < 5; i++) { len[i] = avio_rl16(pb); // utf8 string should be <= 2 * utf16 string, extra byte for the terminator buflen[i] = 2 * len[i] + 1; } for (i = 0; i < 5; i++) { ch = av_malloc(buflen[i]); if (!ch) return(AVERROR(ENOMEM)); asf_read_metadata(s, titles[i], len[i], ch, buflen[i]); av_freep(&ch); } align_position(pb, asf->offset, size); return 0; } static int asf_read_properties(AVFormatContext *s, const GUIDParseTable *g) { ASFContext *asf = s->priv_data; AVIOContext *pb = s->pb; time_t creation_time; avio_rl64(pb); // read object size avio_skip(pb, 16); // skip File ID avio_skip(pb, 8); // skip File size creation_time = avio_rl64(pb); if (!(asf->b_flags & ASF_FLAG_BROADCAST)) { struct tm tmbuf; struct tm *tm; char buf[64]; // creation date is in 100 ns units from 1 Jan 1601, conversion to s creation_time /= 10000000; // there are 11644473600 seconds between 1 Jan 1601 and 1 Jan 1970 creation_time -= 11644473600; tm = gmtime_r(&creation_time, &tmbuf); if (tm) { if (!strftime(buf, sizeof(buf), "%Y-%m-%d %H:%M:%S", tm)) buf[0] = '\0'; } else buf[0] = '\0'; if (buf[0]) { if (av_dict_set(&s->metadata, "creation_time", buf, 0) < 0) av_log(s, AV_LOG_WARNING, "av_dict_set failed.\n"); } } asf->nb_packets = avio_rl64(pb); asf->duration = avio_rl64(pb) / 10000; // stream duration avio_skip(pb, 8); // skip send duration asf->preroll = avio_rl64(pb); asf->duration -= asf->preroll; asf->b_flags = avio_rl32(pb); avio_skip(pb, 4); // skip minimal packet size asf->packet_size = avio_rl32(pb); avio_skip(pb, 4); // skip max_bitrate return 0; } static int parse_video_info(AVIOContext *pb, AVStream *st) { uint16_t size; unsigned int tag; st->codecpar->width = avio_rl32(pb); st->codecpar->height = avio_rl32(pb); avio_skip(pb, 1); // skip reserved flags size = avio_rl16(pb); // size of the Format Data tag = ff_get_bmp_header(pb, st, NULL); st->codecpar->codec_tag = tag; st->codecpar->codec_id = ff_codec_get_id(ff_codec_bmp_tags, tag); if (size > BMP_HEADER_SIZE) { int ret; st->codecpar->extradata_size = size - BMP_HEADER_SIZE; if (!(st->codecpar->extradata = av_malloc(st->codecpar->extradata_size + AV_INPUT_BUFFER_PADDING_SIZE))) { st->codecpar->extradata_size = 0; return AVERROR(ENOMEM); } memset(st->codecpar->extradata + st->codecpar->extradata_size , 0, AV_INPUT_BUFFER_PADDING_SIZE); if ((ret = avio_read(pb, st->codecpar->extradata, st->codecpar->extradata_size)) < 0) return ret; } return 0; } static int asf_read_stream_properties(AVFormatContext *s, const GUIDParseTable *g) { ASFContext *asf = s->priv_data; AVIOContext *pb = s->pb; uint64_t size; uint32_t err_data_len, ts_data_len; // type specific data length uint16_t flags; ff_asf_guid stream_type; enum AVMediaType type; int i, ret; uint8_t stream_index; AVStream *st; ASFStream *asf_st; // ASF file must not contain more than 128 streams according to the specification if (asf->nb_streams >= ASF_MAX_STREAMS) return AVERROR_INVALIDDATA; size = avio_rl64(pb); ff_get_guid(pb, &stream_type); if (!ff_guidcmp(&stream_type, &ff_asf_audio_stream)) type = AVMEDIA_TYPE_AUDIO; else if (!ff_guidcmp(&stream_type, &ff_asf_video_stream)) type = AVMEDIA_TYPE_VIDEO; else if (!ff_guidcmp(&stream_type, &ff_asf_jfif_media)) type = AVMEDIA_TYPE_VIDEO; else if (!ff_guidcmp(&stream_type, &ff_asf_command_stream)) type = AVMEDIA_TYPE_DATA; else if (!ff_guidcmp(&stream_type, &ff_asf_ext_stream_embed_stream_header)) type = AVMEDIA_TYPE_UNKNOWN; else return AVERROR_INVALIDDATA; ff_get_guid(pb, &stream_type); // error correction type avio_skip(pb, 8); // skip the time offset ts_data_len = avio_rl32(pb); err_data_len = avio_rl32(pb); flags = avio_rl16(pb); // bit 15 - Encrypted Content stream_index = flags & ASF_STREAM_NUM; for (i = 0; i < asf->nb_streams; i++) if (stream_index == asf->asf_st[i]->stream_index) { av_log(s, AV_LOG_WARNING, "Duplicate stream found, this stream will be ignored.\n"); align_position(pb, asf->offset, size); return 0; } st = avformat_new_stream(s, NULL); if (!st) return AVERROR(ENOMEM); avpriv_set_pts_info(st, 32, 1, 1000); // pts should be dword, in milliseconds st->codecpar->codec_type = type; asf->asf_st[asf->nb_streams] = av_mallocz(sizeof(*asf_st)); if (!asf->asf_st[asf->nb_streams]) return AVERROR(ENOMEM); asf_st = asf->asf_st[asf->nb_streams]; asf->nb_streams++; asf_st->stream_index = stream_index; asf_st->index = st->index; asf_st->indexed = 0; st->id = flags & ASF_STREAM_NUM; av_init_packet(&asf_st->pkt.avpkt); asf_st->pkt.data_size = 0; avio_skip(pb, 4); // skip reserved field switch (type) { case AVMEDIA_TYPE_AUDIO: asf_st->type = AVMEDIA_TYPE_AUDIO; if ((ret = ff_get_wav_header(s, pb, st->codecpar, ts_data_len, 0)) < 0) return ret; break; case AVMEDIA_TYPE_VIDEO: asf_st->type = AVMEDIA_TYPE_VIDEO; if ((ret = parse_video_info(pb, st)) < 0) return ret; break; default: avio_skip(pb, ts_data_len); break; } if (err_data_len) { if (type == AVMEDIA_TYPE_AUDIO) { uint8_t span = avio_r8(pb); if (span > 1) { asf_st->span = span; asf_st->virtual_pkt_len = avio_rl16(pb); asf_st->virtual_chunk_len = avio_rl16(pb); if (!asf_st->virtual_chunk_len || !asf_st->virtual_pkt_len) return AVERROR_INVALIDDATA; avio_skip(pb, err_data_len - 5); } else avio_skip(pb, err_data_len - 1); } else avio_skip(pb, err_data_len); } align_position(pb, asf->offset, size); return 0; } static void set_language(AVFormatContext *s, const char *rfc1766, AVDictionary **met) { // language abbr should contain at least 2 chars if (rfc1766 && strlen(rfc1766) > 1) { const char primary_tag[3] = { rfc1766[0], rfc1766[1], '\0' }; // ignore country code if any const char *iso6392 = ff_convert_lang_to(primary_tag, AV_LANG_ISO639_2_BIBL); if (iso6392) if (av_dict_set(met, "language", iso6392, 0) < 0) av_log(s, AV_LOG_WARNING, "av_dict_set failed.\n"); } } static int asf_read_ext_stream_properties(AVFormatContext *s, const GUIDParseTable *g) { ASFContext *asf = s->priv_data; AVIOContext *pb = s->pb; AVStream *st = NULL; ff_asf_guid guid; uint16_t nb_st_name, nb_pay_exts, st_num, lang_idx; int i, ret; uint32_t bitrate; uint64_t start_time, end_time, time_per_frame; uint64_t size = avio_rl64(pb); start_time = avio_rl64(pb); end_time = avio_rl64(pb); bitrate = avio_rl32(pb); avio_skip(pb, 28); // skip some unused values st_num = avio_rl16(pb); st_num &= ASF_STREAM_NUM; lang_idx = avio_rl16(pb); // Stream Language ID Index for (i = 0; i < asf->nb_streams; i++) { if (st_num == asf->asf_st[i]->stream_index) { st = s->streams[asf->asf_st[i]->index]; asf->asf_st[i]->lang_idx = lang_idx; break; } } time_per_frame = avio_rl64(pb); // average time per frame if (st) { st->start_time = start_time; st->duration = end_time - start_time; st->codecpar->bit_rate = bitrate; st->avg_frame_rate.num = 10000000; st->avg_frame_rate.den = time_per_frame; } nb_st_name = avio_rl16(pb); nb_pay_exts = avio_rl16(pb); for (i = 0; i < nb_st_name; i++) { uint16_t len; avio_rl16(pb); // Language ID Index len = avio_rl16(pb); avio_skip(pb, len); } for (i = 0; i < nb_pay_exts; i++) { uint32_t len; avio_skip(pb, 16); // Extension System ID avio_skip(pb, 2); // Extension Data Size len = avio_rl32(pb); avio_skip(pb, len); } if ((ret = ff_get_guid(pb, &guid)) < 0) { align_position(pb, asf->offset, size); return 0; } g = find_guid(guid); if (g && !(strcmp(g->name, "Stream Properties"))) { if ((ret = g->read_object(s, g)) < 0) return ret; } align_position(pb, asf->offset, size); return 0; } static int asf_read_language_list(AVFormatContext *s, const GUIDParseTable *g) { ASFContext *asf = s->priv_data; AVIOContext *pb = s->pb; int i, ret; uint64_t size = avio_rl64(pb); uint16_t nb_langs = avio_rl16(pb); if (nb_langs < ASF_MAX_STREAMS) { for (i = 0; i < nb_langs; i++) { size_t len; len = avio_r8(pb); if (!len) len = 6; if ((ret = get_asf_string(pb, len, asf->asf_sd[i].langs, sizeof(asf->asf_sd[i].langs))) < 0) { return ret; } } } align_position(pb, asf->offset, size); return 0; } // returns data object offset when reading this object for the first time static int asf_read_data(AVFormatContext *s, const GUIDParseTable *g) { ASFContext *asf = s->priv_data; AVIOContext *pb = s->pb; uint64_t size = asf->data_size = avio_rl64(pb); int i; if (!asf->data_reached) { asf->data_reached = 1; asf->data_offset = asf->offset; } for (i = 0; i < asf->nb_streams; i++) { if (!(asf->b_flags & ASF_FLAG_BROADCAST)) s->streams[i]->duration = asf->duration; } asf->nb_mult_left = 0; asf->sub_left = 0; asf->state = PARSE_PACKET_HEADER; asf->return_subpayload = 0; asf->packet_size_internal = 0; avio_skip(pb, 16); // skip File ID size = avio_rl64(pb); // Total Data Packets if (size != asf->nb_packets) av_log(s, AV_LOG_WARNING, "Number of Packets from File Properties Object is not equal to Total" "Datapackets value! num of packets %"PRIu64" total num %"PRIu64".\n", size, asf->nb_packets); avio_skip(pb, 2); // skip reserved field asf->first_packet_offset = avio_tell(pb); if ((pb->seekable & AVIO_SEEKABLE_NORMAL) && !(asf->b_flags & ASF_FLAG_BROADCAST)) align_position(pb, asf->offset, asf->data_size); return 0; } static int asf_read_simple_index(AVFormatContext *s, const GUIDParseTable *g) { ASFContext *asf = s->priv_data; AVIOContext *pb = s->pb; AVStream *st = NULL; uint64_t interval; // index entry time interval in 100 ns units, usually it's 1s uint32_t pkt_num, nb_entries; int32_t prev_pkt_num = -1; int i, ret; uint64_t size = avio_rl64(pb); // simple index objects should be ordered by stream number, this loop tries to find // the first not indexed video stream for (i = 0; i < asf->nb_streams; i++) { if ((asf->asf_st[i]->type == AVMEDIA_TYPE_VIDEO) && !asf->asf_st[i]->indexed) { asf->asf_st[i]->indexed = 1; st = s->streams[asf->asf_st[i]->index]; break; } } if (!st) { avio_skip(pb, size - 24); // if there's no video stream, skip index object return 0; } avio_skip(pb, 16); // skip File ID interval = avio_rl64(pb); avio_skip(pb, 4); nb_entries = avio_rl32(pb); for (i = 0; i < nb_entries; i++) { pkt_num = avio_rl32(pb); ret = avio_skip(pb, 2); if (ret < 0) { av_log(s, AV_LOG_ERROR, "Skipping failed in asf_read_simple_index.\n"); return ret; } if (prev_pkt_num != pkt_num) { av_add_index_entry(st, asf->first_packet_offset + asf->packet_size * pkt_num, av_rescale(interval, i, 10000), asf->packet_size, 0, AVINDEX_KEYFRAME); prev_pkt_num = pkt_num; } } asf->is_simple_index = 1; align_position(pb, asf->offset, size); return 0; } static const GUIDParseTable gdef[] = { { "Data", { 0x75, 0xB2, 0x26, 0x36, 0x66, 0x8E, 0x11, 0xCF, 0xA6, 0xD9, 0x00, 0xAA, 0x00, 0x62, 0xCE, 0x6C }, asf_read_data, 1 }, { "Simple Index", { 0x33, 0x00, 0x08, 0x90, 0xE5, 0xB1, 0x11, 0xCF, 0x89, 0xF4, 0x00, 0xA0, 0xC9, 0x03, 0x49, 0xCB }, asf_read_simple_index, 1 }, { "Content Description", { 0x75, 0xB2, 0x26, 0x33, 0x66 ,0x8E, 0x11, 0xCF, 0xA6, 0xD9, 0x00, 0xAA, 0x00, 0x62, 0xCE, 0x6C }, asf_read_content_desc, 1 }, { "Extended Content Description", { 0xD2, 0xD0, 0xA4, 0x40, 0xE3, 0x07, 0x11, 0xD2, 0x97, 0xF0, 0x00, 0xA0, 0xC9, 0x5e, 0xA8, 0x50 }, asf_read_ext_content, 1 }, { "Stream Bitrate Properties", { 0x7B, 0xF8, 0x75, 0xCE, 0x46, 0x8D, 0x11, 0xD1, 0x8D, 0x82, 0x00, 0x60, 0x97, 0xC9, 0xA2, 0xB2 }, asf_read_unknown, 1 }, { "File Properties", { 0x8C, 0xAB, 0xDC, 0xA1, 0xA9, 0x47, 0x11, 0xCF, 0x8E, 0xE4, 0x00, 0xC0, 0x0C, 0x20, 0x53, 0x65 }, asf_read_properties, 1 }, { "Header Extension", { 0x5F, 0xBF, 0x03, 0xB5, 0xA9, 0x2E, 0x11, 0xCF, 0x8E, 0xE3, 0x00, 0xC0, 0x0C, 0x20, 0x53, 0x65 }, asf_read_unknown, 0 }, { "Stream Properties", { 0xB7, 0xDC, 0x07, 0x91, 0xA9, 0xB7, 0x11, 0xCF, 0x8E, 0xE6, 0x00, 0xC0, 0x0C, 0x20, 0x53, 0x65 }, asf_read_stream_properties, 1 }, { "Codec List", { 0x86, 0xD1, 0x52, 0x40, 0x31, 0x1D, 0x11, 0xD0, 0xA3, 0xA4, 0x00, 0xA0, 0xC9, 0x03, 0x48, 0xF6 }, asf_read_unknown, 1 }, { "Marker", { 0xF4, 0x87, 0xCD, 0x01, 0xA9, 0x51, 0x11, 0xCF, 0x8E, 0xE6, 0x00, 0xC0, 0x0C, 0x20, 0x53, 0x65 }, asf_read_marker, 1 }, { "Script Command", { 0x1E, 0xFB, 0x1A, 0x30, 0x0B, 0x62, 0x11, 0xD0, 0xA3, 0x9B, 0x00, 0xA0, 0xC9, 0x03, 0x48, 0xF6 }, asf_read_unknown, 1 }, { "Language List", { 0x7C, 0x43, 0x46, 0xa9, 0xef, 0xe0, 0x4B, 0xFC, 0xB2, 0x29, 0x39, 0x3e, 0xde, 0x41, 0x5c, 0x85 }, asf_read_language_list, 1}, { "Padding", { 0x18, 0x06, 0xD4, 0x74, 0xCA, 0xDF, 0x45, 0x09, 0xA4, 0xBA, 0x9A, 0xAB, 0xCB, 0x96, 0xAA, 0xE8 }, asf_read_unknown, 1 }, { "DRMv1 Header", { 0x22, 0x11, 0xB3, 0xFB, 0xBD, 0x23, 0x11, 0xD2, 0xB4, 0xB7, 0x00, 0xA0, 0xC9, 0x55, 0xFC, 0x6E }, asf_read_unknown, 1 }, { "DRMv2 Header", { 0x29, 0x8A, 0xE6, 0x14, 0x26, 0x22, 0x4C, 0x17, 0xB9, 0x35, 0xDA, 0xE0, 0x7E, 0xE9, 0x28, 0x9c }, asf_read_unknown, 1 }, { "Index", { 0xD6, 0xE2, 0x29, 0xD3, 0x35, 0xDA, 0x11, 0xD1, 0x90, 0x34, 0x00, 0xA0, 0xC9, 0x03, 0x49, 0xBE }, asf_read_unknown, 1 }, { "Media Object Index", { 0xFE, 0xB1, 0x03, 0xF8, 0x12, 0xAD, 0x4C, 0x64, 0x84, 0x0F, 0x2A, 0x1D, 0x2F, 0x7A, 0xD4, 0x8C }, asf_read_unknown, 1 }, { "Timecode Index", { 0x3C, 0xB7, 0x3F, 0xD0, 0x0C, 0x4A, 0x48, 0x03, 0x95, 0x3D, 0xED, 0xF7, 0xB6, 0x22, 0x8F, 0x0C }, asf_read_unknown, 0 }, { "Bitrate_Mutual_Exclusion", { 0xD6, 0xE2, 0x29, 0xDC, 0x35, 0xDA, 0x11, 0xD1, 0x90, 0x34, 0x00, 0xA0, 0xC9, 0x03, 0x49, 0xBE }, asf_read_unknown, 1 }, { "Error Correction", { 0x75, 0xB2, 0x26, 0x35, 0x66, 0x8E, 0x11, 0xCF, 0xA6, 0xD9, 0x00, 0xAA, 0x00, 0x62, 0xCE, 0x6C }, asf_read_unknown, 1 }, { "Content Branding", { 0x22, 0x11, 0xB3, 0xFA, 0xBD, 0x23, 0x11, 0xD2, 0xB4, 0xB7, 0x00, 0xA0, 0xC9, 0x55, 0xFC, 0x6E }, asf_read_unknown, 1 }, { "Content Encryption", { 0x22, 0x11, 0xB3, 0xFB, 0xBD, 0x23, 0x11, 0xD2, 0xB4, 0xB7, 0x00, 0xA0, 0xC9, 0x55, 0xFC, 0x6E }, asf_read_unknown, 1 }, { "Extended Content Encryption", { 0x29, 0x8A, 0xE6, 0x14, 0x26, 0x22, 0x4C, 0x17, 0xB9, 0x35, 0xDA, 0xE0, 0x7E, 0xE9, 0x28, 0x9C }, asf_read_unknown, 1 }, { "Digital Signature", { 0x22, 0x11, 0xB3, 0xFC, 0xBD, 0x23, 0x11, 0xD2, 0xB4, 0xB7, 0x00, 0xA0, 0xC9, 0x55, 0xFC, 0x6E }, asf_read_unknown, 1 }, { "Extended Stream Properties", { 0x14, 0xE6, 0xA5, 0xCB, 0xC6, 0x72, 0x43, 0x32, 0x83, 0x99, 0xA9, 0x69, 0x52, 0x06, 0x5B, 0x5A }, asf_read_ext_stream_properties, 1 }, { "Advanced Mutual Exclusion", { 0xA0, 0x86, 0x49, 0xCF, 0x47, 0x75, 0x46, 0x70, 0x8A, 0x16, 0x6E, 0x35, 0x35, 0x75, 0x66, 0xCD }, asf_read_unknown, 1 }, { "Group Mutual Exclusion", { 0xD1, 0x46, 0x5A, 0x40, 0x5A, 0x79, 0x43, 0x38, 0xB7, 0x1B, 0xE3, 0x6B, 0x8F, 0xD6, 0xC2, 0x49 }, asf_read_unknown, 1}, { "Stream Prioritization", { 0xD4, 0xFE, 0xD1, 0x5B, 0x88, 0xD3, 0x45, 0x4F, 0x81, 0xF0, 0xED, 0x5C, 0x45, 0x99, 0x9E, 0x24 }, asf_read_unknown, 1 }, { "Bandwidth Sharing Object", { 0xA6, 0x96, 0x09, 0xE6, 0x51, 0x7B, 0x11, 0xD2, 0xB6, 0xAF, 0x00, 0xC0, 0x4F, 0xD9, 0x08, 0xE9 }, asf_read_unknown, 1 }, { "Metadata", { 0xC5, 0xF8, 0xCB, 0xEA, 0x5B, 0xAF, 0x48, 0x77, 0x84, 0x67, 0xAA, 0x8C, 0x44, 0xFA, 0x4C, 0xCA }, asf_read_metadata_obj, 1 }, { "Metadata Library", { 0x44, 0x23, 0x1C, 0x94, 0x94, 0x98, 0x49, 0xD1, 0xA1, 0x41, 0x1D, 0x13, 0x4E, 0x45, 0x70, 0x54 }, asf_read_metadata_obj, 1 }, { "Audio Spread", { 0xBF, 0xC3, 0xCD, 0x50, 0x61, 0x8F, 0x11, 0xCF, 0x8B, 0xB2, 0x00, 0xAA, 0x00, 0xB4, 0xE2, 0x20 }, asf_read_unknown, 1 }, { "Index Parameters", { 0xD6, 0xE2, 0x29, 0xDF, 0x35, 0xDA, 0x11, 0xD1, 0x90, 0x34, 0x00, 0xA0, 0xC9, 0x03, 0x49, 0xBE }, asf_read_unknown, 1 }, { "Content Encryption System Windows Media DRM Network Devices", { 0x7A, 0x07, 0x9B, 0xB6, 0xDA, 0XA4, 0x4e, 0x12, 0xA5, 0xCA, 0x91, 0xD3, 0x8D, 0xC1, 0x1A, 0x8D }, asf_read_unknown, 1 }, { "Mutex Language", { 0xD6, 0xE2, 0x2A, 0x00, 0x25, 0xDA, 0x11, 0xD1, 0x90, 0x34, 0x00, 0xA0, 0xC9, 0x03, 0x49, 0xBE }, asf_read_unknown, 1 }, { "Mutex Bitrate", { 0xD6, 0xE2, 0x2A, 0x01, 0x25, 0xDA, 0x11, 0xD1, 0x90, 0x34, 0x00, 0xA0, 0xC9, 0x03, 0x49, 0xBE }, asf_read_unknown, 1 }, { "Mutex Unknown", { 0xD6, 0xE2, 0x2A, 0x02, 0x25, 0xDA, 0x11, 0xD1, 0x90, 0x34, 0x00, 0xA0, 0xC9, 0x03, 0x49, 0xBE }, asf_read_unknown, 1 }, { "Bandwidth Sharing Exclusive", { 0xAF, 0x60, 0x60, 0xAA, 0x51, 0x97, 0x11, 0xD2, 0xB6, 0xAF, 0x00, 0xC0, 0x4F, 0xD9, 0x08, 0xE9 }, asf_read_unknown, 1 }, { "Bandwidth Sharing Partial", { 0xAF, 0x60, 0x60, 0xAB, 0x51, 0x97, 0x11, 0xD2, 0xB6, 0xAF, 0x00, 0xC0, 0x4F, 0xD9, 0x08, 0xE9 }, asf_read_unknown, 1 }, { "Payload Extension System Timecode", { 0x39, 0x95, 0x95, 0xEC, 0x86, 0x67, 0x4E, 0x2D, 0x8F, 0xDB, 0x98, 0x81, 0x4C, 0xE7, 0x6C, 0x1E }, asf_read_unknown, 1 }, { "Payload Extension System File Name", { 0xE1, 0x65, 0xEC, 0x0E, 0x19, 0xED, 0x45, 0xD7, 0xB4, 0xA7, 0x25, 0xCB, 0xD1, 0xE2, 0x8E, 0x9B }, asf_read_unknown, 1 }, { "Payload Extension System Content Type", { 0xD5, 0x90, 0xDC, 0x20, 0x07, 0xBC, 0x43, 0x6C, 0x9C, 0xF7, 0xF3, 0xBB, 0xFB, 0xF1, 0xA4, 0xDC }, asf_read_unknown, 1 }, { "Payload Extension System Pixel Aspect Ratio", { 0x1, 0x1E, 0xE5, 0x54, 0xF9, 0xEA, 0x4B, 0xC8, 0x82, 0x1A, 0x37, 0x6B, 0x74, 0xE4, 0xC4, 0xB8 }, asf_read_unknown, 1 }, { "Payload Extension System Sample Duration", { 0xC6, 0xBD, 0x94, 0x50, 0x86, 0x7F, 0x49, 0x07, 0x83, 0xA3, 0xC7, 0x79, 0x21, 0xB7, 0x33, 0xAD }, asf_read_unknown, 1 }, { "Payload Extension System Encryption Sample ID", { 0x66, 0x98, 0xB8, 0x4E, 0x0A, 0xFA, 0x43, 0x30, 0xAE, 0xB2, 0x1C, 0x0A, 0x98, 0xD7, 0xA4, 0x4D }, asf_read_unknown, 1 }, { "Payload Extension System Degradable JPEG", { 0x00, 0xE1, 0xAF, 0x06, 0x7B, 0xEC, 0x11, 0xD1, 0xA5, 0x82, 0x00, 0xC0, 0x4F, 0xC2, 0x9C, 0xFB }, asf_read_unknown, 1 }, }; #define READ_LEN(flag, name, len) \ do { \ if ((flag) == name ## IS_BYTE) \ len = avio_r8(pb); \ else if ((flag) == name ## IS_WORD) \ len = avio_rl16(pb); \ else if ((flag) == name ## IS_DWORD) \ len = avio_rl32(pb); \ else \ len = 0; \ } while(0) static int asf_read_subpayload(AVFormatContext *s, AVPacket *pkt, int is_header) { ASFContext *asf = s->priv_data; AVIOContext *pb = s->pb; uint8_t sub_len; int ret, i; if (is_header) { asf->dts_delta = avio_r8(pb); if (asf->nb_mult_left) { asf->mult_sub_len = avio_rl16(pb); // total } asf->sub_header_offset = avio_tell(pb); asf->nb_sub = 0; asf->sub_left = 1; } sub_len = avio_r8(pb); if ((ret = av_get_packet(pb, pkt, sub_len)) < 0) // each subpayload is entire frame return ret; for (i = 0; i < asf->nb_streams; i++) { if (asf->stream_index == asf->asf_st[i]->stream_index) { pkt->stream_index = asf->asf_st[i]->index; break; } } asf->return_subpayload = 1; if (!sub_len) asf->return_subpayload = 0; if (sub_len) asf->nb_sub++; pkt->dts = asf->sub_dts + (asf->nb_sub - 1) * asf->dts_delta - asf->preroll; if (asf->nb_mult_left && (avio_tell(pb) >= (asf->sub_header_offset + asf->mult_sub_len))) { asf->sub_left = 0; asf->nb_mult_left--; } if (avio_tell(pb) >= asf->packet_offset + asf->packet_size - asf->pad_len) { asf->sub_left = 0; if (!asf->nb_mult_left) { avio_skip(pb, asf->pad_len); if (avio_tell(pb) != asf->packet_offset + asf->packet_size) { if (!asf->packet_size) return AVERROR_INVALIDDATA; av_log(s, AV_LOG_WARNING, "Position %"PRId64" wrong, should be %"PRId64"\n", avio_tell(pb), asf->packet_offset + asf->packet_size); avio_seek(pb, asf->packet_offset + asf->packet_size, SEEK_SET); } } } return 0; } static void reset_packet(ASFPacket *asf_pkt) { asf_pkt->size_left = 0; asf_pkt->data_size = 0; asf_pkt->duration = 0; asf_pkt->flags = 0; asf_pkt->dts = 0; asf_pkt->duration = 0; av_packet_unref(&asf_pkt->avpkt); av_init_packet(&asf_pkt->avpkt); } static int asf_read_replicated_data(AVFormatContext *s, ASFPacket *asf_pkt) { ASFContext *asf = s->priv_data; AVIOContext *pb = s->pb; int ret, data_size; if (!asf_pkt->data_size) { data_size = avio_rl32(pb); // read media object size if (data_size <= 0) return AVERROR_INVALIDDATA; if ((ret = av_new_packet(&asf_pkt->avpkt, data_size)) < 0) return ret; asf_pkt->data_size = asf_pkt->size_left = data_size; } else avio_skip(pb, 4); // reading of media object size is already done asf_pkt->dts = avio_rl32(pb); // read presentation time if (asf->rep_data_len && (asf->rep_data_len >= 8)) avio_skip(pb, asf->rep_data_len - 8); // skip replicated data return 0; } static int asf_read_multiple_payload(AVFormatContext *s, AVPacket *pkt, ASFPacket *asf_pkt) { ASFContext *asf = s->priv_data; AVIOContext *pb = s->pb; uint16_t pay_len; unsigned char *p; int ret; int skip = 0; // if replicated length is 1, subpayloads are present if (asf->rep_data_len == 1) { asf->sub_left = 1; asf->state = READ_MULTI_SUB; pkt->flags = asf_pkt->flags; if ((ret = asf_read_subpayload(s, pkt, 1)) < 0) return ret; } else { if (asf->rep_data_len) if ((ret = asf_read_replicated_data(s, asf_pkt)) < 0) return ret; pay_len = avio_rl16(pb); // payload length should be WORD if (pay_len > asf->packet_size) { av_log(s, AV_LOG_ERROR, "Error: invalid data packet size, pay_len %"PRIu16", " "asf->packet_size %"PRIu32", offset %"PRId64".\n", pay_len, asf->packet_size, avio_tell(pb)); return AVERROR_INVALIDDATA; } p = asf_pkt->avpkt.data + asf_pkt->data_size - asf_pkt->size_left; if (pay_len > asf_pkt->size_left) { av_log(s, AV_LOG_ERROR, "Error: invalid buffer size, pay_len %d, data size left %d.\n", pay_len, asf_pkt->size_left); skip = pay_len - asf_pkt->size_left; pay_len = asf_pkt->size_left; } if (asf_pkt->size_left <= 0) return AVERROR_INVALIDDATA; if ((ret = avio_read(pb, p, pay_len)) < 0) return ret; if (s->key && s->keylen == 20) ff_asfcrypt_dec(s->key, p, ret); avio_skip(pb, skip); asf_pkt->size_left -= pay_len; asf->nb_mult_left--; } return 0; } static int asf_read_single_payload(AVFormatContext *s, ASFPacket *asf_pkt) { ASFContext *asf = s->priv_data; AVIOContext *pb = s->pb; int64_t offset; uint64_t size; unsigned char *p; int ret, data_size; if (!asf_pkt->data_size) { data_size = avio_rl32(pb); // read media object size if (data_size <= 0) return AVERROR_EOF; if ((ret = av_new_packet(&asf_pkt->avpkt, data_size)) < 0) return ret; asf_pkt->data_size = asf_pkt->size_left = data_size; } else avio_skip(pb, 4); // skip media object size asf_pkt->dts = avio_rl32(pb); // read presentation time if (asf->rep_data_len >= 8) avio_skip(pb, asf->rep_data_len - 8); // skip replicated data offset = avio_tell(pb); // size of the payload - size of the packet without header and padding if (asf->packet_size_internal) size = asf->packet_size_internal - offset + asf->packet_offset - asf->pad_len; else size = asf->packet_size - offset + asf->packet_offset - asf->pad_len; if (size > asf->packet_size) { av_log(s, AV_LOG_ERROR, "Error: invalid data packet size, offset %"PRId64".\n", avio_tell(pb)); return AVERROR_INVALIDDATA; } p = asf_pkt->avpkt.data + asf_pkt->data_size - asf_pkt->size_left; if (size > asf_pkt->size_left || asf_pkt->size_left <= 0) return AVERROR_INVALIDDATA; if (asf_pkt->size_left > size) asf_pkt->size_left -= size; else asf_pkt->size_left = 0; if ((ret = avio_read(pb, p, size)) < 0) return ret; if (s->key && s->keylen == 20) ff_asfcrypt_dec(s->key, p, ret); if (asf->packet_size_internal) avio_skip(pb, asf->packet_size - asf->packet_size_internal); avio_skip(pb, asf->pad_len); // skip padding return 0; } static int asf_read_payload(AVFormatContext *s, AVPacket *pkt) { ASFContext *asf = s->priv_data; AVIOContext *pb = s->pb; int ret, i; ASFPacket *asf_pkt = NULL; if (!asf->sub_left) { uint32_t off_len, media_len; uint8_t stream_num; stream_num = avio_r8(pb); asf->stream_index = stream_num & ASF_STREAM_NUM; for (i = 0; i < asf->nb_streams; i++) { if (asf->stream_index == asf->asf_st[i]->stream_index) { asf_pkt = &asf->asf_st[i]->pkt; asf_pkt->stream_index = asf->asf_st[i]->index; break; } } if (!asf_pkt) { if (asf->packet_offset + asf->packet_size <= asf->data_offset + asf->data_size) { if (!asf->packet_size) { av_log(s, AV_LOG_ERROR, "Invalid packet size 0.\n"); return AVERROR_INVALIDDATA; } avio_seek(pb, asf->packet_offset + asf->packet_size, SEEK_SET); av_log(s, AV_LOG_WARNING, "Skipping the stream with the invalid stream index %d.\n", asf->stream_index); return AVERROR(EAGAIN); } else return AVERROR_INVALIDDATA; } if (stream_num >> 7) asf_pkt->flags |= AV_PKT_FLAG_KEY; READ_LEN(asf->prop_flags & ASF_PL_MASK_MEDIA_OBJECT_NUMBER_LENGTH_FIELD_SIZE, ASF_PL_FLAG_MEDIA_OBJECT_NUMBER_LENGTH_FIELD_, media_len); READ_LEN(asf->prop_flags & ASF_PL_MASK_OFFSET_INTO_MEDIA_OBJECT_LENGTH_FIELD_SIZE, ASF_PL_FLAG_OFFSET_INTO_MEDIA_OBJECT_LENGTH_FIELD_, off_len); READ_LEN(asf->prop_flags & ASF_PL_MASK_REPLICATED_DATA_LENGTH_FIELD_SIZE, ASF_PL_FLAG_REPLICATED_DATA_LENGTH_FIELD_, asf->rep_data_len); if (asf_pkt->size_left && (asf_pkt->frame_num != media_len)) { av_log(s, AV_LOG_WARNING, "Unfinished frame will be ignored\n"); reset_packet(asf_pkt); } asf_pkt->frame_num = media_len; asf->sub_dts = off_len; if (asf->nb_mult_left) { if ((ret = asf_read_multiple_payload(s, pkt, asf_pkt)) < 0) return ret; } else if (asf->rep_data_len == 1) { asf->sub_left = 1; asf->state = READ_SINGLE; pkt->flags = asf_pkt->flags; if ((ret = asf_read_subpayload(s, pkt, 1)) < 0) return ret; } else { if ((ret = asf_read_single_payload(s, asf_pkt)) < 0) return ret; } } else { for (i = 0; i <= asf->nb_streams; i++) { if (asf->stream_index == asf->asf_st[i]->stream_index) { asf_pkt = &asf->asf_st[i]->pkt; break; } } if (!asf_pkt) return AVERROR_INVALIDDATA; pkt->flags = asf_pkt->flags; pkt->dts = asf_pkt->dts; pkt->stream_index = asf->asf_st[i]->index; if ((ret = asf_read_subpayload(s, pkt, 0)) < 0) // read subpayload without its header return ret; } return 0; } static int asf_read_packet_header(AVFormatContext *s) { ASFContext *asf = s->priv_data; AVIOContext *pb = s->pb; uint64_t size; uint32_t av_unused seq; unsigned char error_flags, len_flags, pay_flags; asf->packet_offset = avio_tell(pb); error_flags = avio_r8(pb); // read Error Correction Flags if (error_flags & ASF_PACKET_FLAG_ERROR_CORRECTION_PRESENT) { if (!(error_flags & ASF_ERROR_CORRECTION_LENGTH_TYPE)) { size = error_flags & ASF_PACKET_ERROR_CORRECTION_DATA_SIZE; avio_skip(pb, size); } len_flags = avio_r8(pb); } else len_flags = error_flags; asf->prop_flags = avio_r8(pb); READ_LEN(len_flags & ASF_PPI_MASK_PACKET_LENGTH_FIELD_SIZE, ASF_PPI_FLAG_PACKET_LENGTH_FIELD_, asf->packet_size_internal); READ_LEN(len_flags & ASF_PPI_MASK_SEQUENCE_FIELD_SIZE, ASF_PPI_FLAG_SEQUENCE_FIELD_, seq); READ_LEN(len_flags & ASF_PPI_MASK_PADDING_LENGTH_FIELD_SIZE, ASF_PPI_FLAG_PADDING_LENGTH_FIELD_, asf->pad_len ); asf->send_time = avio_rl32(pb); // send time avio_skip(pb, 2); // skip duration if (len_flags & ASF_PPI_FLAG_MULTIPLE_PAYLOADS_PRESENT) { // Multiple Payloads present pay_flags = avio_r8(pb); asf->nb_mult_left = (pay_flags & ASF_NUM_OF_PAYLOADS); } return 0; } static int asf_deinterleave(AVFormatContext *s, ASFPacket *asf_pkt, int st_num) { ASFContext *asf = s->priv_data; ASFStream *asf_st = asf->asf_st[st_num]; unsigned char *p = asf_pkt->avpkt.data; uint16_t pkt_len = asf->asf_st[st_num]->virtual_pkt_len; uint16_t chunk_len = asf->asf_st[st_num]->virtual_chunk_len; int nchunks = pkt_len / chunk_len; AVPacket pkt; int pos = 0, j, l, ret; if ((ret = av_new_packet(&pkt, asf_pkt->data_size)) < 0) return ret; while (asf_pkt->data_size >= asf_st->span * pkt_len + pos) { if (pos >= asf_pkt->data_size) { break; } for (l = 0; l < pkt_len; l++) { if (pos >= asf_pkt->data_size) { break; } for (j = 0; j < asf_st->span; j++) { if ((pos + chunk_len) >= asf_pkt->data_size) break; memcpy(pkt.data + pos, p + (j * nchunks + l) * chunk_len, chunk_len); pos += chunk_len; } } p += asf_st->span * pkt_len; if (p > asf_pkt->avpkt.data + asf_pkt->data_size) break; } av_packet_unref(&asf_pkt->avpkt); asf_pkt->avpkt = pkt; return 0; } static int asf_read_packet(AVFormatContext *s, AVPacket *pkt) { ASFContext *asf = s->priv_data; AVIOContext *pb = s->pb; int ret, i; if ((avio_tell(pb) >= asf->data_offset + asf->data_size) && !(asf->b_flags & ASF_FLAG_BROADCAST)) return AVERROR_EOF; while (!pb->eof_reached) { if (asf->state == PARSE_PACKET_HEADER) { asf_read_packet_header(s); if (pb->eof_reached) break; if (!asf->nb_mult_left) asf->state = READ_SINGLE; else asf->state = READ_MULTI; } ret = asf_read_payload(s, pkt); if (ret == AVERROR(EAGAIN)) { asf->state = PARSE_PACKET_HEADER; continue; } else if (ret < 0) return ret; switch (asf->state) { case READ_SINGLE: if (!asf->sub_left) asf->state = PARSE_PACKET_HEADER; break; case READ_MULTI_SUB: if (!asf->sub_left && !asf->nb_mult_left) { asf->state = PARSE_PACKET_HEADER; if (!asf->return_subpayload && (avio_tell(pb) <= asf->packet_offset + asf->packet_size - asf->pad_len)) avio_skip(pb, asf->pad_len); // skip padding if (asf->packet_offset + asf->packet_size > avio_tell(pb)) avio_seek(pb, asf->packet_offset + asf->packet_size, SEEK_SET); } else if (!asf->sub_left) asf->state = READ_MULTI; break; case READ_MULTI: if (!asf->nb_mult_left) { asf->state = PARSE_PACKET_HEADER; if (!asf->return_subpayload && (avio_tell(pb) <= asf->packet_offset + asf->packet_size - asf->pad_len)) avio_skip(pb, asf->pad_len); // skip padding if (asf->packet_offset + asf->packet_size > avio_tell(pb)) avio_seek(pb, asf->packet_offset + asf->packet_size, SEEK_SET); } break; } if (asf->return_subpayload) { asf->return_subpayload = 0; return 0; } for (i = 0; i < s->nb_streams; i++) { ASFPacket *asf_pkt = &asf->asf_st[i]->pkt; if (asf_pkt && !asf_pkt->size_left && asf_pkt->data_size) { if (asf->asf_st[i]->span > 1 && asf->asf_st[i]->type == AVMEDIA_TYPE_AUDIO) if ((ret = asf_deinterleave(s, asf_pkt, i)) < 0) return ret; av_packet_move_ref(pkt, &asf_pkt->avpkt); pkt->stream_index = asf->asf_st[i]->index; pkt->flags = asf_pkt->flags; pkt->dts = asf_pkt->dts - asf->preroll; asf_pkt->data_size = 0; asf_pkt->frame_num = 0; return 0; } } } if (pb->eof_reached) return AVERROR_EOF; return 0; } static int asf_read_close(AVFormatContext *s) { ASFContext *asf = s->priv_data; int i; for (i = 0; i < ASF_MAX_STREAMS; i++) { av_dict_free(&asf->asf_sd[i].asf_met); if (i < asf->nb_streams) { av_packet_unref(&asf->asf_st[i]->pkt.avpkt); av_freep(&asf->asf_st[i]); } } asf->nb_streams = 0; return 0; } static void reset_packet_state(AVFormatContext *s) { ASFContext *asf = s->priv_data; int i; asf->state = PARSE_PACKET_HEADER; asf->offset = 0; asf->return_subpayload = 0; asf->sub_left = 0; asf->sub_header_offset = 0; asf->packet_offset = asf->first_packet_offset; asf->pad_len = 0; asf->rep_data_len = 0; asf->dts_delta = 0; asf->mult_sub_len = 0; asf->nb_mult_left = 0; asf->nb_sub = 0; asf->prop_flags = 0; asf->sub_dts = 0; for (i = 0; i < asf->nb_streams; i++) { ASFPacket *pkt = &asf->asf_st[i]->pkt; pkt->size_left = 0; pkt->data_size = 0; pkt->duration = 0; pkt->flags = 0; pkt->dts = 0; pkt->duration = 0; av_packet_unref(&pkt->avpkt); av_init_packet(&pkt->avpkt); } } /* * Find a timestamp for the requested position within the payload * where the pos (position) is the offset inside the Data Object. * When position is not on the packet boundary, asf_read_timestamp tries * to find the closest packet offset after this position. If this packet * is a key frame, this packet timestamp is read and an index entry is created * for the packet. If this packet belongs to the requested stream, * asf_read_timestamp upgrades pos to the packet beginning offset and * returns this packet's dts. So returned dts is the dts of the first key frame with * matching stream number after given position. */ static int64_t asf_read_timestamp(AVFormatContext *s, int stream_index, int64_t *pos, int64_t pos_limit) { ASFContext *asf = s->priv_data; int64_t pkt_pos = *pos, pkt_offset, dts = AV_NOPTS_VALUE, data_end; AVPacket pkt; int n; data_end = asf->data_offset + asf->data_size; n = (pkt_pos - asf->first_packet_offset + asf->packet_size - 1) / asf->packet_size; n = av_clip(n, 0, ((data_end - asf->first_packet_offset) / asf->packet_size - 1)); pkt_pos = asf->first_packet_offset + n * asf->packet_size; avio_seek(s->pb, pkt_pos, SEEK_SET); pkt_offset = pkt_pos; reset_packet_state(s); while (avio_tell(s->pb) < data_end) { int i, ret, st_found; av_init_packet(&pkt); pkt_offset = avio_tell(s->pb); if ((ret = asf_read_packet(s, &pkt)) < 0) { dts = AV_NOPTS_VALUE; return ret; } // ASFPacket may contain fragments of packets belonging to different streams, // pkt_offset is the offset of the first fragment within it. if ((pkt_offset >= (pkt_pos + asf->packet_size))) pkt_pos += asf->packet_size; for (i = 0; i < asf->nb_streams; i++) { ASFStream *st = asf->asf_st[i]; st_found = 0; if (pkt.flags & AV_PKT_FLAG_KEY) { dts = pkt.dts; if (dts) { av_add_index_entry(s->streams[pkt.stream_index], pkt_pos, dts, pkt.size, 0, AVINDEX_KEYFRAME); if (stream_index == st->index) { st_found = 1; break; } } } } if (st_found) break; av_packet_unref(&pkt); } *pos = pkt_pos; av_packet_unref(&pkt); return dts; } static int asf_read_seek(AVFormatContext *s, int stream_index, int64_t timestamp, int flags) { ASFContext *asf = s->priv_data; int idx, ret; if (s->streams[stream_index]->nb_index_entries && asf->is_simple_index) { idx = av_index_search_timestamp(s->streams[stream_index], timestamp, flags); if (idx < 0 || idx >= s->streams[stream_index]->nb_index_entries) return AVERROR_INVALIDDATA; avio_seek(s->pb, s->streams[stream_index]->index_entries[idx].pos, SEEK_SET); } else { if ((ret = ff_seek_frame_binary(s, stream_index, timestamp, flags)) < 0) return ret; } reset_packet_state(s); return 0; } static const GUIDParseTable *find_guid(ff_asf_guid guid) { int j, ret; const GUIDParseTable *g; swap_guid(guid); g = gdef; for (j = 0; j < FF_ARRAY_ELEMS(gdef); j++) { if (!(ret = memcmp(guid, g->guid, sizeof(g->guid)))) return g; g++; } return NULL; } static int detect_unknown_subobject(AVFormatContext *s, int64_t offset, int64_t size) { ASFContext *asf = s->priv_data; AVIOContext *pb = s->pb; const GUIDParseTable *g = NULL; ff_asf_guid guid; int ret; while (avio_tell(pb) <= offset + size) { if (avio_tell(pb) == asf->offset) break; asf->offset = avio_tell(pb); if ((ret = ff_get_guid(pb, &guid)) < 0) return ret; g = find_guid(guid); if (g) { if ((ret = g->read_object(s, g)) < 0) return ret; } else { GUIDParseTable g2; g2.name = "Unknown"; g2.is_subobject = 1; asf_read_unknown(s, &g2); } } return 0; } static int asf_read_header(AVFormatContext *s) { ASFContext *asf = s->priv_data; AVIOContext *pb = s->pb; const GUIDParseTable *g = NULL; ff_asf_guid guid; int i, ret; uint64_t size; asf->preroll = 0; asf->is_simple_index = 0; ff_get_guid(pb, &guid); if (ff_guidcmp(&guid, &ff_asf_header)) return AVERROR_INVALIDDATA; avio_skip(pb, 8); // skip header object size avio_skip(pb, 6); // skip number of header objects and 2 reserved bytes asf->data_reached = 0; /* 1 is here instead of pb->eof_reached because (when not streaming), Data are skipped * for the first time, * Index object is processed and got eof and then seeking back to the Data is performed. */ while (1) { // for the cases when object size is invalid if (avio_tell(pb) == asf->offset) break; asf->offset = avio_tell(pb); if ((ret = ff_get_guid(pb, &guid)) < 0) { if (ret == AVERROR_EOF && asf->data_reached) break; else goto failed; } g = find_guid(guid); if (g) { asf->unknown_offset = asf->offset; asf->is_header = 1; if ((ret = g->read_object(s, g)) < 0) goto failed; } else { size = avio_rl64(pb); align_position(pb, asf->offset, size); } if (asf->data_reached && (!(pb->seekable & AVIO_SEEKABLE_NORMAL) || (asf->b_flags & ASF_FLAG_BROADCAST))) break; } if (!asf->data_reached) { av_log(s, AV_LOG_ERROR, "Data Object was not found.\n"); ret = AVERROR_INVALIDDATA; goto failed; } if (pb->seekable & AVIO_SEEKABLE_NORMAL) avio_seek(pb, asf->first_packet_offset, SEEK_SET); for (i = 0; i < asf->nb_streams; i++) { const char *rfc1766 = asf->asf_sd[asf->asf_st[i]->lang_idx].langs; AVStream *st = s->streams[asf->asf_st[i]->index]; set_language(s, rfc1766, &st->metadata); } for (i = 0; i < ASF_MAX_STREAMS; i++) { AVStream *st = NULL; st = find_stream(s, i); if (st) { av_dict_copy(&st->metadata, asf->asf_sd[i].asf_met, AV_DICT_IGNORE_SUFFIX); if (asf->asf_sd[i].aspect_ratio.num > 0 && asf->asf_sd[i].aspect_ratio.den > 0) { st->sample_aspect_ratio.num = asf->asf_sd[i].aspect_ratio.num; st->sample_aspect_ratio.den = asf->asf_sd[i].aspect_ratio.den; } } } return 0; failed: asf_read_close(s); return ret; } AVInputFormat ff_asf_o_demuxer = { .name = "asf_o", .long_name = NULL_IF_CONFIG_SMALL("ASF (Advanced / Active Streaming Format)"), .priv_data_size = sizeof(ASFContext), .read_probe = asf_probe, .read_header = asf_read_header, .read_packet = asf_read_packet, .read_close = asf_read_close, .read_timestamp = asf_read_timestamp, .read_seek = asf_read_seek, .flags = AVFMT_NOBINSEARCH | AVFMT_NOGENSEARCH, };
/* Copyright (c) 2020 vesoft inc. All rights reserved. * * This source code is licensed under Apache 2.0 License. */ #pragma once #include <folly/Benchmark.h> #include <folly/Format.h> #include <folly/container/Enumerate.h> #include <boost/uuid/uuid.hpp> #include <boost/uuid/uuid_generators.hpp> #include <boost/uuid/uuid_io.hpp> #include <chrono> #include "clients/storage/GraphStorageClient.h" #include "clients/storage/InternalStorageClient.h" #include "codec/RowWriterV2.h" #include "common/base/Base.h" #include "common/expression/ConstantExpression.h" #include "common/meta/SchemaManager.h" #include "common/utils/NebulaKeyUtils.h" #include "kvstore/LogEncoder.h" #include "storage/transaction/TransactionUtils.h" namespace nebula { namespace storage { struct TossTestUtils { static std::vector<nebula::Value> genSingleVal(int n) { boost::uuids::random_generator gen; std::vector<nebula::Value> ret(2); ret[0].setInt(n); ret[1].setStr(boost::uuids::to_string(gen())); return ret; } static std::vector<std::vector<nebula::Value>> genValues(size_t num) { boost::uuids::random_generator gen; std::vector<std::vector<nebula::Value>> ret(num); for (auto i = 0U; i != num; ++i) { ret[i].resize(2); int32_t n = 1024 * (1 + i); ret[i][0].setInt(n); ret[i][1].setStr(boost::uuids::to_string(gen())); } return ret; } static std::string dumpDataSet(const DataSet& ds) { std::stringstream oss; for (auto&& it : folly::enumerate(ds.colNames)) { oss << "\ncolNames[" << it.index << "]=" << *it; } oss << "\n"; oss << dumpRows(ds.rows); return oss.str(); } static std::string concatValues(const std::vector<nebula::Value>& vals) { if (vals.empty()) { return ""; } std::ostringstream oss; for (auto& val : vals) { oss << val << ','; } std::string ret = oss.str(); return ret.substr(0, ret.size() - 1); } static std::string dumpValues(const std::vector<Value>& vals) { std::stringstream oss; oss << "vals.size() = " << vals.size() << "\n"; for (auto& val : vals) { oss << val.toString() << "\n"; } return oss.str(); } static std::string dumpRows(const std::vector<Row>& rows) { std::stringstream oss; oss << "rows.size() = " << rows.size() << "\n"; for (auto& row : rows) { oss << "row.size()=" << row.size() << "\n"; oss << row.toString() << "\n"; } return oss.str(); } static std::string hexVid(int64_t vid) { std::string str(reinterpret_cast<char*>(&vid), sizeof(int64_t)); return folly::hexlify(str); } static std::string hexEdgeId(const cpp2::EdgeKey& ek) { return hexVid(ek.get_src().getInt()) + hexVid(ek.get_dst().getInt()); } static std::vector<std::string> splitNeiResults(std::vector<std::string>& svec) { std::vector<std::string> ret; for (auto& str : svec) { auto sub = splitNeiResult(str); ret.insert(ret.end(), sub.begin(), sub.end()); } return ret; } static bool compareSize(const std::vector<std::string>& svec, size_t expect) { auto equalSize = svec.size() == expect; if (!equalSize) { LOG(INFO) << "compareSize failed: expect=" << expect; print_svec(svec); } return equalSize; } static std::vector<std::string> splitNeiResult(folly::StringPiece str) { std::vector<std::string> ret; auto begin = str.begin(); auto end = str.end(); if (str.startsWith("[[")) { begin++; begin++; } if (str.endsWith("]]")) { end--; end--; } str.assign(begin, end); folly::split("],[", str, ret); if (ret.size() == 1U && ret.back() == "__EMPTY__") { ret.clear(); } return ret; } static void print_svec(const std::vector<std::string>& svec) { LOG(INFO) << "svec.size()=" << svec.size(); for (auto& str : svec) { LOG(INFO) << str; } } static cpp2::NewEdge toVertexIdEdge(const cpp2::NewEdge& e) { cpp2::NewEdge ret(e); (*ret.key_ref()) .set_src(std::string(reinterpret_cast<const char*>(&e.get_key().get_src().getInt()), 8)); (*ret.key_ref()) .set_dst(std::string(reinterpret_cast<const char*>(&e.get_key().get_dst().getInt()), 8)); return ret; } static cpp2::EdgeKey makeEdgeKeyS(const cpp2::EdgeKey& input) { if (input.src.type() == Value::Type::STRING) { return input; } cpp2::EdgeKey ret(input); ret.set_src(std::string(reinterpret_cast<const char*>(&input.get_src().getInt()), 8)); ret.set_dst(std::string(reinterpret_cast<const char*>(&input.get_dst().getInt()), 8)); return ret; } static std::vector<nebula::Value> makeISValue(int64_t iVal) { boost::uuids::random_generator gen; std::vector<nebula::Value> vals(2); vals[0].setInt(iVal); vals[1].setStr(boost::uuids::to_string(gen())); return vals; } // generate a vector of values, 1st is ant i64, 2nd is a random string. static std::vector<std::vector<nebula::Value>> genISValues(size_t num) { std::vector<std::vector<nebula::Value>> ret; for (auto i = 0U; i != num; ++i) { int32_t n = 1024 * (1 + i); ret.emplace_back(makeISValue(n)); } return ret; } // generate num different edges with same dst // the first src is dst + 1, and increase 1 for each static std::vector<cpp2::NewEdge> makeNeighborEdges(int64_t dst, int edgeType, size_t num) { auto values = genISValues(num); std::vector<cpp2::NewEdge> edges; auto rank = 0; for (auto i = 0U; i < num; ++i) { auto src = dst + i + 1; auto ekey = makeEdgeKeyI(src, edgeType, rank, dst); edges.emplace_back(); edges.back().set_key(std::move(ekey)); edges.back().set_props(std::move(values[i])); } return edges; } static cpp2::NewEdge makeEdge(int64_t src, int edgeType) { cpp2::NewEdge edge; edge.set_key(makeEdgeKeyI(src, edgeType, 0, src + 1)); edge.set_props(makeISValue(1024)); return edge; } static cpp2::NewEdge makeEdgeS(int64_t src, int edgeType) { cpp2::NewEdge edge = makeEdge(src, edgeType); edge.key = makeEdgeKeyS(edge.key); return edge; } static cpp2::NewEdge makeTwinEdge(const cpp2::NewEdge& oldEdge) { cpp2::NewEdge newEdge(oldEdge); auto newVal = makeISValue(newEdge.props[0].getInt() + 1024); newEdge.set_props(newVal); return newEdge; } static std::vector<std::string> makeColNames(size_t n) { std::vector<std::string> colNames; for (auto i = 0U; i < n; ++i) { colNames.emplace_back(folly::sformat("c{}", i + 1)); } return colNames; } static std::vector<meta::cpp2::ColumnDef> makeColDefs( const std::vector<nebula::cpp2::PropertyType>& types) { auto N = types.size(); auto colNames = makeColNames(N); std::vector<meta::cpp2::ColumnDef> columnDefs(N); for (auto i = 0U; i != N; ++i) { columnDefs[i].set_name(colNames[i]); meta::cpp2::ColumnTypeDef colTypeDef; colTypeDef.set_type(types[i]); columnDefs[i].set_type(colTypeDef); columnDefs[i].set_nullable(true); } return columnDefs; } }; // end TossTestUtils } // namespace storage } // namespace nebula
#include <stdio.h> #include <stdlib.h> #include <cs50.h> #include <stdint.h> //defining the type byte typedef uint8_t BYTE; //defining the size of the block #define block 512 //defining the size of the file name #define filenamesize 8 bool is_start_of_jpeg(BYTE buffer[]); int main(int argc, char *argv[]) { //if it has no command-line argument if (argc != 2) { printf("Missing command-line argument!\n"); return 1; } FILE *inside_file = fopen(argv[1], "r"); //if there is no file if (inside_file == NULL) { printf("Missing file!\n"); return 1; } BYTE buffer[block]; bool found_first_jpeg = false; int number_of_files = 0; FILE *jpeg; //reading the file and restoring the jpegs while (fread(buffer, block, 1, inside_file)) { //starts or close a jpeg file if (is_start_of_jpeg(buffer)) { if (!found_first_jpeg) { found_first_jpeg = true; } else { fclose(jpeg); } char filename[filenamesize]; sprintf(filename, "%03i.jpg", number_of_files++); jpeg = fopen(filename, "w"); if (jpeg == NULL) { return 1; } fwrite(buffer, block, 1, jpeg); } //keeps writing in the same jpeg file else if (found_first_jpeg) { fwrite(buffer, block, 1, jpeg); } } fclose(jpeg); fclose(inside_file); } //check if it is the beggining of a jpeg bool is_start_of_jpeg(BYTE buffer[]) { return buffer[0] == 0xff && buffer[1] == 0xd8 && buffer[2] == 0xff && (buffer[3] & 0xf0) == 0xe0; }
/* * This header is generated by classdump-dyld 1.5 * on Wednesday, April 14, 2021 at 2:38:54 PM Mountain Standard Time * Operating System: Version 14.4 (Build 18K802) * Image Source: /System/Library/PrivateFrameworks/WorkflowKit.framework/WorkflowKit * classdump-dyld is licensed under GPLv3, Copyright © 2013-2016 by Elias Limneos. Updated by Kevin Bradley. */ #import <WorkflowKit/WorkflowKit-Structs.h> #import <libobjc.A.dylib/NSCopying.h> #import <libobjc.A.dylib/WFParameterState.h> @protocol WFParameterState; @class NSString; @interface WFPropertyListParameterValue : NSObject <NSCopying, WFParameterState> { long long _valueType; id<WFParameterState> _state; } @property (nonatomic,readonly) long long valueType; //@synthesize valueType=_valueType - In the implementation block @property (nonatomic,readonly) id<WFParameterState> state; //@synthesize state=_state - In the implementation block @property (readonly) unsigned long long hash; @property (readonly) Class superclass; @property (copy,readonly) NSString * description; @property (copy,readonly) NSString * debugDescription; +(Class)classForValueType:(long long)arg1 ; +(id)defaultStateForValueType:(long long)arg1 ; +(Class)processedClassForValueType:(long long)arg1 ; +(id)localizedTitleForValueType:(long long)arg1 ; -(BOOL)isEqual:(id)arg1 ; -(unsigned long long)hash; -(id)copyWithZone:(NSZone*)arg1 ; -(id)initWithArray:(id)arg1 ; -(id)initWithObject:(id)arg1 ; -(id)initWithString:(id)arg1 ; -(id)initWithDictionary:(id)arg1 ; -(id<WFParameterState>)state; -(id)serializedRepresentation; -(long long)valueType; -(id)initWithNumber:(id)arg1 ; -(void)processWithContext:(id)arg1 userInputRequiredHandler:(/*^block*/id)arg2 valueHandler:(/*^block*/id)arg3 ; -(id)containedVariables; -(id)initWithSerializedRepresentation:(id)arg1 variableProvider:(id)arg2 parameter:(id)arg3 ; -(id)initWithType:(long long)arg1 state:(id)arg2 ; -(id)initWithStringState:(id)arg1 ; -(id)initWithDictionaryState:(id)arg1 ; -(id)initWithArrayState:(id)arg1 ; -(id)initWithNumberState:(id)arg1 ; -(id)initWithBooleanState:(id)arg1 ; -(id)initWithBoolean:(id)arg1 ; @end
#import "OSPlatform.h" NS_ASSUME_NONNULL_BEGIN @interface OSImage (QRCode) + (OSImage *_Nullable )QRImageWithString:(NSString *)dataString withSize:(CGSize)requestedSize; - (NSString *)QRCodeString; + (void) QRImageWithString:(NSString*) dataString scaledSize:(CGSize)requestedSize completionQueue:(dispatch_queue_t _Nullable)completionQueue completionBlock:(void (^)(OSImage * _Nullable image))completionBlock; @end NS_ASSUME_NONNULL_END
// Copyright (c) 2012-2017, The CryptoNote developers, The Bytecoin developers // Copyright (c) 2018-2019, The Qwertycoin developers // // This file is part of Qwertycoin. // // Qwertycoin is free software: you can redistribute it and/or modify // it under the terms of the GNU Lesser General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any later version. // // Qwertycoin is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU Lesser General Public License for more details. // // You should have received a copy of the GNU Lesser General Public License // along with Qwertycoin. If not, see <http://www.gnu.org/licenses/>. #pragma once #include <atomic> #include <functional> #include <map> #include <string> #include <thread> #include <vector> #include "BlockingQueue.h" #include "ConsoleTools.h" #ifndef _WIN32 #include <sys/select.h> #endif namespace Common { class AsyncConsoleReader { public: AsyncConsoleReader(); ~AsyncConsoleReader(); void start(); bool getline(std::string& line); void stop(); bool stopped() const; void pause(); void unpause(); private: void consoleThread(); bool waitInput(); std::atomic<bool> m_stop; std::thread m_thread; BlockingQueue<std::string> m_queue; }; class ConsoleHandler { public: ~ConsoleHandler(); typedef std::function<bool(const std::vector<std::string> &)> ConsoleCommandHandler; std::string getUsage() const; void setHandler(const std::string& command, const ConsoleCommandHandler& handler, const std::string& usage = ""); void requestStop(); bool runCommand(const std::vector<std::string>& cmdAndArgs); void start(bool startThread = true, const std::string& prompt = "", Console::Color promptColor = Console::Color::Default); void stop(); void wait(); void pause(); void unpause(); private: typedef std::map<std::string, std::pair<ConsoleCommandHandler, std::string>> CommandHandlersMap; virtual void handleCommand(const std::string& cmd); void handlerThread(); std::thread m_thread; std::string m_prompt; Console::Color m_promptColor = Console::Color::Default; CommandHandlersMap m_handlers; AsyncConsoleReader m_consoleReader; }; }
/** ************************************************************************************** * @file main.c * @author shaokairu * @date 2021.7.8 * @brief This file includes the main program body ************************************************************************************** */ /* Includes --------------------------------------------------------------------------*/ #include "main.h" #include "sys.h" #include "delay.h" #include "usart.h" #include "led.h" #include "adc.h" #include "key.h" #include "exti.h" #include "timer.h" #include "lcd.h" #include "plot.h" #include "fitted.h" #include "filter.h" /* Exported variables ------------------------------------------------------------------*/ uint16_t Ladc1=0, Ladc2=0, Ladc3=0; uint8_t penState = 0; // 0 pen up, 1 pen down double x, y; // axis position /** *@brief The application entry point. *@param None *@retval int */ int main(void) { uint8_t i; /* MCU Configuration--------------------------------------------------------------*/ /* Reset of all peripherals, Initializes the Flash interface and the Systick. */ HAL_Init(); /* Configure the system clock */ Stm32_Clock_Init(RCC_PLL_MUL9); /* Initialize all configured peripherals */ delay_init(72); uart_init(115200); LED_Init(); KEY_Init(); ADC1_Init(); EXTI_Init(); TIM3_Init(719, 199); LCD_Init(); /* Pragram begin configuration----------------------------------------------------*/ /* Drawing Area Set*/ POINT_COLOR = RED; LCD_Clear(BLUE); LCD_Fill( 0, 0, 239, 160, WHITE); LCD_DrawRectangle( 0, 0, 239, 160); // plot border LCD_DrawRectangle( 1, 1, 238, 159); LCD_DrawRectangle( 12, 8, 227, 152); // drawing border LCD_DrawRectangle( 66, 44, 173, 116); // high-accuracy border LCD_DrawLine( 0, 80, 239, 80); // centre line LCD_DrawLine( 119, 0, 119, 160); /* Drawing Paramter List */ BACK_COLOR = BLUE; LCD_ShowString( 42, 161,240, 24, 24, "Paramter List"); POINT_COLOR = BROWN; LCD_DrawRectangle( 14, 185, 225, 315); // border LCD_DrawRectangle( 15, 186, 224, 314); LCD_DrawRectangle( 16, 187, 223, 313); LCD_Fill( 17, 188, 222, 312, WHITE); // background POINT_COLOR = BLACK; BACK_COLOR = WHITE; LCD_ShowString( 20, 190, 240, 16, 16, "ADC1: "); // paramter location LCD_ShowString( 20, 206, 240, 16, 16, "ADC2: "); LCD_ShowString( 20, 222, 240, 16, 16, "ADC3: "); LCD_ShowString( 20, 238, 240, 16, 16, "x: "); LCD_ShowString( 70, 238, 240, 16, 16, "mm"); LCD_ShowString( 20, 254, 240, 16, 16, "y: "); LCD_ShowString( 70, 254, 240, 16, 16, "mm"); POINT_COLOR = MAGENTA; LCD_ShowString( 20, 270, 240, 16, 16, "pen up "); POINT_COLOR = BLACK; // draw_point_graph( -7, 0,119, 80, CYAN); // drawing point /* Infinite loop */ while(1) { LCD_ShowNum( 56, 190, Ladc1, 6, 16); // paramter display LCD_ShowNum( 56, 206, Ladc2, 6, 16); LCD_ShowNum( 56, 222, Ladc3, 6, 16); /* detemine whether the pen is down */ POINT_COLOR = MAGENTA; if(Ladc3 > 695) { LCD_ShowString( 20, 270, 240, 16, 16, "pen down"); penState = 1; } else { LCD_ShowString( 20, 270, 240, 16, 16, "pen up "); penState = 0; } POINT_COLOR = BLACK; //printf("%d\r\n", Ladc1); if(penState == 1) { delay_ms(500); x = fitted_position_x(Ladc1 - Ladc3, Ladc2); y = - fitted_position_y(Ladc1 - Ladc3, Ladc2); // because printf("%lf,%lf\r\n",x,y); if(x < 0) { LCD_ShowString( 35, 238, 240, 16, 16, "-"); LCD_ShowNum( 40, 238, -x, 3, 16); } else { LCD_ShowString( 35, 238, 240, 16, 16, " "); LCD_ShowNum( 40, 238, x, 3, 16); } if( y< 0) { LCD_ShowString( 40, 254, 240, 16, 16, "-"); LCD_ShowNum( 40, 254, -y, 3, 16); } else { LCD_ShowString( 40, 254, 240, 16, 16, " "); LCD_ShowNum( 40, 254, y, 3, 16); } draw_point_graph( x, y, 119, 80, BLACK); } } } /**********************************END OF FILE*****************************************/
// // RTMeetKitDelegate.h // RTMeetEngine // // Created by EricTao on 16/11/10. // Copyright © 2016年 EricTao. All rights reserved. // #ifndef RTMeetKitDelegate_h #define RTMeetKitDelegate_h #if TARGET_OS_IPHONE #import <UIKit/UIKit.h> #else #import <AppKit/AppKit.h> #endif @protocol RTMeetKitDelegate <NSObject> @required /** 加入会议成功的回调 @param strAnyRTCId 会议号(在开发者业务系统中保持唯一的Id); 说明:加入会议成功。 */ - (void)onRTCJoinMeetOK:(NSString*)strAnyRTCId; /** 加入会议失败 @param strAnyRTCId 会议号(在开发者业务系统中保持唯一的Id); @param nCode 状态码,错误原因可查看nCode对应原因; 说明:加入会议失败。 */ - (void)onRTCJoinMeetFailed:(NSString*)strAnyRTCId withCode:(int)nCode; /** 离开会议 @param nCode 状态码,错误原因可查看nCode对应原因; 说明:离开会议状态回调。 */ -(void)onRTCLeaveMeet:(int) nCode; /** 其他与会者加入(音视频) @param strRTCPeerId RTC服务生成的标识Id (用于标识与会者,每次加入会议随机生成); @param strRTCPubId RTC服务生成流的ID (用于标识与会者发布的流); @param strUserId 开发者自己平台的Id; @param strUserData 开发者自己平台的相关信息(昵称,头像等); 说明:其他与会者进入会议的回调,开发者需调用设置其他与会者视频窗口(setRTCVideoRender)方法。 */ -(void)onRTCOpenVideoRender:(NSString*)strRTCPeerId withRTCPubId:(NSString *)strRTCPubId withUserId:(NSString*)strUserId withUserData:(NSString*)strUserData; /** 其他与会者离开(音视频) @param strRTCPeerId RTC服务生成的标识Id (用于标识与会者,每次加入会议随机生成); @param strRTCPubId RTC服务生成流的ID (用于标识与会者发布的流); @param strUserId 开发者自己平台的Id; 说明:其他与会者离开将会回调此方法;需本地移除与会者视频视图。 */ -(void)onRTCCloseVideoRender:(NSString*)strRTCPeerId withRTCPubId:(NSString *)strRTCPubId withUserId:(NSString*)strUserId; /** 用户开启桌面共享 @param strRTCPeerId RTC服务生成的标识Id (用于标识与会者,每次加入会议随机生成); @param strRTCPubId RTC服务生成流的ID (用于标识与会者发布的流); @param strUserId 开发者自己平台的Id; @param strUserData 开发者自己平台的相关信息(昵称,头像等); 说明:开发者需调用设置其他与会者视频窗口(setRTCVideoRender)方法 */ -(void)onRTCOpenScreenRender:(NSString*)strRTCPeerId withRTCPubId:(NSString *)strRTCPubId withUserId:(NSString*)strUserId withUserData:(NSString*)strUserData; /** 用户退出桌面共享 @param strRTCPeerId RTC服务生成的标识Id (用于标识与会者,每次加入会议随机生成); @param strRTCPubId RTC服务生成流的ID (用于标识与会者发布的流); @param strUserId 开发者自己平台的Id; 说明:其他与会者离开将会回调此方法;需本地移除屏幕共享窗口。 */ -(void)onRTCCloseScreenRender:(NSString*)strRTCPeerId withRTCPubId:(NSString *)strRTCPubId withUserId:(NSString*)strUserId; /** 其他与会者视频窗口的对音视频的操作 @param strRTCPeerId RTC服务生成的标识Id (用于标识与会者,每次加入会议随机生成); @param bAudio yes为打开音频,no为关闭音频 @param bVideo yes为打开视频,no为关闭视频 说明:比如对方关闭了音频,对方关闭了视频 */ -(void)onRTCAVStatus:(NSString*) strRTCPeerId withAudio:(BOOL)bAudio withVideo:(BOOL)bVideo; /** RTC音频检测 @param strRTCPeerId RTC服务生成的与会者标识Id(用于标识与会者用户,每次随机生成) @param strUserId 连麦者在自己平台的用户Id; @param nLevel 音频检测音量;(0~100) @param nTime 音频检测在nTime毫秒内不会再回调该方法(单位:毫秒); 说明:对方关闭音频后(setLocalAudioEnable为NO),该回调将不再回调;对方关闭音频检测后(setAudioActiveCheck为NO),该回调也将不再回调。 */ -(void)onRTCAudioActive:(NSString*)strRTCPeerId withUserId:(NSString *)strUserId withAudioLevel:(int)nLevel withShowTime:(int)nTime; /** 视频窗口大小的回调 @param videoView 视频窗口 @param size 视频的分辨率 说明:与会者或者自己视频窗口大小变化的回调。一般处理视频窗口第一针视频显示:美颜相机没有该回调 */ #if TARGET_OS_IPHONE -(void) onRTCViewChanged:(UIView*)videoView didChangeVideoSize:(CGSize)size; #else #endif @optional /** 网络状态 @param strRTCPeerId RTC服务生成的与会者标识Id(用于标识与会者用户,每次随机生成) @param strUserId 连麦者在自己平台的用户Id; @param nNetSpeed 网络上行 @param nPacketLost 丢包率 */ - (void)onRtcNetworkStatus:(NSString*)strRTCPeerId withUserId:(NSString *)strUserId withNetSpeed:(int)nNetSpeed withPacketLost:(int)nPacketLost; /** 收到消息回调 @param strUserId 发送消息者在自己平台下的Id; @param strUserName 发送消息者的昵称 @param strUserHeaderUrl 发送者的头像 @param strContent 消息内容 说明:该参数来源均为发送消息时所带参数。 */ - (void)onRTCUserMessage:(NSString*)strUserId withUserName:(NSString*)strUserName withUserHeader:(NSString*)strUserHeaderUrl withContent:(NSString*)strContent; /** 主持人上线(只有主持模式下的游客身份登录才有用) @param strRTCPeerId RTC服务生成的标识Id (用于标识与会者,每次加入会议随机生成); @param strUserId 开发者自己平台的Id; @param strUserData 开发者自己平台的相关信息(昵称,头像等); */ - (void)onRTCHosterOnLine:(NSString*)strRTCPeerId withUserId:(NSString*)strUserId withUserData:(NSString*)strUserData; /** 主持人下线(只有主持模式下的游客身份登录才有用) @param strRTCPeerId RTC服务生成的标识Id (用于标识与会者,每次加入会议随机生成); */ - (void)onRTCHosterOffLine:(NSString*)strRTCPeerId; /** 1v1开启 @param strRTCPeerId RTC服务生成的标识Id (用于标识与会者,每次加入会议随机生成); @param strUserId 开发者自己平台的Id; @param strUserData 开发者自己平台的相关信息(昵称,头像等); */ - (void)onRTCTalkOnlyOn:(NSString*)strRTCPeerId withUserId:(NSString*)strUserId withUserData:(NSString*)strUserData; /** 1v1关闭 @param strRTCPeerId RTC服务生成的标识Id (用于标识与会者,每次加入会议随机生成); */ - (void)onRtcTalkOnlyOff:(NSString*)strRTCPeerId; /** 检测服务链接与否 @param bOk YES/NO 成功/失败 */ - (void)onRTCCheckConnectionRealtime:(BOOL)bOk; @end #endif /* RTMeetKitDelegate_h */
/* * Copyright (c) 2017, Arm Limited and affiliates. * SPDX-License-Identifier: Apache-2.0 * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #ifndef QUECTEL_BG96_H_ #define QUECTEL_BG96_H_ #ifdef TARGET_FF_ARDUINO #ifndef MBED_CONF_QUECTEL_BG96_TX #define MBED_CONF_QUECTEL_BG96_TX D1 #endif #ifndef MBED_CONF_QUECTEL_BG96_RX #define MBED_CONF_QUECTEL_BG96_RX D0 #endif #endif /* TARGET_FF_ARDUINO */ #include "DigitalOut.h" #include "AT_CellularDevice.h" namespace mbed { class QUECTEL_BG96 : public AT_CellularDevice { public: QUECTEL_BG96(FileHandle *fh, PinName pwr = NC, bool active_high = true, PinName rst = NC); protected: // AT_CellularDevice virtual AT_CellularNetwork *open_network_impl(ATHandler &at); virtual AT_CellularContext *create_context_impl(ATHandler &at, const char *apn, bool cp_req = false, bool nonip_req = false); virtual AT_CellularInformation *open_information_impl(ATHandler &at); virtual void set_ready_cb(Callback<void()> callback); virtual nsapi_error_t hard_power_on(); virtual nsapi_error_t hard_power_off(); virtual nsapi_error_t soft_power_on(); virtual nsapi_error_t init(); public: void handle_urc(FileHandle *fh); private: nsapi_error_t press_power_button(uint32_t timeout); bool _active_high; DigitalOut _pwr; DigitalOut _rst; }; } // namespace mbed #endif // QUECTEL_BG96_H_
/* * md5.c - the MD5 Message-Digest Algorithm (RFC 1321) * * Copyright (C) 2014 - 2016, Xiaoxiao <i@pxx.io> * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ #include <stdint.h> #include <string.h> #include "md5.h" static inline uint32_t F(uint32_t x, uint32_t y, uint32_t z) { return (x & y) | (~x & z); } static inline uint32_t G(uint32_t x, uint32_t y, uint32_t z) { return (x & z) | (y & ~z); } static inline uint32_t H(uint32_t x, uint32_t y, uint32_t z) { return x ^ y ^ z; } static inline uint32_t I(uint32_t x, uint32_t y, uint32_t z) { return y ^ (x | ~z); } static inline uint32_t LEFT_ROTATE(uint32_t x, uint32_t n) { return (x << n) | (x >> (32 - n)); } static inline void FF(uint32_t *a, uint32_t b, uint32_t c, uint32_t d, uint32_t x, uint32_t s, uint32_t ac) { *a += F(b, c, d); *a += x; *a += ac; *a = LEFT_ROTATE(*a, s); *a += b; } static inline void GG(uint32_t *a, uint32_t b, uint32_t c, uint32_t d, uint32_t x, uint32_t s, uint32_t ac) { *a += G(b, c, d); *a += x; *a += ac; *a = LEFT_ROTATE(*a, s); *a += b; } static inline void HH(uint32_t *a, uint32_t b, uint32_t c, uint32_t d, uint32_t x, uint32_t s, uint32_t ac) { *a += H(b, c, d); *a += x; *a += ac; *a = LEFT_ROTATE(*a, s); *a += b; } static inline void II(uint32_t *a, uint32_t b, uint32_t c, uint32_t d, uint32_t x, uint32_t s, uint32_t ac) { *a += I(b, c, d); *a += x; *a += ac; *a = LEFT_ROTATE(*a, s); *a += b; } #ifndef AC_LITTLE_ENDIAN static uint32_t bswap(uint32_t x) { uint32_t r = 0; r |= (x & 0xff000000u) >> 24; r |= (x & 0x00ff0000u) >> 8; r |= (x & 0x0000ff00u) << 8; r |= (x & 0x000000ffu) << 24; return r; } #endif void md5(void *digest, const void *in, size_t ilen) { size_t n = (ilen * 8 + 512 * 2 - 448) / 512; uint32_t M[n * 16]; memcpy(M, in, ilen); bzero((char *)M + ilen, sizeof(M) - ilen); #ifdef AC_LITTLE_ENDIAN M[ilen / 4] |= 0x80 << 8 * (ilen % 4); M[n * 16 - 2] = ilen * 8; #else M[ilen / 4] |= bswap(0x80 << 8 * (ilen % 4)); M[n * 16 - 2] = bswap(ilen * 8); #endif uint32_t state[4] = {0x67452301u, 0xefcdab89u, 0x98badcfeu, 0x10325476u}; for (size_t i = 0; i < n; i++) { uint32_t X[16]; uint32_t a, b, c, d; for (int j = 0; j < 16; j++) { #ifdef AC_LITTLE_ENDIAN X[j] = M[i * 16 + j]; #else X[j] = bswap(M[i * 16 + j]); #endif } a = state[0]; b = state[1]; c = state[2]; d = state[3]; // 第一轮 FF(&a, b, c, d, X[ 0], 7, 0xd76aa478u); // 1 FF(&d, a, b, c, X[ 1], 12, 0xe8c7b756u); // 2 FF(&c, d, a, b, X[ 2], 17, 0x242070dbu); // 3 FF(&b, c, d, a, X[ 3], 22, 0xc1bdceeeu); // 4 FF(&a, b, c, d, X[ 4], 7, 0xf57c0fafu); // 5 FF(&d, a, b, c, X[ 5], 12, 0x4787c62au); // 6 FF(&c, d, a, b, X[ 6], 17, 0xa8304613u); // 7 FF(&b, c, d, a, X[ 7], 22, 0xfd469501u); // 8 FF(&a, b, c, d, X[ 8], 7, 0x698098d8u); // 9 FF(&d, a, b, c, X[ 9], 12, 0x8b44f7afu); // 10 FF(&c, d, a, b, X[10], 17, 0xffff5bb1u); // 11 FF(&b, c, d, a, X[11], 22, 0x895cd7beu); // 12 FF(&a, b, c, d, X[12], 7, 0x6b901122u); // 13 FF(&d, a, b, c, X[13], 12, 0xfd987193u); // 14 FF(&c, d, a, b, X[14], 17, 0xa679438eu); // 15 FF(&b, c, d, a, X[15], 22, 0x49b40821u); // 16 // 第二轮 GG(&a, b, c, d, X[ 1], 5, 0xf61e2562u); // 17 GG(&d, a, b, c, X[ 6], 9, 0xc040b340u); // 18 GG(&c, d, a, b, X[11], 14, 0x265e5a51u); // 19 GG(&b, c, d, a, X[ 0], 20, 0xe9b6c7aau); // 20 GG(&a, b, c, d, X[ 5], 5, 0xd62f105du); // 21 GG(&d, a, b, c, X[10], 9, 0x02441453u); // 22 GG(&c, d, a, b, X[15], 14, 0xd8a1e681u); // 23 GG(&b, c, d, a, X[ 4], 20, 0xe7d3fbc8u); // 24 GG(&a, b, c, d, X[ 9], 5, 0x21e1cde6u); // 25 GG(&d, a, b, c, X[14], 9, 0xc33707d6u); // 26 GG(&c, d, a, b, X[ 3], 14, 0xf4d50d87u); // 27 GG(&b, c, d, a, X[ 8], 20, 0x455a14edu); // 28 GG(&a, b, c, d, X[13], 5, 0xa9e3e905u); // 29 GG(&d, a, b, c, X[ 2], 9, 0xfcefa3f8u); // 30 GG(&c, d, a, b, X[ 7], 14, 0x676f02d9u); // 31 GG(&b, c, d, a, X[12], 20, 0x8d2a4c8au); // 32 // 第三轮 HH(&a, b, c, d, X[ 5], 4, 0xfffa3942u); // 33 HH(&d, a, b, c, X[ 8], 11, 0x8771f681u); // 34 HH(&c, d, a, b, X[11], 16, 0x6d9d6122u); // 35 HH(&b, c, d, a, X[14], 23, 0xfde5380cu); // 36 HH(&a, b, c, d, X[ 1], 4, 0xa4beea44u); // 37 HH(&d, a, b, c, X[ 4], 11, 0x4bdecfa9u); // 38 HH(&c, d, a, b, X[ 7], 16, 0xf6bb4b60u); // 39 HH(&b, c, d, a, X[10], 23, 0xbebfbc70u); // 40 HH(&a, b, c, d, X[13], 4, 0x289b7ec6u); // 41 HH(&d, a, b, c, X[ 0], 11, 0xeaa127fau); // 42 HH(&c, d, a, b, X[ 3], 16, 0xd4ef3085u); // 43 HH(&b, c, d, a, X[ 6], 23, 0x04881d05u); // 44 HH(&a, b, c, d, X[ 9], 4, 0xd9d4d039u); // 45 HH(&d, a, b, c, X[12], 11, 0xe6db99e5u); // 46 HH(&c, d, a, b, X[15], 16, 0x1fa27cf8u); // 47 HH(&b, c, d, a, X[ 2], 23, 0xc4ac5665u); // 48 // 第四轮 II(&a, b, c, d, X[ 0], 6, 0xf4292244u); // 49 II(&d, a, b, c, X[ 7], 10, 0x432aff97u); // 50 II(&c, d, a, b, X[14], 15, 0xab9423a7u); // 51 II(&b, c, d, a, X[ 5], 21, 0xfc93a039u); // 52 II(&a, b, c, d, X[12], 6, 0x655b59c3u); // 53 II(&d, a, b, c, X[ 3], 10, 0x8f0ccc92u); // 54 II(&c, d, a, b, X[10], 15, 0xffeff47du); // 55 II(&b, c, d, a, X[ 1], 21, 0x85845dd1u); // 56 II(&a, b, c, d, X[ 8], 6, 0x6fa87e4fu); // 57 II(&d, a, b, c, X[15], 10, 0xfe2ce6e0u); // 58 II(&c, d, a, b, X[ 6], 15, 0xa3014314u); // 59 II(&b, c, d, a, X[13], 21, 0x4e0811a1u); // 60 II(&a, b, c, d, X[ 4], 6, 0xf7537e82u); // 61 II(&d, a, b, c, X[11], 10, 0xbd3af235u); // 62 II(&c, d, a, b, X[ 2], 15, 0x2ad7d2bbu); // 63 II(&b, c, d, a, X[ 9], 21, 0xeb86d391u); // 64 state[0] += a; state[1] += b; state[2] += c; state[3] += d; } for (int i = 0; i < 16; i++) { ((uint8_t *)digest)[i] = (state[i / 4] >> (i % 4 * 8)) & 0xffu; } } void hmac_md5(void *digest, const void *key, size_t klen, const void *in, size_t ilen) { uint8_t ipad[64 + ilen]; uint8_t opad[64 + 16]; bzero(ipad, 64); bzero(opad, 64); if (klen > 64) { md5(ipad, key, klen); memcpy(opad, ipad, 16); } else { memcpy(ipad, key, klen); memcpy(opad, key, klen); } for (int i = 0; i < 64; i++) { ipad[i] ^= 0x36; opad[i] ^= 0x5c; } memcpy(ipad + 64, in, ilen); md5(opad + 64, ipad, sizeof(ipad)); md5(digest, opad, sizeof(opad)); }
/** * (C) Copyright 2017-2019 Intel Corporation. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * * GOVERNMENT LICENSE RIGHTS-OPEN SOURCE SOFTWARE * The Government's rights to use, modify, reproduce, release, perform, display, * or disclose this software are subject to the terms of the Apache License as * provided in Contract No. B609815. * Any reproduction of computer software, computer software documentation, or * portions thereof marked with this legend must also reproduce the markings. */ /** * rdb: Internal Declarations */ #ifndef RDB_INTERNAL_H #define RDB_INTERNAL_H #include <abt.h> #include <raft.h> #include <gurt/hash.h> #include <daos/lru.h> #include <daos/rpc.h> #include "rdb_layout.h" /* rdb_raft.c (parts required by struct rdb) **********************************/ enum rdb_raft_event_type { RDB_RAFT_STEP_UP, RDB_RAFT_STEP_DOWN }; struct rdb_raft_event { enum rdb_raft_event_type dre_type; uint64_t dre_term; }; /* rdb.c **********************************************************************/ struct rdb { /* General fields */ d_list_t d_entry; /* in rdb_hash */ uuid_t d_uuid; /* of database */ ABT_mutex d_mutex; /* mainly for using CVs */ int d_ref; /* of callers and RPCs */ ABT_cond d_ref_cv; /* for d_ref decrements */ struct rdb_cbs *d_cbs; /* callers' callbacks */ void *d_arg; /* for d_cbs callbacks */ struct daos_lru_cache *d_kvss; /* rdb_kvs cache */ daos_handle_t d_pool; /* VOS pool */ daos_handle_t d_mc; /* metadata container */ /* rdb_raft fields */ raft_server_t *d_raft; daos_handle_t d_lc; /* log container */ struct rdb_lc_record d_lc_record; /* of d_lc */ daos_handle_t d_slc; /* staging log container */ struct rdb_lc_record d_slc_record; /* of d_slc */ d_rank_list_t *d_replicas; uint64_t d_applied; /* last applied index */ uint64_t d_debut; /* first entry in a term */ ABT_cond d_applied_cv; /* for d_applied updates */ struct d_hash_table d_results; /* rdb_raft_result hash */ d_list_t d_requests; /* RPCs waiting for replies */ d_list_t d_replies; /* RPCs received replies */ ABT_cond d_replies_cv; /* for d_replies enqueues */ struct rdb_raft_event d_events[2]; /* rdb_raft_events queue */ int d_nevents; /* d_events queue len from 0 */ ABT_cond d_events_cv; /* for d_events enqueues */ uint64_t d_compact_thres;/* of compactable entries */ ABT_cond d_compact_cv; /* for base updates */ bool d_stop; /* for rdb_stop() */ ABT_thread d_timerd; ABT_thread d_callbackd; ABT_thread d_recvd; ABT_thread d_compactd; }; /* Current rank */ #define DF_RANK "%u" static inline d_rank_t DP_RANK(void) { d_rank_t rank; int rc; rc = crt_group_rank(NULL, &rank); D_ASSERTF(rc == 0, "%d\n", rc); return rank; } #define DF_DB DF_UUID"["DF_RANK"]" #define DP_DB(db) DP_UUID(db->d_uuid), DP_RANK() /* Number of "base" references that the rdb_stop() path expects to remain */ #define RDB_BASE_REFS 1 int rdb_hash_init(void); void rdb_hash_fini(void); void rdb_get(struct rdb *db); void rdb_put(struct rdb *db); struct rdb *rdb_lookup(const uuid_t uuid); /* rdb_raft.c *****************************************************************/ /* * Per-raft_node_t INSTALLSNAPSHOT state * * dis_seq and dis_anchor track the last chunk successfully received by the * follower. */ struct rdb_raft_is { uint64_t dis_index; /* snapshot index */ uint64_t dis_seq; /* last sequence number */ struct rdb_anchor dis_anchor; /* last anchor */ }; /* Per-raft_node_t data */ struct rdb_raft_node { d_rank_t dn_rank; /* Leader fields */ uint64_t dn_term; /* of leader */ struct rdb_raft_is dn_is; }; int rdb_raft_init(daos_handle_t pool, daos_handle_t mc, const d_rank_list_t *replicas); int rdb_raft_start(struct rdb *db); void rdb_raft_stop(struct rdb *db); void rdb_raft_resign(struct rdb *db, uint64_t term); int rdb_raft_verify_leadership(struct rdb *db); int rdb_raft_append_apply(struct rdb *db, msg_entry_t *mentry, void *result); int rdb_raft_wait_applied(struct rdb *db, uint64_t index, uint64_t term); void rdb_requestvote_handler(crt_rpc_t *rpc); void rdb_appendentries_handler(crt_rpc_t *rpc); void rdb_installsnapshot_handler(crt_rpc_t *rpc); void rdb_raft_process_reply(struct rdb *db, raft_node_t *node, crt_rpc_t *rpc); void rdb_raft_free_request(struct rdb *db, crt_rpc_t *rpc); /* rdb_rpc.c ******************************************************************/ /* * RPC operation codes * * These are for daos_rpc::dr_opc and DAOS_RPC_OPCODE(opc, ...) rather than * crt_req_create(..., opc, ...). See src/include/daos/rpc.h. */ #define DAOS_RDB_VERSION 1 /* LIST of internal RPCS in form of: * OPCODE, flags, FMT, handler, corpc_hdlr, */ #define RDB_PROTO_SRV_RPC_LIST \ X(RDB_REQUESTVOTE, \ 0, &CQF_rdb_requestvote, \ rdb_requestvote_handler, NULL), \ X(RDB_APPENDENTRIES, \ 0, &CQF_rdb_appendentries, \ rdb_appendentries_handler, NULL), \ X(RDB_INSTALLSNAPSHOT, \ 0, &CQF_rdb_installsnapshot, \ rdb_installsnapshot_handler, NULL) /* Define for RPC enum population below */ #define X(a, b, c, d, e) a enum rdb_operation { RDB_PROTO_SRV_RPC_LIST, }; #undef X extern struct crt_proto_format rdb_proto_fmt; #define DAOS_ISEQ_RDB_OP /* input fields */ \ ((uuid_t) (ri_uuid) CRT_VAR) #define DAOS_OSEQ_RDB_OP /* output fields */ \ ((int32_t) (ro_rc) CRT_VAR) \ ((uint32_t) (ro_padding) CRT_VAR) CRT_RPC_DECLARE(rdb_op, DAOS_ISEQ_RDB_OP, DAOS_OSEQ_RDB_OP) #define DAOS_ISEQ_RDB_REQUESTVOTE /* input fields */ \ ((struct rdb_op_in) (rvi_op) CRT_VAR) \ ((msg_requestvote_t) (rvi_msg) CRT_VAR) #define DAOS_OSEQ_RDB_REQUESTVOTE /* output fields */ \ ((struct rdb_op_out) (rvo_op) CRT_VAR) \ ((msg_requestvote_response_t) (rvo_msg) CRT_VAR) CRT_RPC_DECLARE(rdb_requestvote, DAOS_ISEQ_RDB_REQUESTVOTE, DAOS_OSEQ_RDB_REQUESTVOTE) #define DAOS_ISEQ_RDB_APPENDENTRIES /* input fields */ \ ((struct rdb_op_in) (aei_op) CRT_VAR) \ ((msg_appendentries_t) (aei_msg) CRT_VAR) #define DAOS_OSEQ_RDB_APPENDENTRIES /* output fields */ \ ((struct rdb_op_out) (aeo_op) CRT_VAR) \ ((msg_appendentries_response_t) (aeo_msg) CRT_VAR) CRT_RPC_DECLARE(rdb_appendentries, DAOS_ISEQ_RDB_APPENDENTRIES, DAOS_OSEQ_RDB_APPENDENTRIES) struct rdb_local { daos_iov_t rl_kds_iov; /* isi_kds buffer */ daos_iov_t rl_data_iov; /* isi_data buffer */ }; #define DAOS_ISEQ_RDB_INSTALLSNAPSHOT /* input fields */ \ ((struct rdb_op_in) (isi_op) CRT_VAR) \ ((msg_installsnapshot_t) (isi_msg) CRT_VAR) \ ((uint32_t) (isi_padding) CRT_VAR) \ /* chunk sequence number */ \ ((uint64_t) (isi_seq) CRT_VAR) \ /* chunk anchor */ \ ((struct rdb_anchor) (isi_anchor) CRT_VAR) \ /* daos_key_desc_t[] */ \ ((crt_bulk_t) (isi_kds) CRT_VAR) \ /* described by isi_kds */ \ ((crt_bulk_t) (isi_data) CRT_VAR) \ /* Local fields (not sent over the network) */ \ ((struct rdb_local) (isi_local) CRT_VAR) #define DAOS_OSEQ_RDB_INSTALLSNAPSHOT /* output fields */ \ ((struct rdb_op_out) (iso_op) CRT_VAR) \ ((msg_installsnapshot_response_t) (iso_msg) CRT_VAR) \ ((uint32_t) (iso_padding) CRT_VAR) \ /* chunk saved? */ \ ((uint64_t) (iso_success) CRT_VAR) \ /* last seq number */ \ ((uint64_t) (iso_seq) CRT_VAR) \ /* last anchor */ \ ((struct rdb_anchor) (iso_anchor) CRT_VAR) CRT_RPC_DECLARE(rdb_installsnapshot, DAOS_ISEQ_RDB_INSTALLSNAPSHOT, DAOS_OSEQ_RDB_INSTALLSNAPSHOT) int rdb_create_raft_rpc(crt_opcode_t opc, raft_node_t *node, crt_rpc_t **rpc); int rdb_send_raft_rpc(crt_rpc_t *rpc, struct rdb *db, raft_node_t *node); int rdb_abort_raft_rpcs(struct rdb *db); int rdb_create_bcast(crt_opcode_t opc, crt_group_t *group, crt_rpc_t **rpc); void rdb_recvd(void *arg); /* rdb_tx.c *******************************************************************/ int rdb_tx_apply(struct rdb *db, uint64_t index, const void *buf, size_t len, void *result); /* rdb_kvs.c ******************************************************************/ /* KVS cache entry */ struct rdb_kvs { struct daos_llink de_entry; /* in LRU */ rdb_path_t de_path; rdb_oid_t de_object; uint8_t de_buf[]; /* for de_path */ }; int rdb_kvs_cache_create(struct daos_lru_cache **cache); void rdb_kvs_cache_destroy(struct daos_lru_cache *cache); void rdb_kvs_cache_evict(struct daos_lru_cache *cache); int rdb_kvs_lookup(struct rdb *db, const rdb_path_t *path, uint64_t index, bool alloc, struct rdb_kvs **kvs); void rdb_kvs_put(struct rdb *db, struct rdb_kvs *kvs); void rdb_kvs_evict(struct rdb *db, struct rdb_kvs *kvs); /* rdb_path.c *****************************************************************/ int rdb_path_clone(const rdb_path_t *path, rdb_path_t *new_path); typedef int (*rdb_path_iterate_cb_t)(daos_iov_t *key, void *arg); int rdb_path_iterate(const rdb_path_t *path, rdb_path_iterate_cb_t cb, void *arg); int rdb_path_pop(rdb_path_t *path); /* rdb_util.c *****************************************************************/ #define DF_IOV "<%p,"DF_U64">" #define DP_IOV(iov) (iov)->iov_buf, (iov)->iov_len extern const daos_size_t rdb_iov_max; size_t rdb_encode_iov(const daos_iov_t *iov, void *buf); ssize_t rdb_decode_iov(const void *buf, size_t len, daos_iov_t *iov); ssize_t rdb_decode_iov_backward(const void *buf_end, size_t len, daos_iov_t *iov); void rdb_oid_to_uoid(rdb_oid_t oid, daos_unit_oid_t *uoid); void rdb_anchor_set_zero(struct rdb_anchor *anchor); void rdb_anchor_set_eof(struct rdb_anchor *anchor); bool rdb_anchor_is_eof(const struct rdb_anchor *anchor); void rdb_anchor_to_hashes(const struct rdb_anchor *anchor, daos_anchor_t *obj_anchor, daos_anchor_t *dkey_anchor, daos_anchor_t *akey_anchor, daos_anchor_t *ev_anchor, daos_anchor_t *sv_anchor); void rdb_anchor_from_hashes(struct rdb_anchor *anchor, daos_anchor_t *obj_anchor, daos_anchor_t *dkey_anchor, daos_anchor_t *akey_anchor, daos_anchor_t *ev_anchor, daos_anchor_t *sv_anchor); int rdb_vos_fetch(daos_handle_t cont, daos_epoch_t epoch, rdb_oid_t oid, daos_key_t *akey, daos_iov_t *value); int rdb_vos_fetch_addr(daos_handle_t cont, daos_epoch_t epoch, rdb_oid_t oid, daos_key_t *akey, daos_iov_t *value); int rdb_vos_iter_fetch(daos_handle_t cont, daos_epoch_t epoch, rdb_oid_t oid, enum rdb_probe_opc opc, daos_key_t *akey_in, daos_key_t *akey_out, daos_iov_t *value); int rdb_vos_iterate(daos_handle_t cont, daos_epoch_t epoch, rdb_oid_t oid, bool backward, rdb_iterate_cb_t cb, void *arg); int rdb_vos_update(daos_handle_t cont, daos_epoch_t epoch, rdb_oid_t oid, int n, daos_iov_t akeys[], daos_iov_t values[]); int rdb_vos_punch(daos_handle_t cont, daos_epoch_t epoch, rdb_oid_t oid, int n, daos_iov_t akeys[]); int rdb_vos_discard(daos_handle_t cont, daos_epoch_t low, daos_epoch_t high); int rdb_vos_aggregate(daos_handle_t cont, daos_epoch_t high); /* * Maximal number of a-keys (i.e., the n parameter) passed to an * rdb_mc_update() call. Bumping this number increases the stack usage of * rdb_vos_update(). */ #define RDB_VOS_BATCH_MAX 2 /* Update n (<= RDB_VOS_BATCH_MAX) a-keys atomically. */ static inline int rdb_mc_update(daos_handle_t mc, rdb_oid_t oid, int n, daos_iov_t akeys[], daos_iov_t values[]) { D_DEBUG(DB_TRACE, "mc="DF_X64" oid="DF_X64" n=%d akeys[0]=<%p, %zd> " "values[0]=<%p, %zd>\n", mc.cookie, oid, n, akeys[0].iov_buf, akeys[0].iov_len, values[0].iov_buf, values[0].iov_len); return rdb_vos_update(mc, RDB_MC_EPOCH, oid, n, akeys, values); } static inline int rdb_mc_lookup(daos_handle_t mc, rdb_oid_t oid, daos_iov_t *akey, daos_iov_t *value) { D_DEBUG(DB_TRACE, "mc="DF_X64" oid="DF_X64" akey=<%p, %zd> " "value=<%p, %zd, %zd>\n", mc.cookie, oid, akey->iov_buf, akey->iov_len, value->iov_buf, value->iov_buf_len, value->iov_len); return rdb_vos_fetch(mc, RDB_MC_EPOCH, oid, akey, value); } static inline int rdb_lc_update(daos_handle_t lc, uint64_t index, rdb_oid_t oid, int n, daos_iov_t akeys[], daos_iov_t values[]) { D_DEBUG(DB_TRACE, "lc="DF_X64" index="DF_U64" oid="DF_X64 " n=%d akeys[0]=<%p, %zd> values[0]=<%p, %zd>\n", lc.cookie, index, oid, n, akeys[0].iov_buf, akeys[0].iov_len, values[0].iov_buf, values[0].iov_len); return rdb_vos_update(lc, index, oid, n, akeys, values); } static inline int rdb_lc_punch(daos_handle_t lc, uint64_t index, rdb_oid_t oid, int n, daos_iov_t akeys[]) { if (n > 0) D_DEBUG(DB_TRACE, "lc="DF_X64" index="DF_U64" oid="DF_X64 " n=%d akeys[0]=<%p, %zd>\n", lc.cookie, index, oid, n, akeys[0].iov_buf, akeys[0].iov_len); else D_DEBUG(DB_TRACE, "lc="DF_X64" index="DF_U64" oid="DF_X64 " n=%d\n", lc.cookie, index, oid, n); return rdb_vos_punch(lc, index, oid, n, akeys); } /* Discard index range [low, high]. */ static inline int rdb_lc_discard(daos_handle_t lc, uint64_t low, uint64_t high) { D_DEBUG(DB_TRACE, "lc="DF_X64" low="DF_U64" high="DF_U64"\n", lc.cookie, low, high); return rdb_vos_discard(lc, low, high); } /* Aggregate index range [0, high] and yield from time to time. */ static inline int rdb_lc_aggregate(daos_handle_t lc, uint64_t high) { D_DEBUG(DB_TRACE, "lc="DF_X64" high="DF_U64"\n", lc.cookie, high); return rdb_vos_aggregate(lc, high); } static inline int rdb_lc_lookup(daos_handle_t lc, uint64_t index, rdb_oid_t oid, daos_iov_t *akey, daos_iov_t *value) { D_DEBUG(DB_TRACE, "lc="DF_X64" index="DF_U64" oid="DF_X64 " akey=<%p, %zd> value=<%p, %zd, %zd>\n", lc.cookie, index, oid, akey->iov_buf, akey->iov_len, value->iov_buf, value->iov_buf_len, value->iov_len); if (value->iov_buf == NULL) return rdb_vos_fetch_addr(lc, index, oid, akey, value); else return rdb_vos_fetch(lc, index, oid, akey, value); } static inline int rdb_lc_iter_fetch(daos_handle_t lc, uint64_t index, rdb_oid_t oid, enum rdb_probe_opc opc, daos_iov_t *akey_in, daos_iov_t *akey_out, daos_iov_t *value) { D_DEBUG(DB_TRACE, "lc="DF_X64" index="DF_U64" oid="DF_X64" opc=%d" " akey_in=<%p, %zd> akey_out=<%p, %zd> value=<%p, %zd, %zd>\n", lc.cookie, index, oid, opc, akey_in == NULL ? NULL : akey_in->iov_buf, akey_in == NULL ? 0 : akey_in->iov_len, akey_out == NULL ? NULL : akey_out->iov_buf, akey_out == NULL ? 0 : akey_out->iov_len, value == NULL ? NULL : value->iov_buf, value == NULL ? 0 : value->iov_buf_len, value == NULL ? 0 : value->iov_len); return rdb_vos_iter_fetch(lc, index, oid, opc, akey_in, akey_out, value); } static inline int rdb_lc_iterate(daos_handle_t lc, uint64_t index, rdb_oid_t oid, bool backward, rdb_iterate_cb_t cb, void *arg) { D_DEBUG(DB_TRACE, "lc="DF_X64" index="DF_U64" oid="DF_X64 " backward=%d\n", lc.cookie, index, oid, backward); return rdb_vos_iterate(lc, index, oid, backward, cb, arg); } #endif /* RDB_INTERNAL_H */
/* * The Spread Toolkit. * * The contents of this file are subject to the Spread Open-Source * License, Version 1.0 (the ``License''); you may not use * this file except in compliance with the License. You may obtain a * copy of the License at: * * http://www.spread.org/license/ * * or in the file ``license.txt'' found in this distribution. * * Software distributed under the License is distributed on an AS IS basis, * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License * for the specific language governing rights and limitations under the * License. * * The Creators of Spread are: * Yair Amir, Michal Miskin-Amir, Jonathan Stanton, John Schultz. * * Copyright (C) 1993-2006 Spread Concepts LLC <info@spreadconcepts.com> * * All Rights Reserved. * * Major Contributor(s): * --------------- * Ryan Caudy rcaudy@gmail.com - contributions to process groups. * Claudiu Danilov claudiu@acm.org - scalable wide area support. * Cristina Nita-Rotaru crisn@cs.purdue.edu - group communication security. * Theo Schlossnagle jesus@omniti.com - Perl, autoconf, old skiplist. * Dan Schoenblum dansch@cnds.jhu.edu - Java interface. * */ #ifndef INC_ALARM #define INC_ALARM #include <stdio.h> #include "arch.h" #define DEBUG 0x00000001 #define EXIT 0x00000002 #define PRINT 0x00000004 /* new type to replace general prints */ #define SYSTEM 0x00000004 #define DATA_LINK 0x00000010 #define NETWORK 0x00000020 #define PROTOCOL 0x00000040 #define SESSION 0x00000080 #define CONF 0x00000100 #define MEMB 0x00000200 #define FLOW_CONTROL 0x00000400 #define STATUS 0x00000800 #define EVENTS 0x00001000 #define GROUPS 0x00002000 #define HOP 0x00004000 #define OBJ_HANDLER 0x00008000 #define MEMORY 0x00010000 #define ROUTE 0x00020000 #define QOS 0x00040000 #define RING 0x00080000 #define TCP_HOP 0x00100000 #define SKIPLIST 0x00200000 #define ACM 0x00400000 #define SECURITY 0x00800000 #define ALL 0xffffffff #define NONE 0x00000000 /* Priority levels */ #define SPLOG_DEBUG 1 /* Program information that is only useful for debugging. Will normally be turned off in operation. */ #define SPLOG_INFO 2 /* Program reports information that may be useful for performance tuning, analysis, or operational checks. */ #define SPLOG_WARNING 3 /* Program encountered a situation that is not erroneous, but is uncommon and may indicate an error. */ #define SPLOG_ERROR 4 /* Program encountered an error that can be recovered from. */ #define SPLOG_CRITICAL 5 /* Program will not exit, but has only temporarily recovered and without help may soon fail. */ #define SPLOG_FATAL 6 /* Program will exit() or abort(). */ #define SPLOG_PRINT 7 /* Program should always print this information */ #define SPLOG_PRINT_NODATE 8 /* Program should always print this information, but the datestamp should be omitted. */ #ifdef HAVE_GOOD_VARGS void Alarmp( int16 priority, int32 type, char *message, ...); void Alarm( int32 type, char *message, ...); #else void Alarm(); #endif void Alarm_set_output(char *filename); void Alarm_enable_timestamp(char *format); void Alarm_disable_timestamp(void); void Alarm_set_types(int32 mask); void Alarm_clear_types(int32 mask); int32 Alarm_get_types(void); void Alarm_set_priority(int16 priority); int16 Alarm_get_priority(void); void Alarm_set_interactive(void); int Alarm_get_interactive(void); #define IP1( address ) ( ( 0xFF000000 & (address) ) >> 24 ) #define IP2( address ) ( ( 0x00FF0000 & (address) ) >> 16 ) #define IP3( address ) ( ( 0x0000FF00 & (address) ) >> 8 ) #define IP4( address ) ( ( 0x000000FF & (address) ) ) #endif /* INC_ALARM */
/* $info$ category: backend ~ IR to host code generation tags: backend|shared $end_info$ */ #pragma once #include <FEXCore/Utils/CompilerDefs.h> #include <cstdint> #include <string> namespace FEXCore { namespace IR { class IRListView; class RegisterAllocationData; } namespace Core { struct DebugData; struct ThreadState; struct CpuStateFrame; } namespace CodeSerialize { struct CodeObjectFileSection; } namespace CPU { class InterpreterCore; class JITCore; class LLVMCore; class CPUBackend { public: virtual ~CPUBackend() = default; /** * @return The name of this backend */ [[nodiscard]] virtual std::string GetName() = 0; /** * @brief Tells this CPUBackend to compile code for the provided IR and DebugData * * The returned pointer needs to be long lived and be executable in the host environment * FEXCore's frontend will store this pointer in to a cache for the current RIP when this was executed * * This is a thread specific compilation unit since there is one CPUBackend per guest thread * * If NeedsOpDispatch is returning false then IR and DebugData may be null and the expectation is that the code will still compile * FEXCore::Core::ThreadState* is valid at the time of compilation. * * @param IR - IR that maps to the IR for this RIP * @param DebugData - Debug data that is available for this IR indirectly * * @return An executable function pointer that is theoretically compiled from this point. * Is actually a function pointer of type `void (FEXCore::Core::ThreadState *Thread) */ [[nodiscard]] virtual void *CompileCode(uint64_t Entry, FEXCore::IR::IRListView const *IR, FEXCore::Core::DebugData *DebugData, FEXCore::IR::RegisterAllocationData *RAData) = 0; /** * @brief Relocates a block of code from the JIT code object cache * * @param Entry - RIP of the entry * @param SerializationData - Serialization data referring to the object cache for `Entry` * * @return An executable function pointer relocated from the cache object */ [[nodiscard]] virtual void *RelocateJITObjectCode(uint64_t Entry, CodeSerialize::CodeObjectFileSection const *SerializationData) { return nullptr; } /** * @brief Function for mapping memory in to the CPUBackend's visible space. Allows setting up virtual mappings if required * * @return Currently unused */ [[nodiscard]] virtual void *MapRegion(void *HostPtr, uint64_t GuestPtr, uint64_t Size) = 0; /** * @brief This is post-setup initialization that is called just before code executino * * Guest memory is available at this point and ThreadState is valid */ virtual void Initialize() {} /** * @brief Lets FEXCore know if this CPUBackend needs IR and DebugData for CompileCode * * This is useful if the FEXCore Frontend hits an x86-64 instruction that isn't understood but can continue regardless * * This is useful for example, a VM based CPUbackend * * @return true if it needs the IR */ [[nodiscard]] virtual bool NeedsOpDispatch() = 0; void ExecuteDispatch(FEXCore::Core::CpuStateFrame *Frame) { DispatchPtr(Frame); } virtual void ClearCache() {} virtual bool IsAddressInJITCode(uint64_t Address, bool IncludeDispatcher = true) const { return false; } /** * @brief Does this CPUBackend need its IR to stick around for correct emulation * * This should only be used on the interpreter, all other backends can clear their IR */ virtual bool NeedsRetainedIRCopy() const { return false; } /** * @brief Clear any relocations after JIT compiling */ virtual void ClearRelocations() {} using AsmDispatch = FEX_NAKED void(*)(FEXCore::Core::CpuStateFrame *Frame); using JITCallback = FEX_NAKED void(*)(FEXCore::Core::CpuStateFrame *Frame, uint64_t RIP); JITCallback CallbackPtr{}; protected: AsmDispatch DispatchPtr{}; }; } }
#ifndef _JRATE_MEM_DISPLAY_REFERENCE_CHECKER_H_ #define _JRATE_MEM_DISPLAY_REFERENCE_CHECKER_H_ #include <jrate/mem/IMemoryArea.h> #define DISPLAY_SIZE 64 namespace jrate { namespace mem { class DisplayRefChecker; typedef DisplayRefChecker DisplayRefChecker_t; /** * This class implements a display based memory reference * checker. For a description of the technique used to * implement diplay based reference checks please see: * "A. Corsaro, R. Cytron, Efficient Memory Reference Checks * in Real-Time Java, LCTES 2003". * * @author Angelo Corsaro <corsaro@cse.wustl.edu> */ class DisplayRefChecker { public: DisplayRefChecker(); template <typename T> DisplayRefChecker(T* ma) { typeID_ = ma->typeID(); display_[0] = (size_t)this; depth_ = 0; } template <typename T> void init(T* ma) { typeID_ = ma->typeID(); display_[0] = (size_t)this; depth_ = 0; } ~DisplayRefChecker(); public: bool checkReference(const jrate::mem::DisplayRefChecker& from); bool checkReference(); public: void validate(jrate::mem::DisplayRefChecker& parent); void invalidate(); public: inline bool isPrimordial() { return typeID_ & jrate::mem::PRIMORDIAL_MEMORY; } private: int typeID_; int depth_; // TODO: Currently the display is statically allocated, we should // allocate this in the memory area that owns it. size_t display_[DISPLAY_SIZE]; }; } /* jrate */ } /* mem */ #endif // _JRATE_MEM_DISPLAY_REFERENCE_CHECKER_H_
/*- * SPDX-License-Identifier: BSD-2-Clause-FreeBSD * * Copyright (c) 2001 Katsurajima Naoto <raven@katsurajima.seya.yokohama.jp> * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHERIN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF * SUCH DAMAGE. * */ #ifdef HAVE_KERNEL_OPTION_HEADERS #include "opt_snd.h" #endif #include <dev/sound/pcm/sound.h> #include <dev/sound/pcm/ac97.h> #include <dev/sound/pci/spicds.h> #include <dev/sound/pci/envy24.h> #include <dev/pci/pcireg.h> #include <dev/pci/pcivar.h> #include "mixer_if.h" SND_DECLARE_FILE("$FreeBSD$"); static MALLOC_DEFINE(M_ENVY24, "envy24", "envy24 audio"); /* -------------------------------------------------------------------- */ struct sc_info; #define ENVY24_PLAY_CHNUM 10 #define ENVY24_REC_CHNUM 12 #define ENVY24_PLAY_BUFUNIT (4 /* byte/sample */ * 10 /* channel */) #define ENVY24_REC_BUFUNIT (4 /* byte/sample */ * 12 /* channel */) #define ENVY24_SAMPLE_NUM 4096 #define ENVY24_TIMEOUT 1000 #define ENVY24_DEFAULT_FORMAT SND_FORMAT(AFMT_S16_LE, 2, 0) #define ENVY24_NAMELEN 32 #define SDA_GPIO 0x10 #define SCL_GPIO 0x20 struct envy24_sample { volatile u_int32_t buffer; }; typedef struct envy24_sample sample32_t; /* channel registers */ struct sc_chinfo { struct snd_dbuf *buffer; struct pcm_channel *channel; struct sc_info *parent; int dir; unsigned num; /* hw channel number */ /* channel information */ u_int32_t format; u_int32_t speed; u_int32_t blk; /* hw block size(dword) */ /* format conversion structure */ u_int8_t *data; unsigned int size; /* data buffer size(byte) */ int unit; /* sample size(byte) */ unsigned int offset; /* samples number offset */ void (*emldma)(struct sc_chinfo *); /* flags */ int run; }; /* codec interface entrys */ struct codec_entry { void *(*create)(device_t dev, void *devinfo, int dir, int num); void (*destroy)(void *codec); void (*init)(void *codec); void (*reinit)(void *codec); void (*setvolume)(void *codec, int dir, unsigned int left, unsigned int right); void (*setrate)(void *codec, int which, int rate); }; /* system configuration information */ struct cfg_info { char *name; u_int16_t subvendor, subdevice; u_int8_t scfg, acl, i2s, spdif; u_int8_t gpiomask, gpiostate, gpiodir; u_int8_t cdti, cclk, cs, cif, type; u_int8_t free; struct codec_entry *codec; }; /* device private data */ struct sc_info { device_t dev; struct mtx *lock; /* Control/Status registor */ struct resource *cs; int csid; bus_space_tag_t cst; bus_space_handle_t csh; /* DDMA registor */ struct resource *ddma; int ddmaid; bus_space_tag_t ddmat; bus_space_handle_t ddmah; /* Consumer Section DMA Channel Registers */ struct resource *ds; int dsid; bus_space_tag_t dst; bus_space_handle_t dsh; /* MultiTrack registor */ struct resource *mt; int mtid; bus_space_tag_t mtt; bus_space_handle_t mth; /* DMA tag */ bus_dma_tag_t dmat; /* IRQ resource */ struct resource *irq; int irqid; void *ih; /* system configuration data */ struct cfg_info *cfg; /* ADC/DAC number and info */ int adcn, dacn; void *adc[4], *dac[4]; /* mixer control data */ u_int32_t src; u_int8_t left[ENVY24_CHAN_NUM]; u_int8_t right[ENVY24_CHAN_NUM]; /* Play/Record DMA fifo */ sample32_t *pbuf; sample32_t *rbuf; u_int32_t psize, rsize; /* DMA buffer size(byte) */ u_int16_t blk[2]; /* transfer check blocksize(dword) */ bus_dmamap_t pmap, rmap; bus_addr_t paddr, raddr; /* current status */ u_int32_t speed; int run[2]; u_int16_t intr[2]; struct pcmchan_caps caps[2]; /* channel info table */ unsigned chnum; struct sc_chinfo chan[11]; }; /* -------------------------------------------------------------------- */ /* * prototypes */ /* DMA emulator */ static void envy24_p8u(struct sc_chinfo *); static void envy24_p16sl(struct sc_chinfo *); static void envy24_p32sl(struct sc_chinfo *); static void envy24_r16sl(struct sc_chinfo *); static void envy24_r32sl(struct sc_chinfo *); /* channel interface */ static void *envy24chan_init(kobj_t, void *, struct snd_dbuf *, struct pcm_channel *, int); static int envy24chan_setformat(kobj_t, void *, u_int32_t); static u_int32_t envy24chan_setspeed(kobj_t, void *, u_int32_t); static u_int32_t envy24chan_setblocksize(kobj_t, void *, u_int32_t); static int envy24chan_trigger(kobj_t, void *, int); static u_int32_t envy24chan_getptr(kobj_t, void *); static struct pcmchan_caps *envy24chan_getcaps(kobj_t, void *); /* mixer interface */ static int envy24mixer_init(struct snd_mixer *); static int envy24mixer_reinit(struct snd_mixer *); static int envy24mixer_uninit(struct snd_mixer *); static int envy24mixer_set(struct snd_mixer *, unsigned, unsigned, unsigned); static u_int32_t envy24mixer_setrecsrc(struct snd_mixer *, u_int32_t); /* M-Audio Delta series AK4524 access interface */ static void *envy24_delta_ak4524_create(device_t, void *, int, int); static void envy24_delta_ak4524_destroy(void *); static void envy24_delta_ak4524_init(void *); static void envy24_delta_ak4524_reinit(void *); static void envy24_delta_ak4524_setvolume(void *, int, unsigned int, unsigned int); /* -------------------------------------------------------------------- */ /* system constant tables */ /* API -> hardware channel map */ static unsigned envy24_chanmap[ENVY24_CHAN_NUM] = { ENVY24_CHAN_PLAY_SPDIF, /* 0 */ ENVY24_CHAN_PLAY_DAC1, /* 1 */ ENVY24_CHAN_PLAY_DAC2, /* 2 */ ENVY24_CHAN_PLAY_DAC3, /* 3 */ ENVY24_CHAN_PLAY_DAC4, /* 4 */ ENVY24_CHAN_REC_MIX, /* 5 */ ENVY24_CHAN_REC_SPDIF, /* 6 */ ENVY24_CHAN_REC_ADC1, /* 7 */ ENVY24_CHAN_REC_ADC2, /* 8 */ ENVY24_CHAN_REC_ADC3, /* 9 */ ENVY24_CHAN_REC_ADC4, /* 10 */ }; /* mixer -> API channel map. see above */ static int envy24_mixmap[] = { -1, /* Master output level. It is depend on codec support */ -1, /* Treble level of all output channels */ -1, /* Bass level of all output channels */ -1, /* Volume of synthesier input */ 0, /* Output level for the audio device */ -1, /* Output level for the PC speaker */ 7, /* line in jack */ -1, /* microphone jack */ -1, /* CD audio input */ -1, /* Recording monitor */ 1, /* alternative codec */ -1, /* global recording level */ -1, /* Input gain */ -1, /* Output gain */ 8, /* Input source 1 */ 9, /* Input source 2 */ 10, /* Input source 3 */ 6, /* Digital (input) 1 */ -1, /* Digital (input) 2 */ -1, /* Digital (input) 3 */ -1, /* Phone input */ -1, /* Phone output */ -1, /* Video/TV (audio) in */ -1, /* Radio in */ -1, /* Monitor volume */ }; /* variable rate audio */ static u_int32_t envy24_speed[] = { 96000, 88200, 64000, 48000, 44100, 32000, 24000, 22050, 16000, 12000, 11025, 9600, 8000, 0 }; /* known boards configuration */ static struct codec_entry delta_codec = { envy24_delta_ak4524_create, envy24_delta_ak4524_destroy, envy24_delta_ak4524_init, envy24_delta_ak4524_reinit, envy24_delta_ak4524_setvolume, NULL, /* setrate */ }; static struct cfg_info cfg_table[] = { { "Envy24 audio (M Audio Delta Dio 2496)", 0x1412, 0xd631, 0x10, 0x80, 0xf0, 0x03, 0x02, 0xc0, 0xfd, 0x10, 0x20, 0x40, 0x00, 0x00, 0x00, &delta_codec, }, { "Envy24 audio (Terratec DMX 6fire)", 0x153b, 0x1138, 0x2f, 0x80, 0xf0, 0x03, 0xc0, 0xff, 0x7f, 0x10, 0x20, 0x01, 0x01, 0x00, 0x00, &delta_codec, }, { "Envy24 audio (M Audio Audiophile 2496)", 0x1412, 0xd634, 0x10, 0x80, 0x72, 0x03, 0x04, 0xfe, 0xfb, 0x08, 0x02, 0x20, 0x00, 0x01, 0x00, &delta_codec, }, { "Envy24 audio (M Audio Delta 66)", 0x1412, 0xd632, 0x15, 0x80, 0xf0, 0x03, 0x02, 0xc0, 0xfd, 0x10, 0x20, 0x40, 0x00, 0x00, 0x00, &delta_codec, }, { "Envy24 audio (M Audio Delta 44)", 0x1412, 0xd633, 0x15, 0x80, 0xf0, 0x00, 0x02, 0xc0, 0xfd, 0x10, 0x20, 0x40, 0x00, 0x00, 0x00, &delta_codec, }, { "Envy24 audio (M Audio Delta 1010)", 0x1412, 0xd630, 0x1f, 0x80, 0xf0, 0x03, 0x22, 0xd0, 0xdd, 0x10, 0x20, 0x40, 0x00, 0x00, 0x00, &delta_codec, }, { "Envy24 audio (M Audio Delta 1010LT)", 0x1412, 0xd63b, 0x1f, 0x80, 0x72, 0x03, 0x04, 0x7e, 0xfb, 0x08, 0x02, 0x70, 0x00, 0x00, 0x00, &delta_codec, }, { "Envy24 audio (Terratec EWX 2496)", 0x153b, 0x1130, 0x10, 0x80, 0xf0, 0x03, 0xc0, 0x3f, 0x3f, 0x10, 0x20, 0x01, 0x01, 0x00, 0x00, &delta_codec, }, { "Envy24 audio (Generic)", 0, 0, 0x0f, 0x00, 0x01, 0x03, 0xff, 0x00, 0x00, 0x10, 0x20, 0x40, 0x00, 0x00, 0x00, &delta_codec, /* default codec routines */ } }; static u_int32_t envy24_recfmt[] = { SND_FORMAT(AFMT_S16_LE, 2, 0), SND_FORMAT(AFMT_S32_LE, 2, 0), 0 }; static struct pcmchan_caps envy24_reccaps = {8000, 96000, envy24_recfmt, 0}; static u_int32_t envy24_playfmt[] = { SND_FORMAT(AFMT_U8, 2, 0), SND_FORMAT(AFMT_S16_LE, 2, 0), SND_FORMAT(AFMT_S32_LE, 2, 0), 0 }; static struct pcmchan_caps envy24_playcaps = {8000, 96000, envy24_playfmt, 0}; struct envy24_emldma { u_int32_t format; void (*emldma)(struct sc_chinfo *); int unit; }; static struct envy24_emldma envy24_pemltab[] = { {SND_FORMAT(AFMT_U8, 2, 0), envy24_p8u, 2}, {SND_FORMAT(AFMT_S16_LE, 2, 0), envy24_p16sl, 4}, {SND_FORMAT(AFMT_S32_LE, 2, 0), envy24_p32sl, 8}, {0, NULL, 0} }; static struct envy24_emldma envy24_remltab[] = { {SND_FORMAT(AFMT_S16_LE, 2, 0), envy24_r16sl, 4}, {SND_FORMAT(AFMT_S32_LE, 2, 0), envy24_r32sl, 8}, {0, NULL, 0} }; /* -------------------------------------------------------------------- */ /* common routines */ static u_int32_t envy24_rdcs(struct sc_info *sc, int regno, int size) { switch (size) { case 1: return bus_space_read_1(sc->cst, sc->csh, regno); case 2: return bus_space_read_2(sc->cst, sc->csh, regno); case 4: return bus_space_read_4(sc->cst, sc->csh, regno); default: return 0xffffffff; } } static void envy24_wrcs(struct sc_info *sc, int regno, u_int32_t data, int size) { switch (size) { case 1: bus_space_write_1(sc->cst, sc->csh, regno, data); break; case 2: bus_space_write_2(sc->cst, sc->csh, regno, data); break; case 4: bus_space_write_4(sc->cst, sc->csh, regno, data); break; } } static u_int32_t envy24_rdmt(struct sc_info *sc, int regno, int size) { switch (size) { case 1: return bus_space_read_1(sc->mtt, sc->mth, regno); case 2: return bus_space_read_2(sc->mtt, sc->mth, regno); case 4: return bus_space_read_4(sc->mtt, sc->mth, regno); default: return 0xffffffff; } } static void envy24_wrmt(struct sc_info *sc, int regno, u_int32_t data, int size) { switch (size) { case 1: bus_space_write_1(sc->mtt, sc->mth, regno, data); break; case 2: bus_space_write_2(sc->mtt, sc->mth, regno, data); break; case 4: bus_space_write_4(sc->mtt, sc->mth, regno, data); break; } } static u_int32_t envy24_rdci(struct sc_info *sc, int regno) { envy24_wrcs(sc, ENVY24_CCS_INDEX, regno, 1); return envy24_rdcs(sc, ENVY24_CCS_DATA, 1); } static void envy24_wrci(struct sc_info *sc, int regno, u_int32_t data) { envy24_wrcs(sc, ENVY24_CCS_INDEX, regno, 1); envy24_wrcs(sc, ENVY24_CCS_DATA, data, 1); } /* -------------------------------------------------------------------- */ /* I2C port/E2PROM access routines */ static int envy24_rdi2c(struct sc_info *sc, u_int32_t dev, u_int32_t addr) { u_int32_t data; int i; #if(0) device_printf(sc->dev, "envy24_rdi2c(sc, 0x%02x, 0x%02x)\n", dev, addr); #endif for (i = 0; i < ENVY24_TIMEOUT; i++) { data = envy24_rdcs(sc, ENVY24_CCS_I2CSTAT, 1); if ((data & ENVY24_CCS_I2CSTAT_BSY) == 0) break; DELAY(32); /* 31.25kHz */ } if (i == ENVY24_TIMEOUT) { return -1; } envy24_wrcs(sc, ENVY24_CCS_I2CADDR, addr, 1); envy24_wrcs(sc, ENVY24_CCS_I2CDEV, (dev & ENVY24_CCS_I2CDEV_ADDR) | ENVY24_CCS_I2CDEV_RD, 1); for (i = 0; i < ENVY24_TIMEOUT; i++) { data = envy24_rdcs(sc, ENVY24_CCS_I2CSTAT, 1); if ((data & ENVY24_CCS_I2CSTAT_BSY) == 0) break; DELAY(32); /* 31.25kHz */ } if (i == ENVY24_TIMEOUT) { return -1; } data = envy24_rdcs(sc, ENVY24_CCS_I2CDATA, 1); #if(0) device_printf(sc->dev, "envy24_rdi2c(): return 0x%x\n", data); #endif return (int)data; } #if 0 static int envy24_wri2c(struct sc_info *sc, u_int32_t dev, u_int32_t addr, u_int32_t data) { u_int32_t tmp; int i; #if(0) device_printf(sc->dev, "envy24_rdi2c(sc, 0x%02x, 0x%02x)\n", dev, addr); #endif for (i = 0; i < ENVY24_TIMEOUT; i++) { tmp = envy24_rdcs(sc, ENVY24_CCS_I2CSTAT, 1); if ((tmp & ENVY24_CCS_I2CSTAT_BSY) == 0) break; DELAY(32); /* 31.25kHz */ } if (i == ENVY24_TIMEOUT) { return -1; } envy24_wrcs(sc, ENVY24_CCS_I2CADDR, addr, 1); envy24_wrcs(sc, ENVY24_CCS_I2CDATA, data, 1); envy24_wrcs(sc, ENVY24_CCS_I2CDEV, (dev & ENVY24_CCS_I2CDEV_ADDR) | ENVY24_CCS_I2CDEV_WR, 1); for (i = 0; i < ENVY24_TIMEOUT; i++) { data = envy24_rdcs(sc, ENVY24_CCS_I2CSTAT, 1); if ((data & ENVY24_CCS_I2CSTAT_BSY) == 0) break; DELAY(32); /* 31.25kHz */ } if (i == ENVY24_TIMEOUT) { return -1; } return 0; } #endif static int envy24_rdrom(struct sc_info *sc, u_int32_t addr) { u_int32_t data; #if(0) device_printf(sc->dev, "envy24_rdrom(sc, 0x%02x)\n", addr); #endif data = envy24_rdcs(sc, ENVY24_CCS_I2CSTAT, 1); if ((data & ENVY24_CCS_I2CSTAT_ROM) == 0) { #if(0) device_printf(sc->dev, "envy24_rdrom(): E2PROM not presented\n"); #endif return -1; } return envy24_rdi2c(sc, ENVY24_CCS_I2CDEV_ROM, addr); } static struct cfg_info * envy24_rom2cfg(struct sc_info *sc) { struct cfg_info *buff; int size; int i; #if(0) device_printf(sc->dev, "envy24_rom2cfg(sc)\n"); #endif size = envy24_rdrom(sc, ENVY24_E2PROM_SIZE); if (size < ENVY24_E2PROM_GPIODIR + 1) { #if(0) device_printf(sc->dev, "envy24_rom2cfg(): ENVY24_E2PROM_SIZE-->%d\n", size); #endif return NULL; } buff = malloc(sizeof(*buff), M_ENVY24, M_NOWAIT); if (buff == NULL) { #if(0) device_printf(sc->dev, "envy24_rom2cfg(): malloc()\n"); #endif return NULL; } buff->free = 1; buff->subvendor = envy24_rdrom(sc, ENVY24_E2PROM_SUBVENDOR) << 8; buff->subvendor += envy24_rdrom(sc, ENVY24_E2PROM_SUBVENDOR + 1); buff->subdevice = envy24_rdrom(sc, ENVY24_E2PROM_SUBDEVICE) << 8; buff->subdevice += envy24_rdrom(sc, ENVY24_E2PROM_SUBDEVICE + 1); buff->scfg = envy24_rdrom(sc, ENVY24_E2PROM_SCFG); buff->acl = envy24_rdrom(sc, ENVY24_E2PROM_ACL); buff->i2s = envy24_rdrom(sc, ENVY24_E2PROM_I2S); buff->spdif = envy24_rdrom(sc, ENVY24_E2PROM_SPDIF); buff->gpiomask = envy24_rdrom(sc, ENVY24_E2PROM_GPIOMASK); buff->gpiostate = envy24_rdrom(sc, ENVY24_E2PROM_GPIOSTATE); buff->gpiodir = envy24_rdrom(sc, ENVY24_E2PROM_GPIODIR); for (i = 0; cfg_table[i].subvendor != 0 || cfg_table[i].subdevice != 0; i++) if (cfg_table[i].subvendor == buff->subvendor && cfg_table[i].subdevice == buff->subdevice) break; buff->name = cfg_table[i].name; buff->codec = cfg_table[i].codec; return buff; } static void envy24_cfgfree(struct cfg_info *cfg) { if (cfg == NULL) return; if (cfg->free) free(cfg, M_ENVY24); return; } /* -------------------------------------------------------------------- */ /* AC'97 codec access routines */ #if 0 static int envy24_coldcd(struct sc_info *sc) { u_int32_t data; int i; #if(0) device_printf(sc->dev, "envy24_coldcd()\n"); #endif envy24_wrmt(sc, ENVY24_MT_AC97CMD, ENVY24_MT_AC97CMD_CLD, 1); DELAY(10); envy24_wrmt(sc, ENVY24_MT_AC97CMD, 0, 1); DELAY(1000); for (i = 0; i < ENVY24_TIMEOUT; i++) { data = envy24_rdmt(sc, ENVY24_MT_AC97CMD, 1); if (data & ENVY24_MT_AC97CMD_RDY) { return 0; } } return -1; } #endif static int envy24_slavecd(struct sc_info *sc) { u_int32_t data; int i; #if(0) device_printf(sc->dev, "envy24_slavecd()\n"); #endif envy24_wrmt(sc, ENVY24_MT_AC97CMD, ENVY24_MT_AC97CMD_CLD | ENVY24_MT_AC97CMD_WRM, 1); DELAY(10); envy24_wrmt(sc, ENVY24_MT_AC97CMD, 0, 1); DELAY(1000); for (i = 0; i < ENVY24_TIMEOUT; i++) { data = envy24_rdmt(sc, ENVY24_MT_AC97CMD, 1); if (data & ENVY24_MT_AC97CMD_RDY) { return 0; } } return -1; } #if 0 static int envy24_rdcd(kobj_t obj, void *devinfo, int regno) { struct sc_info *sc = (struct sc_info *)devinfo; u_int32_t data; int i; #if(0) device_printf(sc->dev, "envy24_rdcd(obj, sc, 0x%02x)\n", regno); #endif envy24_wrmt(sc, ENVY24_MT_AC97IDX, (u_int32_t)regno, 1); envy24_wrmt(sc, ENVY24_MT_AC97CMD, ENVY24_MT_AC97CMD_RD, 1); for (i = 0; i < ENVY24_TIMEOUT; i++) { data = envy24_rdmt(sc, ENVY24_MT_AC97CMD, 1); if ((data & ENVY24_MT_AC97CMD_RD) == 0) break; } data = envy24_rdmt(sc, ENVY24_MT_AC97DLO, 2); #if(0) device_printf(sc->dev, "envy24_rdcd(): return 0x%x\n", data); #endif return (int)data; } static int envy24_wrcd(kobj_t obj, void *devinfo, int regno, u_int16_t data) { struct sc_info *sc = (struct sc_info *)devinfo; u_int32_t cmd; int i; #if(0) device_printf(sc->dev, "envy24_wrcd(obj, sc, 0x%02x, 0x%04x)\n", regno, data); #endif envy24_wrmt(sc, ENVY24_MT_AC97IDX, (u_int32_t)regno, 1); envy24_wrmt(sc, ENVY24_MT_AC97DLO, (u_int32_t)data, 2); envy24_wrmt(sc, ENVY24_MT_AC97CMD, ENVY24_MT_AC97CMD_WR, 1); for (i = 0; i < ENVY24_TIMEOUT; i++) { cmd = envy24_rdmt(sc, ENVY24_MT_AC97CMD, 1); if ((cmd & ENVY24_MT_AC97CMD_WR) == 0) break; } return 0; } static kobj_method_t envy24_ac97_methods[] = { KOBJMETHOD(ac97_read, envy24_rdcd), KOBJMETHOD(ac97_write, envy24_wrcd), KOBJMETHOD_END }; AC97_DECLARE(envy24_ac97); #endif /* -------------------------------------------------------------------- */ /* GPIO access routines */ static u_int32_t envy24_gpiord(struct sc_info *sc) { return envy24_rdci(sc, ENVY24_CCI_GPIODAT); } static void envy24_gpiowr(struct sc_info *sc, u_int32_t data) { #if(0) device_printf(sc->dev, "envy24_gpiowr(sc, 0x%02x)\n", data & 0xff); return; #endif envy24_wrci(sc, ENVY24_CCI_GPIODAT, data); return; } #if 0 static u_int32_t envy24_gpiogetmask(struct sc_info *sc) { return envy24_rdci(sc, ENVY24_CCI_GPIOMASK); } #endif static void envy24_gpiosetmask(struct sc_info *sc, u_int32_t mask) { envy24_wrci(sc, ENVY24_CCI_GPIOMASK, mask); return; } #if 0 static u_int32_t envy24_gpiogetdir(struct sc_info *sc) { return envy24_rdci(sc, ENVY24_CCI_GPIOCTL); } #endif static void envy24_gpiosetdir(struct sc_info *sc, u_int32_t dir) { envy24_wrci(sc, ENVY24_CCI_GPIOCTL, dir); return; } /* -------------------------------------------------------------------- */ /* Envy24 I2C through GPIO bit-banging */ struct envy24_delta_ak4524_codec { struct spicds_info *info; struct sc_info *parent; int dir; int num; int cs, cclk, cdti; }; static void envy24_gpio_i2c_ctl(void *codec, unsigned int scl, unsigned int sda) { u_int32_t data = 0; struct envy24_delta_ak4524_codec *ptr = codec; #if(0) device_printf(ptr->parent->dev, "--> %d, %d\n", scl, sda); #endif data = envy24_gpiord(ptr->parent); data &= ~(SDA_GPIO | SCL_GPIO); if (scl) data += SCL_GPIO; if (sda) data += SDA_GPIO; envy24_gpiowr(ptr->parent, data); return; } static void i2c_wrbit(void *codec, void (*ctrl)(void*, unsigned int, unsigned int), int bit) { struct envy24_delta_ak4524_codec *ptr = codec; unsigned int sda; if (bit) sda = 1; else sda = 0; ctrl(ptr, 0, sda); DELAY(I2C_DELAY); ctrl(ptr, 1, sda); DELAY(I2C_DELAY); ctrl(ptr, 0, sda); DELAY(I2C_DELAY); } static void i2c_start(void *codec, void (*ctrl)(void*, unsigned int, unsigned int)) { struct envy24_delta_ak4524_codec *ptr = codec; ctrl(ptr, 1, 1); DELAY(I2C_DELAY); ctrl(ptr, 1, 0); DELAY(I2C_DELAY); ctrl(ptr, 0, 0); DELAY(I2C_DELAY); } static void i2c_stop(void *codec, void (*ctrl)(void*, unsigned int, unsigned int)) { struct envy24_delta_ak4524_codec *ptr = codec; ctrl(ptr, 0, 0); DELAY(I2C_DELAY); ctrl(ptr, 1, 0); DELAY(I2C_DELAY); ctrl(ptr, 1, 1); DELAY(I2C_DELAY); } static void i2c_ack(void *codec, void (*ctrl)(void*, unsigned int, unsigned int)) { struct envy24_delta_ak4524_codec *ptr = codec; ctrl(ptr, 0, 1); DELAY(I2C_DELAY); ctrl(ptr, 1, 1); DELAY(I2C_DELAY); /* dummy, need routine to change gpio direction */ ctrl(ptr, 0, 1); DELAY(I2C_DELAY); } static void i2c_wr(void *codec, void (*ctrl)(void*, unsigned int, unsigned int), u_int32_t dev, int reg, u_int8_t val) { struct envy24_delta_ak4524_codec *ptr = codec; int mask; i2c_start(ptr, ctrl); for (mask = 0x80; mask != 0; mask >>= 1) i2c_wrbit(ptr, ctrl, dev & mask); i2c_ack(ptr, ctrl); if (reg != 0xff) { for (mask = 0x80; mask != 0; mask >>= 1) i2c_wrbit(ptr, ctrl, reg & mask); i2c_ack(ptr, ctrl); } for (mask = 0x80; mask != 0; mask >>= 1) i2c_wrbit(ptr, ctrl, val & mask); i2c_ack(ptr, ctrl); i2c_stop(ptr, ctrl); } /* -------------------------------------------------------------------- */ /* M-Audio Delta series AK4524 access interface routine */ static void envy24_delta_ak4524_ctl(void *codec, unsigned int cs, unsigned int cclk, unsigned int cdti) { u_int32_t data = 0; struct envy24_delta_ak4524_codec *ptr = codec; #if(0) device_printf(ptr->parent->dev, "--> %d, %d, %d\n", cs, cclk, cdti); #endif data = envy24_gpiord(ptr->parent); data &= ~(ptr->cs | ptr->cclk | ptr->cdti); if (cs) data += ptr->cs; if (cclk) data += ptr->cclk; if (cdti) data += ptr->cdti; envy24_gpiowr(ptr->parent, data); return; } static void * envy24_delta_ak4524_create(device_t dev, void *info, int dir, int num) { struct sc_info *sc = info; struct envy24_delta_ak4524_codec *buff = NULL; #if(0) device_printf(sc->dev, "envy24_delta_ak4524_create(dev, sc, %d, %d)\n", dir, num); #endif buff = malloc(sizeof(*buff), M_ENVY24, M_NOWAIT); if (buff == NULL) return NULL; if (dir == PCMDIR_REC && sc->adc[num] != NULL) buff->info = ((struct envy24_delta_ak4524_codec *)sc->adc[num])->info; else if (dir == PCMDIR_PLAY && sc->dac[num] != NULL) buff->info = ((struct envy24_delta_ak4524_codec *)sc->dac[num])->info; else buff->info = spicds_create(dev, buff, num, envy24_delta_ak4524_ctl); if (buff->info == NULL) { free(buff, M_ENVY24); return NULL; } buff->parent = sc; buff->dir = dir; buff->num = num; return (void *)buff; } static void envy24_delta_ak4524_destroy(void *codec) { struct envy24_delta_ak4524_codec *ptr = codec; if (ptr == NULL) return; #if(0) device_printf(ptr->parent->dev, "envy24_delta_ak4524_destroy()\n"); #endif if (ptr->dir == PCMDIR_PLAY) { if (ptr->parent->dac[ptr->num] != NULL) spicds_destroy(ptr->info); } else { if (ptr->parent->adc[ptr->num] != NULL) spicds_destroy(ptr->info); } free(codec, M_ENVY24); } static void envy24_delta_ak4524_init(void *codec) { #if 0 u_int32_t gpiomask, gpiodir; #endif struct envy24_delta_ak4524_codec *ptr = codec; if (ptr == NULL) return; #if(0) device_printf(ptr->parent->dev, "envy24_delta_ak4524_init()\n"); #endif /* gpiomask = envy24_gpiogetmask(ptr->parent); gpiomask &= ~(ENVY24_GPIO_AK4524_CDTI | ENVY24_GPIO_AK4524_CCLK | ENVY24_GPIO_AK4524_CS0 | ENVY24_GPIO_AK4524_CS1); envy24_gpiosetmask(ptr->parent, gpiomask); gpiodir = envy24_gpiogetdir(ptr->parent); gpiodir |= ENVY24_GPIO_AK4524_CDTI | ENVY24_GPIO_AK4524_CCLK | ENVY24_GPIO_AK4524_CS0 | ENVY24_GPIO_AK4524_CS1; envy24_gpiosetdir(ptr->parent, gpiodir); */ ptr->cs = ptr->parent->cfg->cs; #if 0 envy24_gpiosetmask(ptr->parent, ENVY24_GPIO_CS8414_STATUS); envy24_gpiosetdir(ptr->parent, ~ENVY24_GPIO_CS8414_STATUS); if (ptr->num == 0) ptr->cs = ENVY24_GPIO_AK4524_CS0; else ptr->cs = ENVY24_GPIO_AK4524_CS1; ptr->cclk = ENVY24_GPIO_AK4524_CCLK; #endif ptr->cclk = ptr->parent->cfg->cclk; ptr->cdti = ptr->parent->cfg->cdti; spicds_settype(ptr->info, ptr->parent->cfg->type); spicds_setcif(ptr->info, ptr->parent->cfg->cif); spicds_setformat(ptr->info, AK452X_FORMAT_I2S | AK452X_FORMAT_256FSN | AK452X_FORMAT_1X); spicds_setdvc(ptr->info, AK452X_DVC_DEMOFF); /* for the time being, init only first codec */ if (ptr->num == 0) spicds_init(ptr->info); /* 6fire rear input init test, set ptr->num to 1 for test */ if (ptr->parent->cfg->subvendor == 0x153b && \ ptr->parent->cfg->subdevice == 0x1138 && ptr->num == 100) { ptr->cs = 0x02; spicds_init(ptr->info); device_printf(ptr->parent->dev, "6fire rear input init\n"); i2c_wr(ptr, envy24_gpio_i2c_ctl, \ PCA9554_I2CDEV, PCA9554_DIR, 0x80); i2c_wr(ptr, envy24_gpio_i2c_ctl, \ PCA9554_I2CDEV, PCA9554_OUT, 0x02); } } static void envy24_delta_ak4524_reinit(void *codec) { struct envy24_delta_ak4524_codec *ptr = codec; if (ptr == NULL) return; #if(0) device_printf(ptr->parent->dev, "envy24_delta_ak4524_reinit()\n"); #endif spicds_reinit(ptr->info); } static void envy24_delta_ak4524_setvolume(void *codec, int dir, unsigned int left, unsigned int right) { struct envy24_delta_ak4524_codec *ptr = codec; if (ptr == NULL) return; #if(0) device_printf(ptr->parent->dev, "envy24_delta_ak4524_set()\n"); #endif spicds_set(ptr->info, dir, left, right); } /* There is no need for AK452[48] codec to set sample rate static void envy24_delta_ak4524_setrate(struct envy24_delta_ak4524_codec *codec, int which, int rate) { } */ /* -------------------------------------------------------------------- */ /* hardware access routeines */ static struct { u_int32_t speed; u_int32_t code; } envy24_speedtab[] = { {48000, ENVY24_MT_RATE_48000}, {24000, ENVY24_MT_RATE_24000}, {12000, ENVY24_MT_RATE_12000}, {9600, ENVY24_MT_RATE_9600}, {32000, ENVY24_MT_RATE_32000}, {16000, ENVY24_MT_RATE_16000}, {8000, ENVY24_MT_RATE_8000}, {96000, ENVY24_MT_RATE_96000}, {64000, ENVY24_MT_RATE_64000}, {44100, ENVY24_MT_RATE_44100}, {22050, ENVY24_MT_RATE_22050}, {11025, ENVY24_MT_RATE_11025}, {88200, ENVY24_MT_RATE_88200}, {0, 0x10} }; static u_int32_t envy24_setspeed(struct sc_info *sc, u_int32_t speed) { u_int32_t code; int i = 0; #if(0) device_printf(sc->dev, "envy24_setspeed(sc, %d)\n", speed); #endif if (speed == 0) { code = ENVY24_MT_RATE_SPDIF; /* external master clock */ envy24_slavecd(sc); } else { for (i = 0; envy24_speedtab[i].speed != 0; i++) { if (envy24_speedtab[i].speed == speed) break; } code = envy24_speedtab[i].code; } #if(0) device_printf(sc->dev, "envy24_setspeed(): speed %d/code 0x%04x\n", envy24_speedtab[i].speed, code); #endif if (code < 0x10) { envy24_wrmt(sc, ENVY24_MT_RATE, code, 1); code = envy24_rdmt(sc, ENVY24_MT_RATE, 1); code &= ENVY24_MT_RATE_MASK; for (i = 0; envy24_speedtab[i].code < 0x10; i++) { if (envy24_speedtab[i].code == code) break; } speed = envy24_speedtab[i].speed; } else speed = 0; #if(0) device_printf(sc->dev, "envy24_setspeed(): return %d\n", speed); #endif return speed; } static void envy24_setvolume(struct sc_info *sc, unsigned ch) { #if(0) device_printf(sc->dev, "envy24_setvolume(sc, %d)\n", ch); #endif if (sc->cfg->subvendor==0x153b && sc->cfg->subdevice==0x1138 ) { envy24_wrmt(sc, ENVY24_MT_VOLIDX, 16, 1); envy24_wrmt(sc, ENVY24_MT_VOLUME, 0x7f7f, 2); envy24_wrmt(sc, ENVY24_MT_VOLIDX, 17, 1); envy24_wrmt(sc, ENVY24_MT_VOLUME, 0x7f7f, 2); } envy24_wrmt(sc, ENVY24_MT_VOLIDX, ch * 2, 1); envy24_wrmt(sc, ENVY24_MT_VOLUME, 0x7f00 | sc->left[ch], 2); envy24_wrmt(sc, ENVY24_MT_VOLIDX, ch * 2 + 1, 1); envy24_wrmt(sc, ENVY24_MT_VOLUME, (sc->right[ch] << 8) | 0x7f, 2); } static void envy24_mutevolume(struct sc_info *sc, unsigned ch) { u_int32_t vol; #if(0) device_printf(sc->dev, "envy24_mutevolume(sc, %d)\n", ch); #endif vol = ENVY24_VOL_MUTE << 8 | ENVY24_VOL_MUTE; envy24_wrmt(sc, ENVY24_MT_VOLIDX, ch * 2, 1); envy24_wrmt(sc, ENVY24_MT_VOLUME, vol, 2); envy24_wrmt(sc, ENVY24_MT_VOLIDX, ch * 2 + 1, 1); envy24_wrmt(sc, ENVY24_MT_VOLUME, vol, 2); } static u_int32_t envy24_gethwptr(struct sc_info *sc, int dir) { int unit, regno; u_int32_t ptr, rtn; #if(0) device_printf(sc->dev, "envy24_gethwptr(sc, %d)\n", dir); #endif if (dir == PCMDIR_PLAY) { rtn = sc->psize / 4; unit = ENVY24_PLAY_BUFUNIT / 4; regno = ENVY24_MT_PCNT; } else { rtn = sc->rsize / 4; unit = ENVY24_REC_BUFUNIT / 4; regno = ENVY24_MT_RCNT; } ptr = envy24_rdmt(sc, regno, 2); rtn -= (ptr + 1); rtn /= unit; #if(0) device_printf(sc->dev, "envy24_gethwptr(): return %d\n", rtn); #endif return rtn; } static void envy24_updintr(struct sc_info *sc, int dir) { int regptr, regintr; u_int32_t mask, intr; u_int32_t ptr, size, cnt; u_int16_t blk; #if(0) device_printf(sc->dev, "envy24_updintr(sc, %d)\n", dir); #endif if (dir == PCMDIR_PLAY) { blk = sc->blk[0]; size = sc->psize / 4; regptr = ENVY24_MT_PCNT; regintr = ENVY24_MT_PTERM; mask = ~ENVY24_MT_INT_PMASK; } else { blk = sc->blk[1]; size = sc->rsize / 4; regptr = ENVY24_MT_RCNT; regintr = ENVY24_MT_RTERM; mask = ~ENVY24_MT_INT_RMASK; } ptr = size - envy24_rdmt(sc, regptr, 2) - 1; /* cnt = blk - ptr % blk - 1; if (cnt == 0) cnt = blk - 1; */ cnt = blk - 1; #if(0) device_printf(sc->dev, "envy24_updintr():ptr = %d, blk = %d, cnt = %d\n", ptr, blk, cnt); #endif envy24_wrmt(sc, regintr, cnt, 2); intr = envy24_rdmt(sc, ENVY24_MT_INT, 1); #if(0) device_printf(sc->dev, "envy24_updintr():intr = 0x%02x, mask = 0x%02x\n", intr, mask); #endif envy24_wrmt(sc, ENVY24_MT_INT, intr & mask, 1); #if(0) device_printf(sc->dev, "envy24_updintr():INT-->0x%02x\n", envy24_rdmt(sc, ENVY24_MT_INT, 1)); #endif return; } #if 0 static void envy24_maskintr(struct sc_info *sc, int dir) { u_int32_t mask, intr; #if(0) device_printf(sc->dev, "envy24_maskintr(sc, %d)\n", dir); #endif if (dir == PCMDIR_PLAY) mask = ENVY24_MT_INT_PMASK; else mask = ENVY24_MT_INT_RMASK; intr = envy24_rdmt(sc, ENVY24_MT_INT, 1); envy24_wrmt(sc, ENVY24_MT_INT, intr | mask, 1); return; } #endif static int envy24_checkintr(struct sc_info *sc, int dir) { u_int32_t mask, stat, intr, rtn; #if(0) device_printf(sc->dev, "envy24_checkintr(sc, %d)\n", dir); #endif intr = envy24_rdmt(sc, ENVY24_MT_INT, 1); if (dir == PCMDIR_PLAY) { if ((rtn = intr & ENVY24_MT_INT_PSTAT) != 0) { mask = ~ENVY24_MT_INT_RSTAT; stat = ENVY24_MT_INT_PSTAT | ENVY24_MT_INT_PMASK; envy24_wrmt(sc, ENVY24_MT_INT, (intr & mask) | stat, 1); } } else { if ((rtn = intr & ENVY24_MT_INT_RSTAT) != 0) { mask = ~ENVY24_MT_INT_PSTAT; stat = ENVY24_MT_INT_RSTAT | ENVY24_MT_INT_RMASK; envy24_wrmt(sc, ENVY24_MT_INT, (intr & mask) | stat, 1); } } return rtn; } static void envy24_start(struct sc_info *sc, int dir) { u_int32_t stat, sw; #if(0) device_printf(sc->dev, "envy24_start(sc, %d)\n", dir); #endif if (dir == PCMDIR_PLAY) sw = ENVY24_MT_PCTL_PSTART; else sw = ENVY24_MT_PCTL_RSTART; stat = envy24_rdmt(sc, ENVY24_MT_PCTL, 1); envy24_wrmt(sc, ENVY24_MT_PCTL, stat | sw, 1); #if(0) DELAY(100); device_printf(sc->dev, "PADDR:0x%08x\n", envy24_rdmt(sc, ENVY24_MT_PADDR, 4)); device_printf(sc->dev, "PCNT:%ld\n", envy24_rdmt(sc, ENVY24_MT_PCNT, 2)); #endif return; } static void envy24_stop(struct sc_info *sc, int dir) { u_int32_t stat, sw; #if(0) device_printf(sc->dev, "envy24_stop(sc, %d)\n", dir); #endif if (dir == PCMDIR_PLAY) sw = ~ENVY24_MT_PCTL_PSTART; else sw = ~ENVY24_MT_PCTL_RSTART; stat = envy24_rdmt(sc, ENVY24_MT_PCTL, 1); envy24_wrmt(sc, ENVY24_MT_PCTL, stat & sw, 1); return; } static int envy24_route(struct sc_info *sc, int dac, int class, int adc, int rev) { u_int32_t reg, mask; u_int32_t left, right; #if(0) device_printf(sc->dev, "envy24_route(sc, %d, %d, %d, %d)\n", dac, class, adc, rev); #endif /* parameter pattern check */ if (dac < 0 || ENVY24_ROUTE_DAC_SPDIF < dac) return -1; if (class == ENVY24_ROUTE_CLASS_MIX && (dac != ENVY24_ROUTE_DAC_1 && dac != ENVY24_ROUTE_DAC_SPDIF)) return -1; if (rev) { left = ENVY24_ROUTE_RIGHT; right = ENVY24_ROUTE_LEFT; } else { left = ENVY24_ROUTE_LEFT; right = ENVY24_ROUTE_RIGHT; } if (dac == ENVY24_ROUTE_DAC_SPDIF) { reg = class | class << 2 | ((adc << 1 | left) | left << 3) << 8 | ((adc << 1 | right) | right << 3) << 12; #if(0) device_printf(sc->dev, "envy24_route(): MT_SPDOUT-->0x%04x\n", reg); #endif envy24_wrmt(sc, ENVY24_MT_SPDOUT, reg, 2); } else { mask = ~(0x0303 << dac * 2); reg = envy24_rdmt(sc, ENVY24_MT_PSDOUT, 2); reg = (reg & mask) | ((class | class << 8) << dac * 2); #if(0) device_printf(sc->dev, "envy24_route(): MT_PSDOUT-->0x%04x\n", reg); #endif envy24_wrmt(sc, ENVY24_MT_PSDOUT, reg, 2); mask = ~(0xff << dac * 8); reg = envy24_rdmt(sc, ENVY24_MT_RECORD, 4); reg = (reg & mask) | (((adc << 1 | left) | left << 3) | ((adc << 1 | right) | right << 3) << 4) << dac * 8; #if(0) device_printf(sc->dev, "envy24_route(): MT_RECORD-->0x%08x\n", reg); #endif envy24_wrmt(sc, ENVY24_MT_RECORD, reg, 4); /* 6fire rear input init test */ envy24_wrmt(sc, ENVY24_MT_RECORD, 0x00, 4); } return 0; } /* -------------------------------------------------------------------- */ /* buffer copy routines */ static void envy24_p32sl(struct sc_chinfo *ch) { int length; sample32_t *dmabuf; u_int32_t *data; int src, dst, ssize, dsize, slot; int i; length = sndbuf_getready(ch->buffer) / 8; dmabuf = ch->parent->pbuf; data = (u_int32_t *)ch->data; src = sndbuf_getreadyptr(ch->buffer) / 4; dst = src / 2 + ch->offset; ssize = ch->size / 4; dsize = ch->size / 8; slot = ch->num * 2; for (i = 0; i < length; i++) { dmabuf[dst * ENVY24_PLAY_CHNUM + slot].buffer = data[src]; dmabuf[dst * ENVY24_PLAY_CHNUM + slot + 1].buffer = data[src + 1]; dst++; dst %= dsize; src += 2; src %= ssize; } return; } static void envy24_p16sl(struct sc_chinfo *ch) { int length; sample32_t *dmabuf; u_int16_t *data; int src, dst, ssize, dsize, slot; int i; #if(0) device_printf(ch->parent->dev, "envy24_p16sl()\n"); #endif length = sndbuf_getready(ch->buffer) / 4; dmabuf = ch->parent->pbuf; data = (u_int16_t *)ch->data; src = sndbuf_getreadyptr(ch->buffer) / 2; dst = src / 2 + ch->offset; ssize = ch->size / 2; dsize = ch->size / 4; slot = ch->num * 2; #if(0) device_printf(ch->parent->dev, "envy24_p16sl():%lu-->%lu(%lu)\n", src, dst, length); #endif for (i = 0; i < length; i++) { dmabuf[dst * ENVY24_PLAY_CHNUM + slot].buffer = (u_int32_t)data[src] << 16; dmabuf[dst * ENVY24_PLAY_CHNUM + slot + 1].buffer = (u_int32_t)data[src + 1] << 16; #if(0) if (i < 16) { printf("%08x", dmabuf[dst * ENVY24_PLAY_CHNUM + slot]); printf("%08x", dmabuf[dst * ENVY24_PLAY_CHNUM + slot + 1]); } #endif dst++; dst %= dsize; src += 2; src %= ssize; } #if(0) printf("\n"); #endif return; } static void envy24_p8u(struct sc_chinfo *ch) { int length; sample32_t *dmabuf; u_int8_t *data; int src, dst, ssize, dsize, slot; int i; length = sndbuf_getready(ch->buffer) / 2; dmabuf = ch->parent->pbuf; data = (u_int8_t *)ch->data; src = sndbuf_getreadyptr(ch->buffer); dst = src / 2 + ch->offset; ssize = ch->size; dsize = ch->size / 4; slot = ch->num * 2; for (i = 0; i < length; i++) { dmabuf[dst * ENVY24_PLAY_CHNUM + slot].buffer = ((u_int32_t)data[src] ^ 0x80) << 24; dmabuf[dst * ENVY24_PLAY_CHNUM + slot + 1].buffer = ((u_int32_t)data[src + 1] ^ 0x80) << 24; dst++; dst %= dsize; src += 2; src %= ssize; } return; } static void envy24_r32sl(struct sc_chinfo *ch) { int length; sample32_t *dmabuf; u_int32_t *data; int src, dst, ssize, dsize, slot; int i; length = sndbuf_getfree(ch->buffer) / 8; dmabuf = ch->parent->rbuf; data = (u_int32_t *)ch->data; dst = sndbuf_getfreeptr(ch->buffer) / 4; src = dst / 2 + ch->offset; dsize = ch->size / 4; ssize = ch->size / 8; slot = (ch->num - ENVY24_CHAN_REC_ADC1) * 2; for (i = 0; i < length; i++) { data[dst] = dmabuf[src * ENVY24_REC_CHNUM + slot].buffer; data[dst + 1] = dmabuf[src * ENVY24_REC_CHNUM + slot + 1].buffer; dst += 2; dst %= dsize; src++; src %= ssize; } return; } static void envy24_r16sl(struct sc_chinfo *ch) { int length; sample32_t *dmabuf; u_int16_t *data; int src, dst, ssize, dsize, slot; int i; length = sndbuf_getfree(ch->buffer) / 4; dmabuf = ch->parent->rbuf; data = (u_int16_t *)ch->data; dst = sndbuf_getfreeptr(ch->buffer) / 2; src = dst / 2 + ch->offset; dsize = ch->size / 2; ssize = ch->size / 8; slot = (ch->num - ENVY24_CHAN_REC_ADC1) * 2; for (i = 0; i < length; i++) { data[dst] = dmabuf[src * ENVY24_REC_CHNUM + slot].buffer; data[dst + 1] = dmabuf[src * ENVY24_REC_CHNUM + slot + 1].buffer; dst += 2; dst %= dsize; src++; src %= ssize; } return; } /* -------------------------------------------------------------------- */ /* channel interface */ static void * envy24chan_init(kobj_t obj, void *devinfo, struct snd_dbuf *b, struct pcm_channel *c, int dir) { struct sc_info *sc = (struct sc_info *)devinfo; struct sc_chinfo *ch; unsigned num; #if(0) device_printf(sc->dev, "envy24chan_init(obj, devinfo, b, c, %d)\n", dir); #endif snd_mtxlock(sc->lock); if ((sc->chnum > ENVY24_CHAN_PLAY_SPDIF && dir != PCMDIR_REC) || (sc->chnum < ENVY24_CHAN_REC_ADC1 && dir != PCMDIR_PLAY)) { snd_mtxunlock(sc->lock); return NULL; } num = sc->chnum; ch = &sc->chan[num]; ch->size = 8 * ENVY24_SAMPLE_NUM; ch->data = malloc(ch->size, M_ENVY24, M_NOWAIT); if (ch->data == NULL) { ch->size = 0; ch = NULL; } else { ch->buffer = b; ch->channel = c; ch->parent = sc; ch->dir = dir; /* set channel map */ ch->num = envy24_chanmap[num]; snd_mtxunlock(sc->lock); sndbuf_setup(ch->buffer, ch->data, ch->size); snd_mtxlock(sc->lock); /* these 2 values are dummy */ ch->unit = 4; ch->blk = 10240; } snd_mtxunlock(sc->lock); return ch; } static int envy24chan_free(kobj_t obj, void *data) { struct sc_chinfo *ch = data; struct sc_info *sc = ch->parent; #if(0) device_printf(sc->dev, "envy24chan_free()\n"); #endif snd_mtxlock(sc->lock); if (ch->data != NULL) { free(ch->data, M_ENVY24); ch->data = NULL; } snd_mtxunlock(sc->lock); return 0; } static int envy24chan_setformat(kobj_t obj, void *data, u_int32_t format) { struct sc_chinfo *ch = data; struct sc_info *sc = ch->parent; struct envy24_emldma *emltab; /* unsigned int bcnt, bsize; */ int i; #if(0) device_printf(sc->dev, "envy24chan_setformat(obj, data, 0x%08x)\n", format); #endif snd_mtxlock(sc->lock); /* check and get format related information */ if (ch->dir == PCMDIR_PLAY) emltab = envy24_pemltab; else emltab = envy24_remltab; if (emltab == NULL) { snd_mtxunlock(sc->lock); return -1; } for (i = 0; emltab[i].format != 0; i++) if (emltab[i].format == format) break; if (emltab[i].format == 0) { snd_mtxunlock(sc->lock); return -1; } /* set format information */ ch->format = format; ch->emldma = emltab[i].emldma; if (ch->unit > emltab[i].unit) ch->blk *= ch->unit / emltab[i].unit; else ch->blk /= emltab[i].unit / ch->unit; ch->unit = emltab[i].unit; /* set channel buffer information */ ch->size = ch->unit * ENVY24_SAMPLE_NUM; #if 0 if (ch->dir == PCMDIR_PLAY) bsize = ch->blk * 4 / ENVY24_PLAY_BUFUNIT; else bsize = ch->blk * 4 / ENVY24_REC_BUFUNIT; bsize *= ch->unit; bcnt = ch->size / bsize; sndbuf_resize(ch->buffer, bcnt, bsize); #endif snd_mtxunlock(sc->lock); #if(0) device_printf(sc->dev, "envy24chan_setformat(): return 0x%08x\n", 0); #endif return 0; } /* IMPLEMENT NOTICE: In this driver, setspeed function only do setting of speed information value. And real hardware speed setting is done at start triggered(see envy24chan_trigger()). So, at this function is called, any value that ENVY24 can use is able to set. But, at start triggerd, some other channel is running, and that channel's speed isn't same with, then trigger function will fail. */ static u_int32_t envy24chan_setspeed(kobj_t obj, void *data, u_int32_t speed) { struct sc_chinfo *ch = data; u_int32_t val, prev; int i; #if(0) device_printf(ch->parent->dev, "envy24chan_setspeed(obj, data, %d)\n", speed); #endif prev = 0x7fffffff; for (i = 0; (val = envy24_speed[i]) != 0; i++) { if (abs(val - speed) < abs(prev - speed)) prev = val; else break; } ch->speed = prev; #if(0) device_printf(ch->parent->dev, "envy24chan_setspeed(): return %d\n", ch->speed); #endif return ch->speed; } static u_int32_t envy24chan_setblocksize(kobj_t obj, void *data, u_int32_t blocksize) { struct sc_chinfo *ch = data; /* struct sc_info *sc = ch->parent; */ u_int32_t size, prev; unsigned int bcnt, bsize; #if(0) device_printf(sc->dev, "envy24chan_setblocksize(obj, data, %d)\n", blocksize); #endif prev = 0x7fffffff; /* snd_mtxlock(sc->lock); */ for (size = ch->size / 2; size > 0; size /= 2) { if (abs(size - blocksize) < abs(prev - blocksize)) prev = size; else break; } ch->blk = prev / ch->unit; if (ch->dir == PCMDIR_PLAY) ch->blk *= ENVY24_PLAY_BUFUNIT / 4; else ch->blk *= ENVY24_REC_BUFUNIT / 4; /* set channel buffer information */ /* ch->size = ch->unit * ENVY24_SAMPLE_NUM; */ if (ch->dir == PCMDIR_PLAY) bsize = ch->blk * 4 / ENVY24_PLAY_BUFUNIT; else bsize = ch->blk * 4 / ENVY24_REC_BUFUNIT; bsize *= ch->unit; bcnt = ch->size / bsize; sndbuf_resize(ch->buffer, bcnt, bsize); /* snd_mtxunlock(sc->lock); */ #if(0) device_printf(sc->dev, "envy24chan_setblocksize(): return %d\n", prev); #endif return prev; } /* semantic note: must start at beginning of buffer */ static int envy24chan_trigger(kobj_t obj, void *data, int go) { struct sc_chinfo *ch = data; struct sc_info *sc = ch->parent; u_int32_t ptr; int slot; int error = 0; #if 0 int i; device_printf(sc->dev, "envy24chan_trigger(obj, data, %d)\n", go); #endif snd_mtxlock(sc->lock); if (ch->dir == PCMDIR_PLAY) slot = 0; else slot = 1; switch (go) { case PCMTRIG_START: #if(0) device_printf(sc->dev, "envy24chan_trigger(): start\n"); #endif /* check or set channel speed */ if (sc->run[0] == 0 && sc->run[1] == 0) { sc->speed = envy24_setspeed(sc, ch->speed); sc->caps[0].minspeed = sc->caps[0].maxspeed = sc->speed; sc->caps[1].minspeed = sc->caps[1].maxspeed = sc->speed; } else if (ch->speed != 0 && ch->speed != sc->speed) { error = -1; goto fail; } if (ch->speed == 0) ch->channel->speed = sc->speed; /* start or enable channel */ sc->run[slot]++; if (sc->run[slot] == 1) { /* first channel */ ch->offset = 0; sc->blk[slot] = ch->blk; } else { ptr = envy24_gethwptr(sc, ch->dir); ch->offset = ((ptr / ch->blk + 1) * ch->blk % (ch->size / 4)) * 4 / ch->unit; if (ch->blk < sc->blk[slot]) sc->blk[slot] = ch->blk; } if (ch->dir == PCMDIR_PLAY) { ch->emldma(ch); envy24_setvolume(sc, ch->num); } envy24_updintr(sc, ch->dir); if (sc->run[slot] == 1) envy24_start(sc, ch->dir); ch->run = 1; break; case PCMTRIG_EMLDMAWR: #if(0) device_printf(sc->dev, "envy24chan_trigger(): emldmawr\n"); #endif if (ch->run != 1) { error = -1; goto fail; } ch->emldma(ch); break; case PCMTRIG_EMLDMARD: #if(0) device_printf(sc->dev, "envy24chan_trigger(): emldmard\n"); #endif if (ch->run != 1) { error = -1; goto fail; } ch->emldma(ch); break; case PCMTRIG_ABORT: if (ch->run) { #if(0) device_printf(sc->dev, "envy24chan_trigger(): abort\n"); #endif ch->run = 0; sc->run[slot]--; if (ch->dir == PCMDIR_PLAY) envy24_mutevolume(sc, ch->num); if (sc->run[slot] == 0) { envy24_stop(sc, ch->dir); sc->intr[slot] = 0; } #if 0 else if (ch->blk == sc->blk[slot]) { sc->blk[slot] = ENVY24_SAMPLE_NUM / 2; for (i = 0; i < ENVY24_CHAN_NUM; i++) { if (sc->chan[i].dir == ch->dir && sc->chan[i].run == 1 && sc->chan[i].blk < sc->blk[slot]) sc->blk[slot] = sc->chan[i].blk; } if (ch->blk != sc->blk[slot]) envy24_updintr(sc, ch->dir); } #endif } break; } fail: snd_mtxunlock(sc->lock); return (error); } static u_int32_t envy24chan_getptr(kobj_t obj, void *data) { struct sc_chinfo *ch = data; struct sc_info *sc = ch->parent; u_int32_t ptr, rtn; #if(0) device_printf(sc->dev, "envy24chan_getptr()\n"); #endif snd_mtxlock(sc->lock); ptr = envy24_gethwptr(sc, ch->dir); rtn = ptr * ch->unit; snd_mtxunlock(sc->lock); #if(0) device_printf(sc->dev, "envy24chan_getptr(): return %d\n", rtn); #endif return rtn; } static struct pcmchan_caps * envy24chan_getcaps(kobj_t obj, void *data) { struct sc_chinfo *ch = data; struct sc_info *sc = ch->parent; struct pcmchan_caps *rtn; #if(0) device_printf(sc->dev, "envy24chan_getcaps()\n"); #endif snd_mtxlock(sc->lock); if (ch->dir == PCMDIR_PLAY) { if (sc->run[0] == 0) rtn = &envy24_playcaps; else rtn = &sc->caps[0]; } else { if (sc->run[1] == 0) rtn = &envy24_reccaps; else rtn = &sc->caps[1]; } snd_mtxunlock(sc->lock); return rtn; } static kobj_method_t envy24chan_methods[] = { KOBJMETHOD(channel_init, envy24chan_init), KOBJMETHOD(channel_free, envy24chan_free), KOBJMETHOD(channel_setformat, envy24chan_setformat), KOBJMETHOD(channel_setspeed, envy24chan_setspeed), KOBJMETHOD(channel_setblocksize, envy24chan_setblocksize), KOBJMETHOD(channel_trigger, envy24chan_trigger), KOBJMETHOD(channel_getptr, envy24chan_getptr), KOBJMETHOD(channel_getcaps, envy24chan_getcaps), KOBJMETHOD_END }; CHANNEL_DECLARE(envy24chan); /* -------------------------------------------------------------------- */ /* mixer interface */ static int envy24mixer_init(struct snd_mixer *m) { struct sc_info *sc = mix_getdevinfo(m); #if(0) device_printf(sc->dev, "envy24mixer_init()\n"); #endif if (sc == NULL) return -1; /* set volume control rate */ snd_mtxlock(sc->lock); envy24_wrmt(sc, ENVY24_MT_VOLRATE, 0x30, 1); /* 0x30 is default value */ mix_setdevs(m, ENVY24_MIX_MASK); mix_setrecdevs(m, ENVY24_MIX_REC_MASK); snd_mtxunlock(sc->lock); return 0; } static int envy24mixer_reinit(struct snd_mixer *m) { struct sc_info *sc = mix_getdevinfo(m); if (sc == NULL) return -1; #if(0) device_printf(sc->dev, "envy24mixer_reinit()\n"); #endif return 0; } static int envy24mixer_uninit(struct snd_mixer *m) { struct sc_info *sc = mix_getdevinfo(m); if (sc == NULL) return -1; #if(0) device_printf(sc->dev, "envy24mixer_uninit()\n"); #endif return 0; } static int envy24mixer_set(struct snd_mixer *m, unsigned dev, unsigned left, unsigned right) { struct sc_info *sc = mix_getdevinfo(m); int ch = envy24_mixmap[dev]; int hwch; int i; if (sc == NULL) return -1; if (dev == 0 && sc->cfg->codec->setvolume == NULL) return -1; if (dev != 0 && ch == -1) return -1; hwch = envy24_chanmap[ch]; #if(0) device_printf(sc->dev, "envy24mixer_set(m, %d, %d, %d)\n", dev, left, right); #endif snd_mtxlock(sc->lock); if (dev == 0) { for (i = 0; i < sc->dacn; i++) { sc->cfg->codec->setvolume(sc->dac[i], PCMDIR_PLAY, left, right); } } else { /* set volume value for hardware */ if ((sc->left[hwch] = 100 - left) > ENVY24_VOL_MIN) sc->left[hwch] = ENVY24_VOL_MUTE; if ((sc->right[hwch] = 100 - right) > ENVY24_VOL_MIN) sc->right[hwch] = ENVY24_VOL_MUTE; /* set volume for record channel and running play channel */ if (hwch > ENVY24_CHAN_PLAY_SPDIF || sc->chan[ch].run) envy24_setvolume(sc, hwch); } snd_mtxunlock(sc->lock); return right << 8 | left; } static u_int32_t envy24mixer_setrecsrc(struct snd_mixer *m, u_int32_t src) { struct sc_info *sc = mix_getdevinfo(m); int ch = envy24_mixmap[src]; #if(0) device_printf(sc->dev, "envy24mixer_setrecsrc(m, %d)\n", src); #endif if (ch > ENVY24_CHAN_PLAY_SPDIF) sc->src = ch; return src; } static kobj_method_t envy24mixer_methods[] = { KOBJMETHOD(mixer_init, envy24mixer_init), KOBJMETHOD(mixer_reinit, envy24mixer_reinit), KOBJMETHOD(mixer_uninit, envy24mixer_uninit), KOBJMETHOD(mixer_set, envy24mixer_set), KOBJMETHOD(mixer_setrecsrc, envy24mixer_setrecsrc), KOBJMETHOD_END }; MIXER_DECLARE(envy24mixer); /* -------------------------------------------------------------------- */ /* The interrupt handler */ static void envy24_intr(void *p) { struct sc_info *sc = (struct sc_info *)p; struct sc_chinfo *ch; u_int32_t ptr, dsize, feed; int i; #if(0) device_printf(sc->dev, "envy24_intr()\n"); #endif snd_mtxlock(sc->lock); if (envy24_checkintr(sc, PCMDIR_PLAY)) { #if(0) device_printf(sc->dev, "envy24_intr(): play\n"); #endif dsize = sc->psize / 4; ptr = dsize - envy24_rdmt(sc, ENVY24_MT_PCNT, 2) - 1; #if(0) device_printf(sc->dev, "envy24_intr(): ptr = %d-->", ptr); #endif ptr -= ptr % sc->blk[0]; feed = (ptr + dsize - sc->intr[0]) % dsize; #if(0) printf("%d intr = %d feed = %d\n", ptr, sc->intr[0], feed); #endif for (i = ENVY24_CHAN_PLAY_DAC1; i <= ENVY24_CHAN_PLAY_SPDIF; i++) { ch = &sc->chan[i]; #if(0) if (ch->run) device_printf(sc->dev, "envy24_intr(): chan[%d].blk = %d\n", i, ch->blk); #endif if (ch->run && ch->blk <= feed) { snd_mtxunlock(sc->lock); chn_intr(ch->channel); snd_mtxlock(sc->lock); } } sc->intr[0] = ptr; envy24_updintr(sc, PCMDIR_PLAY); } if (envy24_checkintr(sc, PCMDIR_REC)) { #if(0) device_printf(sc->dev, "envy24_intr(): rec\n"); #endif dsize = sc->rsize / 4; ptr = dsize - envy24_rdmt(sc, ENVY24_MT_RCNT, 2) - 1; ptr -= ptr % sc->blk[1]; feed = (ptr + dsize - sc->intr[1]) % dsize; for (i = ENVY24_CHAN_REC_ADC1; i <= ENVY24_CHAN_REC_SPDIF; i++) { ch = &sc->chan[i]; if (ch->run && ch->blk <= feed) { snd_mtxunlock(sc->lock); chn_intr(ch->channel); snd_mtxlock(sc->lock); } } sc->intr[1] = ptr; envy24_updintr(sc, PCMDIR_REC); } snd_mtxunlock(sc->lock); return; } /* * Probe and attach the card */ static int envy24_pci_probe(device_t dev) { u_int16_t sv, sd; int i; #if(0) printf("envy24_pci_probe()\n"); #endif if (pci_get_device(dev) == PCID_ENVY24 && pci_get_vendor(dev) == PCIV_ENVY24) { sv = pci_get_subvendor(dev); sd = pci_get_subdevice(dev); for (i = 0; cfg_table[i].subvendor != 0 || cfg_table[i].subdevice != 0; i++) { if (cfg_table[i].subvendor == sv && cfg_table[i].subdevice == sd) { break; } } device_set_desc(dev, cfg_table[i].name); #if(0) printf("envy24_pci_probe(): return 0\n"); #endif return 0; } else { #if(0) printf("envy24_pci_probe(): return ENXIO\n"); #endif return ENXIO; } } static void envy24_dmapsetmap(void *arg, bus_dma_segment_t *segs, int nseg, int error) { struct sc_info *sc = (struct sc_info *)arg; sc->paddr = segs->ds_addr; #if(0) device_printf(sc->dev, "envy24_dmapsetmap()\n"); if (bootverbose) { printf("envy24(play): setmap %lx, %lx; ", (unsigned long)segs->ds_addr, (unsigned long)segs->ds_len); printf("%p -> %lx\n", sc->pmap, sc->paddr); } #endif } static void envy24_dmarsetmap(void *arg, bus_dma_segment_t *segs, int nseg, int error) { struct sc_info *sc = (struct sc_info *)arg; sc->raddr = segs->ds_addr; #if(0) device_printf(sc->dev, "envy24_dmarsetmap()\n"); if (bootverbose) { printf("envy24(record): setmap %lx, %lx; ", (unsigned long)segs->ds_addr, (unsigned long)segs->ds_len); printf("%p -> %lx\n", sc->rmap, sc->raddr); } #endif } static void envy24_dmafree(struct sc_info *sc) { #if(0) device_printf(sc->dev, "envy24_dmafree():"); printf(" sc->raddr(0x%08x)", (u_int32_t)sc->raddr); printf(" sc->paddr(0x%08x)", (u_int32_t)sc->paddr); if (sc->rbuf) printf(" sc->rbuf(0x%08x)", (u_int32_t)sc->rbuf); else printf(" sc->rbuf(null)"); if (sc->pbuf) printf(" sc->pbuf(0x%08x)\n", (u_int32_t)sc->pbuf); else printf(" sc->pbuf(null)\n"); #endif #if(0) if (sc->raddr) bus_dmamap_unload(sc->dmat, sc->rmap); if (sc->paddr) bus_dmamap_unload(sc->dmat, sc->pmap); if (sc->rbuf) bus_dmamem_free(sc->dmat, sc->rbuf, sc->rmap); if (sc->pbuf) bus_dmamem_free(sc->dmat, sc->pbuf, sc->pmap); #else bus_dmamap_unload(sc->dmat, sc->rmap); bus_dmamap_unload(sc->dmat, sc->pmap); bus_dmamem_free(sc->dmat, sc->rbuf, sc->rmap); bus_dmamem_free(sc->dmat, sc->pbuf, sc->pmap); #endif sc->raddr = sc->paddr = 0; sc->pbuf = NULL; sc->rbuf = NULL; return; } static int envy24_dmainit(struct sc_info *sc) { #if(0) device_printf(sc->dev, "envy24_dmainit()\n"); #endif /* init values */ sc->psize = ENVY24_PLAY_BUFUNIT * ENVY24_SAMPLE_NUM; sc->rsize = ENVY24_REC_BUFUNIT * ENVY24_SAMPLE_NUM; sc->pbuf = NULL; sc->rbuf = NULL; sc->paddr = sc->raddr = 0; sc->blk[0] = sc->blk[1] = 0; /* allocate DMA buffer */ #if(0) device_printf(sc->dev, "envy24_dmainit(): bus_dmamem_alloc(): sc->pbuf\n"); #endif if (bus_dmamem_alloc(sc->dmat, (void **)&sc->pbuf, BUS_DMA_NOWAIT, &sc->pmap)) goto bad; #if(0) device_printf(sc->dev, "envy24_dmainit(): bus_dmamem_alloc(): sc->rbuf\n"); #endif if (bus_dmamem_alloc(sc->dmat, (void **)&sc->rbuf, BUS_DMA_NOWAIT, &sc->rmap)) goto bad; #if(0) device_printf(sc->dev, "envy24_dmainit(): bus_dmamem_load(): sc->pmap\n"); #endif if (bus_dmamap_load(sc->dmat, sc->pmap, sc->pbuf, sc->psize, envy24_dmapsetmap, sc, 0)) goto bad; #if(0) device_printf(sc->dev, "envy24_dmainit(): bus_dmamem_load(): sc->rmap\n"); #endif if (bus_dmamap_load(sc->dmat, sc->rmap, sc->rbuf, sc->rsize, envy24_dmarsetmap, sc, 0)) goto bad; bzero(sc->pbuf, sc->psize); bzero(sc->rbuf, sc->rsize); /* set values to register */ #if(0) device_printf(sc->dev, "paddr(0x%08x)\n", sc->paddr); #endif envy24_wrmt(sc, ENVY24_MT_PADDR, sc->paddr, 4); #if(0) device_printf(sc->dev, "PADDR-->(0x%08x)\n", envy24_rdmt(sc, ENVY24_MT_PADDR, 4)); device_printf(sc->dev, "psize(%ld)\n", sc->psize / 4 - 1); #endif envy24_wrmt(sc, ENVY24_MT_PCNT, sc->psize / 4 - 1, 2); #if(0) device_printf(sc->dev, "PCNT-->(%ld)\n", envy24_rdmt(sc, ENVY24_MT_PCNT, 2)); #endif envy24_wrmt(sc, ENVY24_MT_RADDR, sc->raddr, 4); envy24_wrmt(sc, ENVY24_MT_RCNT, sc->rsize / 4 - 1, 2); return 0; bad: envy24_dmafree(sc); return ENOSPC; } static void envy24_putcfg(struct sc_info *sc) { device_printf(sc->dev, "system configuration\n"); printf(" SubVendorID: 0x%04x, SubDeviceID: 0x%04x\n", sc->cfg->subvendor, sc->cfg->subdevice); printf(" XIN2 Clock Source: "); switch (sc->cfg->scfg & PCIM_SCFG_XIN2) { case 0x00: printf("22.5792MHz(44.1kHz*512)\n"); break; case 0x40: printf("16.9344MHz(44.1kHz*384)\n"); break; case 0x80: printf("from external clock synthesizer chip\n"); break; default: printf("illegal system setting\n"); } printf(" MPU-401 UART(s) #: "); if (sc->cfg->scfg & PCIM_SCFG_MPU) printf("2\n"); else printf("1\n"); printf(" AC'97 codec: "); if (sc->cfg->scfg & PCIM_SCFG_AC97) printf("not exist\n"); else printf("exist\n"); printf(" ADC #: "); printf("%d\n", sc->adcn); printf(" DAC #: "); printf("%d\n", sc->dacn); printf(" Multi-track converter type: "); if ((sc->cfg->acl & PCIM_ACL_MTC) == 0) { printf("AC'97(SDATA_OUT:"); if (sc->cfg->acl & PCIM_ACL_OMODE) printf("packed"); else printf("split"); printf("|SDATA_IN:"); if (sc->cfg->acl & PCIM_ACL_IMODE) printf("packed"); else printf("split"); printf(")\n"); } else { printf("I2S("); if (sc->cfg->i2s & PCIM_I2S_VOL) printf("with volume, "); if (sc->cfg->i2s & PCIM_I2S_96KHZ) printf("96KHz support, "); switch (sc->cfg->i2s & PCIM_I2S_RES) { case PCIM_I2S_16BIT: printf("16bit resolution, "); break; case PCIM_I2S_18BIT: printf("18bit resolution, "); break; case PCIM_I2S_20BIT: printf("20bit resolution, "); break; case PCIM_I2S_24BIT: printf("24bit resolution, "); break; } printf("ID#0x%x)\n", sc->cfg->i2s & PCIM_I2S_ID); } printf(" S/PDIF(IN/OUT): "); if (sc->cfg->spdif & PCIM_SPDIF_IN) printf("1/"); else printf("0/"); if (sc->cfg->spdif & PCIM_SPDIF_OUT) printf("1 "); else printf("0 "); if (sc->cfg->spdif & (PCIM_SPDIF_IN | PCIM_SPDIF_OUT)) printf("ID# 0x%02x\n", (sc->cfg->spdif & PCIM_SPDIF_ID) >> 2); printf(" GPIO(mask/dir/state): 0x%02x/0x%02x/0x%02x\n", sc->cfg->gpiomask, sc->cfg->gpiodir, sc->cfg->gpiostate); } static int envy24_init(struct sc_info *sc) { u_int32_t data; #if(0) int rtn; #endif int i; u_int32_t sv, sd; #if(0) device_printf(sc->dev, "envy24_init()\n"); #endif /* reset chip */ envy24_wrcs(sc, ENVY24_CCS_CTL, ENVY24_CCS_CTL_RESET | ENVY24_CCS_CTL_NATIVE, 1); DELAY(200); envy24_wrcs(sc, ENVY24_CCS_CTL, ENVY24_CCS_CTL_NATIVE, 1); DELAY(200); /* legacy hardware disable */ data = pci_read_config(sc->dev, PCIR_LAC, 2); data |= PCIM_LAC_DISABLE; pci_write_config(sc->dev, PCIR_LAC, data, 2); /* check system configuration */ sc->cfg = NULL; for (i = 0; cfg_table[i].subvendor != 0 || cfg_table[i].subdevice != 0; i++) { /* 1st: search configuration from table */ sv = pci_get_subvendor(sc->dev); sd = pci_get_subdevice(sc->dev); if (sv == cfg_table[i].subvendor && sd == cfg_table[i].subdevice) { #if(0) device_printf(sc->dev, "Set configuration from table\n"); #endif sc->cfg = &cfg_table[i]; break; } } if (sc->cfg == NULL) { /* 2nd: read configuration from table */ sc->cfg = envy24_rom2cfg(sc); } sc->adcn = ((sc->cfg->scfg & PCIM_SCFG_ADC) >> 2) + 1; sc->dacn = (sc->cfg->scfg & PCIM_SCFG_DAC) + 1; if (1 /* bootverbose */) { envy24_putcfg(sc); } /* set system configuration */ pci_write_config(sc->dev, PCIR_SCFG, sc->cfg->scfg, 1); pci_write_config(sc->dev, PCIR_ACL, sc->cfg->acl, 1); pci_write_config(sc->dev, PCIR_I2S, sc->cfg->i2s, 1); pci_write_config(sc->dev, PCIR_SPDIF, sc->cfg->spdif, 1); envy24_gpiosetmask(sc, sc->cfg->gpiomask); envy24_gpiosetdir(sc, sc->cfg->gpiodir); envy24_gpiowr(sc, sc->cfg->gpiostate); for (i = 0; i < sc->adcn; i++) { sc->adc[i] = sc->cfg->codec->create(sc->dev, sc, PCMDIR_REC, i); sc->cfg->codec->init(sc->adc[i]); } for (i = 0; i < sc->dacn; i++) { sc->dac[i] = sc->cfg->codec->create(sc->dev, sc, PCMDIR_PLAY, i); sc->cfg->codec->init(sc->dac[i]); } /* initialize DMA buffer */ #if(0) device_printf(sc->dev, "envy24_init(): initialize DMA buffer\n"); #endif if (envy24_dmainit(sc)) return ENOSPC; /* initialize status */ sc->run[0] = sc->run[1] = 0; sc->intr[0] = sc->intr[1] = 0; sc->speed = 0; sc->caps[0].fmtlist = envy24_playfmt; sc->caps[1].fmtlist = envy24_recfmt; /* set channel router */ envy24_route(sc, ENVY24_ROUTE_DAC_1, ENVY24_ROUTE_CLASS_MIX, 0, 0); envy24_route(sc, ENVY24_ROUTE_DAC_SPDIF, ENVY24_ROUTE_CLASS_DMA, 0, 0); /* envy24_route(sc, ENVY24_ROUTE_DAC_SPDIF, ENVY24_ROUTE_CLASS_MIX, 0, 0); */ /* set macro interrupt mask */ data = envy24_rdcs(sc, ENVY24_CCS_IMASK, 1); envy24_wrcs(sc, ENVY24_CCS_IMASK, data & ~ENVY24_CCS_IMASK_PMT, 1); data = envy24_rdcs(sc, ENVY24_CCS_IMASK, 1); #if(0) device_printf(sc->dev, "envy24_init(): CCS_IMASK-->0x%02x\n", data); #endif return 0; } static int envy24_alloc_resource(struct sc_info *sc) { /* allocate I/O port resource */ sc->csid = PCIR_CCS; sc->cs = bus_alloc_resource_any(sc->dev, SYS_RES_IOPORT, &sc->csid, RF_ACTIVE); sc->ddmaid = PCIR_DDMA; sc->ddma = bus_alloc_resource_any(sc->dev, SYS_RES_IOPORT, &sc->ddmaid, RF_ACTIVE); sc->dsid = PCIR_DS; sc->ds = bus_alloc_resource_any(sc->dev, SYS_RES_IOPORT, &sc->dsid, RF_ACTIVE); sc->mtid = PCIR_MT; sc->mt = bus_alloc_resource_any(sc->dev, SYS_RES_IOPORT, &sc->mtid, RF_ACTIVE); if (!sc->cs || !sc->ddma || !sc->ds || !sc->mt) { device_printf(sc->dev, "unable to map IO port space\n"); return ENXIO; } sc->cst = rman_get_bustag(sc->cs); sc->csh = rman_get_bushandle(sc->cs); sc->ddmat = rman_get_bustag(sc->ddma); sc->ddmah = rman_get_bushandle(sc->ddma); sc->dst = rman_get_bustag(sc->ds); sc->dsh = rman_get_bushandle(sc->ds); sc->mtt = rman_get_bustag(sc->mt); sc->mth = rman_get_bushandle(sc->mt); #if(0) device_printf(sc->dev, "IO port register values\nCCS: 0x%lx\nDDMA: 0x%lx\nDS: 0x%lx\nMT: 0x%lx\n", pci_read_config(sc->dev, PCIR_CCS, 4), pci_read_config(sc->dev, PCIR_DDMA, 4), pci_read_config(sc->dev, PCIR_DS, 4), pci_read_config(sc->dev, PCIR_MT, 4)); #endif /* allocate interrupt resource */ sc->irqid = 0; sc->irq = bus_alloc_resource_any(sc->dev, SYS_RES_IRQ, &sc->irqid, RF_ACTIVE | RF_SHAREABLE); if (!sc->irq || snd_setup_intr(sc->dev, sc->irq, INTR_MPSAFE, envy24_intr, sc, &sc->ih)) { device_printf(sc->dev, "unable to map interrupt\n"); return ENXIO; } /* allocate DMA resource */ if (bus_dma_tag_create(/*parent*/bus_get_dma_tag(sc->dev), /*alignment*/4, /*boundary*/0, /*lowaddr*/BUS_SPACE_MAXADDR_ENVY24, /*highaddr*/BUS_SPACE_MAXADDR_ENVY24, /*filter*/NULL, /*filterarg*/NULL, /*maxsize*/BUS_SPACE_MAXSIZE_ENVY24, /*nsegments*/1, /*maxsegsz*/0x3ffff, /*flags*/0, /*lockfunc*/busdma_lock_mutex, /*lockarg*/&Giant, &sc->dmat) != 0) { device_printf(sc->dev, "unable to create dma tag\n"); return ENXIO; } return 0; } static int envy24_pci_attach(device_t dev) { struct sc_info *sc; char status[SND_STATUSLEN]; int err = 0; int i; #if(0) device_printf(dev, "envy24_pci_attach()\n"); #endif /* get sc_info data area */ if ((sc = malloc(sizeof(*sc), M_ENVY24, M_NOWAIT)) == NULL) { device_printf(dev, "cannot allocate softc\n"); return ENXIO; } bzero(sc, sizeof(*sc)); sc->lock = snd_mtxcreate(device_get_nameunit(dev), "snd_envy24 softc"); sc->dev = dev; /* initialize PCI interface */ pci_enable_busmaster(dev); /* allocate resources */ err = envy24_alloc_resource(sc); if (err) { device_printf(dev, "unable to allocate system resources\n"); goto bad; } /* initialize card */ err = envy24_init(sc); if (err) { device_printf(dev, "unable to initialize the card\n"); goto bad; } /* set multi track mixer */ mixer_init(dev, &envy24mixer_class, sc); /* set channel information */ err = pcm_register(dev, sc, 5, 2 + sc->adcn); if (err) goto bad; sc->chnum = 0; for (i = 0; i < 5; i++) { pcm_addchan(dev, PCMDIR_PLAY, &envy24chan_class, sc); sc->chnum++; } for (i = 0; i < 2 + sc->adcn; i++) { pcm_addchan(dev, PCMDIR_REC, &envy24chan_class, sc); sc->chnum++; } /* set status iformation */ snprintf(status, SND_STATUSLEN, "at io 0x%jx:%jd,0x%jx:%jd,0x%jx:%jd,0x%jx:%jd irq %jd", rman_get_start(sc->cs), rman_get_end(sc->cs) - rman_get_start(sc->cs) + 1, rman_get_start(sc->ddma), rman_get_end(sc->ddma) - rman_get_start(sc->ddma) + 1, rman_get_start(sc->ds), rman_get_end(sc->ds) - rman_get_start(sc->ds) + 1, rman_get_start(sc->mt), rman_get_end(sc->mt) - rman_get_start(sc->mt) + 1, rman_get_start(sc->irq)); pcm_setstatus(dev, status); return 0; bad: if (sc->ih) bus_teardown_intr(dev, sc->irq, sc->ih); if (sc->irq) bus_release_resource(dev, SYS_RES_IRQ, sc->irqid, sc->irq); envy24_dmafree(sc); if (sc->dmat) bus_dma_tag_destroy(sc->dmat); if (sc->cfg->codec->destroy != NULL) { for (i = 0; i < sc->adcn; i++) sc->cfg->codec->destroy(sc->adc[i]); for (i = 0; i < sc->dacn; i++) sc->cfg->codec->destroy(sc->dac[i]); } envy24_cfgfree(sc->cfg); if (sc->cs) bus_release_resource(dev, SYS_RES_IOPORT, sc->csid, sc->cs); if (sc->ddma) bus_release_resource(dev, SYS_RES_IOPORT, sc->ddmaid, sc->ddma); if (sc->ds) bus_release_resource(dev, SYS_RES_IOPORT, sc->dsid, sc->ds); if (sc->mt) bus_release_resource(dev, SYS_RES_IOPORT, sc->mtid, sc->mt); if (sc->lock) snd_mtxfree(sc->lock); free(sc, M_ENVY24); return err; } static int envy24_pci_detach(device_t dev) { struct sc_info *sc; int r; int i; #if(0) device_printf(dev, "envy24_pci_detach()\n"); #endif sc = pcm_getdevinfo(dev); if (sc == NULL) return 0; r = pcm_unregister(dev); if (r) return r; envy24_dmafree(sc); if (sc->cfg->codec->destroy != NULL) { for (i = 0; i < sc->adcn; i++) sc->cfg->codec->destroy(sc->adc[i]); for (i = 0; i < sc->dacn; i++) sc->cfg->codec->destroy(sc->dac[i]); } envy24_cfgfree(sc->cfg); bus_dma_tag_destroy(sc->dmat); bus_teardown_intr(dev, sc->irq, sc->ih); bus_release_resource(dev, SYS_RES_IRQ, sc->irqid, sc->irq); bus_release_resource(dev, SYS_RES_IOPORT, sc->csid, sc->cs); bus_release_resource(dev, SYS_RES_IOPORT, sc->ddmaid, sc->ddma); bus_release_resource(dev, SYS_RES_IOPORT, sc->dsid, sc->ds); bus_release_resource(dev, SYS_RES_IOPORT, sc->mtid, sc->mt); snd_mtxfree(sc->lock); free(sc, M_ENVY24); return 0; } static device_method_t envy24_methods[] = { /* Device interface */ DEVMETHOD(device_probe, envy24_pci_probe), DEVMETHOD(device_attach, envy24_pci_attach), DEVMETHOD(device_detach, envy24_pci_detach), { 0, 0 } }; static driver_t envy24_driver = { "pcm", envy24_methods, PCM_SOFTC_SIZE, }; DRIVER_MODULE(snd_envy24, pci, envy24_driver, pcm_devclass, 0, 0); MODULE_DEPEND(snd_envy24, sound, SOUND_MINVER, SOUND_PREFVER, SOUND_MAXVER); MODULE_DEPEND(snd_envy24, snd_spicds, 1, 1, 1); MODULE_VERSION(snd_envy24, 1);
// // MGPhotoCollectionView.h // MGPhotoCollectionView // // Created by 高得华 on 16/10/31. // Copyright © 2016年 GaoFei. All rights reserved. // #import <UIKit/UIKit.h> #import "MGPhotoModel.h" /**开始删除ImageView*/ static NSString * const MGPhotoEditIsDeleteImgView = @"MGPhotoEditIsDeleteImgView"; /**结束删除ImageView*/ static NSString * const MGPhotoEndEditIsDeleteImgView = @"MGPhotoEndEditIsDeleteImgView"; @class MGPhotoCollectionView; #pragma mark ====== MGPhotoCollectionViewDelegate === @protocol MGPhotoCollectionViewDelegate <NSObject> //必须实现的方法 //========= 1. 添加图片 -(void)collectionView:(MGPhotoCollectionView *)collectionView addPhotoArray:(NSMutableArray <MGPhotoModel *> *)photoArray; //========= 2.点击图片 -(void)collectionView:(MGPhotoCollectionView *)collectionView clickIndex:(NSInteger)index photoArray:(NSMutableArray<MGPhotoModel *> *)photoArray; @optional//非必需实现的方法 //==========3.是否处于删除状态 -(void)collectionView:(MGPhotoCollectionView *)collectionView isDeleteState:(BOOL)state photoArray:(NSMutableArray<MGPhotoModel *> *)photoArray; /** 点击删除按钮时 返回数据源及下一个按钮 @param collectionView MGPhotoCollectionView对象 @param photoArray 数据源数组 @param nextIndex 下一个数组 */ -(void)collectionView:(MGPhotoCollectionView *)collectionView photoArray:(NSMutableArray <MGPhotoModel *>*)photoArray nextIndex:(NSInteger)nextIndex; /**! * 处于最多照片个数状态下 剩下的就交给各位处理啦 一般是给个提示 */ - (void)MaxPhotoNumberState; @end @interface MGPhotoCollectionView : UIView /**! * 创建CollectionView 1.lineCounts:每一行显示多少列 2.frame,可以不指定大小,但是要确定位置 */ -(instancetype)initWithFrame:(CGRect)frame withLineCounts:(NSInteger)lineCounts; /**! * 每一行需要显示几列 */ @property (nonatomic, assign) NSInteger lineCounts; /**! * 数据源数组 数据类型为:MGPhotoModel */ @property (nonatomic, strong) NSArray <MGPhotoModel *> * dataArray; /**! *MGPhotoCollectionViewDelegate 代理 */ @property (nonatomic, assign) id <MGPhotoCollectionViewDelegate> delegate; /**! * block 返回点击的是第几个 及数据源数组 */ @property (nonatomic, copy) void(^ReturnClickIndexAndArray)(NSInteger index, NSArray <MGPhotoModel *> * photoArray, MGPhotoCollectionView * collectionView); /**! *block 点击的是添加照片的按钮 */ @property (nonatomic, copy) void(^ReturnClickAddPhoto)(NSMutableArray <MGPhotoModel *> * photoArray, MGPhotoCollectionView * collectionView); /**! *block 处于编辑状态 */ @property (nonatomic, copy) void(^ReturnClickIsDeleteState)(BOOL state, MGPhotoCollectionView * collectionView, NSMutableArray<MGPhotoModel *> *photoArray); /** 点击删除按钮时 返回下一个的数据及数据源 */ @property (nonatomic, copy) void(^ReturnClickDeletePhoto)(MGPhotoCollectionView * collectionView, NSMutableArray<MGPhotoModel *> *photoArray, NSInteger nextIndex); /**! * 获取视图的高度 */ -(CGFloat)ReturnViewHeight; /**! * 是否需要删除按钮,默认需要删除 */ @property (nonatomic, assign) BOOL isDelete; /**! *是否需要添加按钮 默认需要添加按钮 */ @property (nonatomic, assign) BOOL isAddClickBtn; /**! * 最多照片的个数 默认是12个 */ @property (nonatomic, assign) NSInteger maxPhotoNumber; /**! * 处于最多照片个数状态下 剩下的就交给各位处理啦 一般是给个提示 */ @property (nonatomic, copy) void(^MaxPhotoNumberStateBlock)(); @end
/* Compute remainder and a congruent to the quotient. Copyright (C) 1997, 1999, 2002 Free Software Foundation, Inc. This file is part of the GNU C Library. Contributed by Ulrich Drepper <drepper@cygnus.com>, 1997 and Jakub Jelinek <jj@ultra.linux.cz>, 1999. The GNU C Library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. The GNU C Library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with the GNU C Library; if not, write to the Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA. */ #include "quadmath-imp.h" static const __float128 zero = 0.0; __float128 remquoq (__float128 x, __float128 y, int *quo) { int64_t hx,hy; uint64_t sx,lx,ly,qs; int cquo; GET_FLT128_WORDS64 (hx, lx, x); GET_FLT128_WORDS64 (hy, ly, y); sx = hx & 0x8000000000000000ULL; qs = sx ^ (hy & 0x8000000000000000ULL); hy &= 0x7fffffffffffffffLL; hx &= 0x7fffffffffffffffLL; /* Purge off exception values. */ if ((hy | ly) == 0) return (x * y) / (x * y); /* y = 0 */ if ((hx >= 0x7fff000000000000LL) /* x not finite */ || ((hy >= 0x7fff000000000000LL) /* y is NaN */ && (((hy - 0x7fff000000000000LL) | ly) != 0))) return (x * y) / (x * y); if (hy <= 0x7ffbffffffffffffLL) x = fmodq (x, 8 * y); /* now x < 8y */ if (((hx - hy) | (lx - ly)) == 0) { *quo = qs ? -1 : 1; return zero * x; } x = fabsq (x); y = fabsq (y); cquo = 0; if (x >= 4 * y) { x -= 4 * y; cquo += 4; } if (x >= 2 * y) { x -= 2 * y; cquo += 2; } if (hy < 0x0002000000000000LL) { if (x + x > y) { x -= y; ++cquo; if (x + x >= y) { x -= y; ++cquo; } } } else { __float128 y_half = 0.5Q * y; if (x > y_half) { x -= y; ++cquo; if (x >= y_half) { x -= y; ++cquo; } } } *quo = qs ? -cquo : cquo; if (sx) x = -x; return x; }
/* * This header is generated by classdump-dyld 1.5 * on Wednesday, April 14, 2021 at 2:22:42 PM Mountain Standard Time * Operating System: Version 14.4 (Build 18K802) * Image Source: /System/Library/Frameworks/Contacts.framework/Contacts * classdump-dyld is licensed under GPLv3, Copyright © 2013-2016 by Elias Limneos. Updated by Kevin Bradley. */ #import <Contacts/Contacts-Structs.h> #import <Contacts/CNPredicate.h> #import <libobjc.A.dylib/CNiOSAccountPredicate.h> @class NSString; @interface CNiOSABAccountForExternalIdentifierPredicate : CNPredicate <CNiOSAccountPredicate> { NSString* _externalIdentifier; } @property (nonatomic,copy,readonly) NSString * externalIdentifier; //@synthesize externalIdentifier=_externalIdentifier - In the implementation block @property (readonly) unsigned long long hash; @property (readonly) Class superclass; @property (copy,readonly) NSString * description; @property (copy,readonly) NSString * debugDescription; +(BOOL)supportsSecureCoding; -(void)encodeWithCoder:(id)arg1 ; -(id)initWithCoder:(id)arg1 ; -(id)initWithPredicate:(id)arg1 ; -(NSString *)externalIdentifier; -(CFArrayRef)cn_copyAccountsInAddressBook:(void*)arg1 error:(_CFError*)arg2 ; -(id)initWithAccountExternalIdentifier:(id)arg1 ; @end
// Copyright (c) 2009-2010 Satoshi Nakamoto // Copyright (c) 2009-2014 The Bitcoin developers // Copyright (c) 2017-2018 The ABLE developers // Distributed under the MIT/X11 software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #ifndef BITCOIN_COMPAT_H #define BITCOIN_COMPAT_H #if defined(HAVE_CONFIG_H) #include "config/able-config.h" #endif #ifdef WIN32 #ifdef _WIN32_WINNT #undef _WIN32_WINNT #endif #define _WIN32_WINNT 0x0501 #ifndef WIN32_LEAN_AND_MEAN #define WIN32_LEAN_AND_MEAN 1 #endif #ifndef NOMINMAX #define NOMINMAX #endif #ifdef FD_SETSIZE #undef FD_SETSIZE // prevent redefinition compiler warning #endif #define FD_SETSIZE 1024 // max number of fds in fd_set #include <winsock2.h> // Must be included before mswsock.h and windows.h #include <mswsock.h> #include <windows.h> #include <ws2tcpip.h> #else #include <arpa/inet.h> #include <ifaddrs.h> #include <limits.h> #include <net/if.h> #include <netdb.h> #include <netinet/in.h> #include <sys/fcntl.h> #include <sys/mman.h> #include <sys/socket.h> #include <sys/types.h> #include <unistd.h> #endif #ifdef WIN32 #define MSG_DONTWAIT 0 #else typedef u_int SOCKET; #include "errno.h" #define WSAGetLastError() errno #define WSAEINVAL EINVAL #define WSAEALREADY EALREADY #define WSAEWOULDBLOCK EWOULDBLOCK #define WSAEMSGSIZE EMSGSIZE #define WSAEINTR EINTR #define WSAEINPROGRESS EINPROGRESS #define WSAEADDRINUSE EADDRINUSE #define WSAENOTSOCK EBADF #define INVALID_SOCKET (SOCKET)(~0) #define SOCKET_ERROR -1 #endif #ifdef WIN32 #ifndef S_IRUSR #define S_IRUSR 0400 #define S_IWUSR 0200 #endif #else #define MAX_PATH 1024 #endif // As Solaris does not have the MSG_NOSIGNAL flag for send(2) syscall, it is defined as 0 #if !defined(HAVE_MSG_NOSIGNAL) && !defined(MSG_NOSIGNAL) #define MSG_NOSIGNAL 0 #endif #ifndef WIN32 // PRIO_MAX is not defined on Solaris #ifndef PRIO_MAX #define PRIO_MAX 20 #endif #define THREAD_PRIORITY_LOWEST PRIO_MAX #define THREAD_PRIORITY_BELOW_NORMAL 2 #define THREAD_PRIORITY_NORMAL 0 #define THREAD_PRIORITY_ABOVE_NORMAL (-2) #endif #if HAVE_DECL_STRNLEN == 0 size_t strnlen( const char *start, size_t max_len); #endif // HAVE_DECL_STRNLEN bool static inline IsSelectableSocket(SOCKET s) { #ifdef WIN32 return true; #else return (s < FD_SETSIZE); #endif } #endif // BITCOIN_COMPAT_H
/* * This header is generated by classdump-dyld 1.5 * on Tuesday, November 10, 2020 at 10:11:50 PM Mountain Standard Time * Operating System: Version 14.2 (Build 18K57) * Image Source: /System/Library/PrivateFrameworks/AuthKit.framework/AuthKit * classdump-dyld is licensed under GPLv3, Copyright © 2013-2016 by Elias Limneos. Updated by Kevin Bradley. */ @protocol AKFollowUpProvider <NSObject> @required -(id)pendingFollowUpItems:(id*)arg1; -(BOOL)removeFollowUpItemsWithIdentifiers:(id)arg1 error:(id*)arg2; -(BOOL)removeAllFollowUpItems:(id*)arg1; -(BOOL)addFollowUpItems:(id)arg1 error:(id*)arg2; -(BOOL)removeFollowUpItems:(id)arg1 error:(id*)arg2; -(BOOL)clearNotificationsForItem:(id)arg1 error:(id*)arg2; @end
/*************************************************************************** * _ _ ____ _ * Project ___| | | | _ \| | * / __| | | | |_) | | * | (__| |_| | _ <| |___ * \___|\___/|_| \_\_____| * * Copyright (C) 1998 - 2014, Daniel Stenberg, <daniel@haxx.se>, et al. * * This software is licensed as described in the file COPYING, which * you should have received as part of this distribution. The terms * are also available at https://curl.haxx.se/docs/copyright.html. * * You may opt to use, copy, modify, merge, publish, distribute and/or sell * copies of the Software, and permit persons to whom the Software is * furnished to do so, under the terms of the COPYING file. * * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY * KIND, either express or implied. * ***************************************************************************/ #include "tool_setup.h" #ifdef HAVE_SETMODE #ifdef HAVE_IO_H # include <io.h> #endif #ifdef HAVE_FCNTL_H # include <fcntl.h> #endif #include "tool_binmode.h" #include "memdebug.h" /* keep this as LAST include */ void set_binmode(FILE *stream) { #ifdef O_BINARY # ifdef __HIGHC__ _setmode(stream, O_BINARY); # else (void)setmode(fileno(stream), O_BINARY); # endif #else (void)stream; #endif } #endif /* HAVE_SETMODE */
// // ______ _ _ _ _____ _____ _ __ // | ____| | | (_) | | / ____| __ \| |/ / // | |__ ___| |_ _ _ __ ___ ___ | |_ ___ | (___ | | | | ' / // | __| / __| __| | '_ ` _ \ / _ \| __/ _ \ \___ \| | | | < // | |____\__ \ |_| | | | | | | (_) | || __/ ____) | |__| | . \ // |______|___/\__|_|_| |_| |_|\___/ \__\___| |_____/|_____/|_|\_\ // // // Copyright © 2015 Estimote. All rights reserved. #import <Foundation/Foundation.h> #import "ESTBeaconOperationProtocol.h" #import "ESTSettingOperation.h" #import "ESTSettingGenericAdvertiserInterval.h" NS_ASSUME_NONNULL_BEGIN /** * ESTBeaconOperationGenericAdvertiserInterval allows to create read/write operations for GenericAdvertiser GenericAdvertiserInterval setting of a device. */ @interface ESTBeaconOperationGenericAdvertiserInterval : ESTSettingOperation <ESTBeaconOperationProtocol> /** * Method allows to create read operation for GenericAdvertiser GenericAdvertiserInterval setting. * * @param advertiserID Advertiser ID. * @param completion Block invoked when the operation is complete. * * @return Initialized object. */ + (instancetype)readOperationForAdvertiser:(ESTGenericAdvertiserID)advertiserID completion:(ESTSettingGenericAdvertiserIntervalCompletionBlock)completion; /** * Method allows to create write operation for GenericAdvertiser GenericAdvertiserInterval setting. * * @param advertiserID Advertiser ID. * @param setting Setting to be written to a device. * @param completion Block invoked when the operation is complete. * * @return Initialized object. */ + (instancetype)writeOperationForAdvertiser:(ESTGenericAdvertiserID)advertiserID setting:(ESTSettingGenericAdvertiserInterval *)setting completion:(ESTSettingGenericAdvertiserIntervalCompletionBlock)completion; @end NS_ASSUME_NONNULL_END
/* * Ptrace test for TAR, PPR, DSCR registers in the TM context * * Copyright (C) 2015 Anshuman Khandual, IBM Corporation. * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version * 2 of the License, or (at your option) any later version. */ #include "ptrace.h" #include "tm.h" #include "ptrace-tar.h" int shm_id; unsigned long *cptr, *pptr; void tm_tar(void) { unsigned long result, texasr; unsigned long regs[3]; int ret; cptr = (unsigned long *)shmat(shm_id, NULL, 0); trans: cptr[1] = 0; asm __volatile__( "li 4, %[tar_1];" "mtspr %[sprn_tar], 4;" /* TAR_1 */ "li 4, %[dscr_1];" "mtspr %[sprn_dscr], 4;" /* DSCR_1 */ "or 31,31,31;" /* PPR_1*/ "1: ;" "tbegin.;" "beq 2f;" "li 4, %[tar_2];" "mtspr %[sprn_tar], 4;" /* TAR_2 */ "li 4, %[dscr_2];" "mtspr %[sprn_dscr], 4;" /* DSCR_2 */ "or 1,1,1;" /* PPR_2 */ "tsuspend.;" "li 0, 1;" "stw 0, 0(%[cptr1]);" "tresume.;" "b .;" "tend.;" "li 0, 0;" "ori %[res], 0, 0;" "b 3f;" /* Transaction abort handler */ "2: ;" "li 0, 1;" "ori %[res], 0, 0;" "mfspr %[texasr], %[sprn_texasr];" "3: ;" : [res] "=r" (result), [texasr] "=r" (texasr) : [sprn_dscr]"i"(SPRN_DSCR), [sprn_tar]"i"(SPRN_TAR), [sprn_ppr]"i"(SPRN_PPR), [sprn_texasr]"i"(SPRN_TEXASR), [tar_1]"i"(TAR_1), [dscr_1]"i"(DSCR_1), [tar_2]"i"(TAR_2), [dscr_2]"i"(DSCR_2), [cptr1] "b" (&cptr[1]) : "memory", "r0", "r1", "r3", "r4", "r5", "r6" ); /* TM failed, analyse */ if (result) { if (!cptr[0]) goto trans; regs[0] = mfspr(SPRN_TAR); regs[1] = mfspr(SPRN_PPR); regs[2] = mfspr(SPRN_DSCR); shmdt(&cptr); printf("%-30s TAR: %lu PPR: %lx DSCR: %lu\n", user_read, regs[0], regs[1], regs[2]); ret = validate_tar_registers(regs, TAR_4, PPR_4, DSCR_4); if (ret) exit(1); exit(0); } shmdt(&cptr); exit(1); } int trace_tm_tar(pid_t child) { unsigned long regs[3]; FAIL_IF(start_trace(child)); FAIL_IF(show_tar_registers(child, regs)); printf("%-30s TAR: %lu PPR: %lx DSCR: %lu\n", ptrace_read_running, regs[0], regs[1], regs[2]); FAIL_IF(validate_tar_registers(regs, TAR_2, PPR_2, DSCR_2)); FAIL_IF(show_tm_checkpointed_state(child, regs)); printf("%-30s TAR: %lu PPR: %lx DSCR: %lu\n", ptrace_read_ckpt, regs[0], regs[1], regs[2]); FAIL_IF(validate_tar_registers(regs, TAR_1, PPR_1, DSCR_1)); FAIL_IF(write_ckpt_tar_registers(child, TAR_4, PPR_4, DSCR_4)); printf("%-30s TAR: %u PPR: %lx DSCR: %u\n", ptrace_write_ckpt, TAR_4, PPR_4, DSCR_4); pptr[0] = 1; FAIL_IF(stop_trace(child)); return TEST_PASS; } int ptrace_tm_tar(void) { pid_t pid; int ret, status; SKIP_IF(!have_htm()); shm_id = shmget(IPC_PRIVATE, sizeof(int) * 2, 0777|IPC_CREAT); pid = fork(); if (pid == 0) tm_tar(); pptr = (unsigned long *)shmat(shm_id, NULL, 0); pptr[0] = 0; if (pid) { while (!pptr[1]) asm volatile("" : : : "memory"); ret = trace_tm_tar(pid); if (ret) { kill(pid, SIGTERM); shmdt(&pptr); shmctl(shm_id, IPC_RMID, NULL); return TEST_FAIL; } shmdt(&pptr); ret = wait(&status); shmctl(shm_id, IPC_RMID, NULL); if (ret != pid) { printf("Child's exit status not captured\n"); return TEST_FAIL; } return (WIFEXITED(status) && WEXITSTATUS(status)) ? TEST_FAIL : TEST_PASS; } return TEST_PASS; } int main(int argc, char *argv[]) { return test_harness(ptrace_tm_tar, "ptrace_tm_tar"); }
/******************************************************************************* The content of this file includes portions of the AUDIOKINETIC Wwise Technology released in source code form as part of the SDK installer package. Commercial License Usage Licensees holding valid commercial licenses to the AUDIOKINETIC Wwise Technology may use this file in accordance with the end user license agreement provided with the software or, alternatively, in accordance with the terms contained in a written agreement between you and Audiokinetic Inc. Apache License Usage Alternatively, this file may be used under the Apache License, Version 2.0 (the "Apache License"); you may not use this file except in compliance with the Apache License. You may obtain a copy of the Apache License at http://www.apache.org/licenses/LICENSE-2.0. Unless required by applicable law or agreed to in writing, software distributed under the Apache License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the Apache License for the specific language governing permissions and limitations under the License. Version: v2021.1.5 Build: 7749 Copyright (c) 2006-2021 Audiokinetic Inc. *******************************************************************************/ #pragma once /// \file /// Plug-in function necessary to link the Wwise Silence plug-in in the sound engine. /// <b>WARNING</b>: Include this file only if you wish to link statically with the plugins. Dynamic Libaries (DLL, so, etc) are automatically detected and do not need this include file. /// <br><b>Wwise plugin name:</b> Wwise Silence /// <br><b>Library file:</b> AkSilenceSource.lib AK_STATIC_LINK_PLUGIN(AkSilenceSource)
// Copyright (c) 2011-2018 The Btcavenue Core developers // Distributed under the MIT software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #ifndef BITCOIN_QT_BANTABLEMODEL_H #define BITCOIN_QT_BANTABLEMODEL_H #include <net.h> #include <memory> #include <QAbstractTableModel> #include <QStringList> class BanTablePriv; namespace interfaces { class Node; } struct CCombinedBan { CSubNet subnet; CBanEntry banEntry; }; class BannedNodeLessThan { public: BannedNodeLessThan(int nColumn, Qt::SortOrder fOrder) : column(nColumn), order(fOrder) {} bool operator()(const CCombinedBan& left, const CCombinedBan& right) const; private: int column; Qt::SortOrder order; }; /** Qt model providing information about connected peers, similar to the "getpeerinfo" RPC call. Used by the rpc console UI. */ class BanTableModel : public QAbstractTableModel { Q_OBJECT public: explicit BanTableModel(interfaces::Node& node, QObject* parent); ~BanTableModel(); void startAutoRefresh(); void stopAutoRefresh(); enum ColumnIndex { Address = 0, Bantime = 1 }; /** @name Methods overridden from QAbstractTableModel @{*/ int rowCount(const QModelIndex &parent) const; int columnCount(const QModelIndex &parent) const; QVariant data(const QModelIndex &index, int role) const; QVariant headerData(int section, Qt::Orientation orientation, int role) const; QModelIndex index(int row, int column, const QModelIndex &parent) const; Qt::ItemFlags flags(const QModelIndex &index) const; void sort(int column, Qt::SortOrder order); bool shouldShow(); /*@}*/ public Q_SLOTS: void refresh(); private: interfaces::Node& m_node; QStringList columns; std::unique_ptr<BanTablePriv> priv; }; #endif // BITCOIN_QT_BANTABLEMODEL_H
#ifndef HEADER_CURL_HTTP_DIGEST_H #define HEADER_CURL_HTTP_DIGEST_H /*************************************************************************** * _ _ ____ _ * Project ___| | | | _ \| | * / __| | | | |_) | | * | (__| |_| | _ <| |___ * \___|\___/|_| \_\_____| * * Copyright (C) 1998 - 2020, Daniel Stenberg, <daniel@haxx.se>, et al. * * This software is licensed as described in the file COPYING, which * you should have received as part of this distribution. The terms * are also available at https://curl.se/docs/copyright.html. * * You may opt to use, copy, modify, merge, publish, distribute and/or sell * copies of the Software, and permit persons to whom the Software is * furnished to do so, under the terms of the COPYING file. * * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY * KIND, either express or implied. * ***************************************************************************/ #include "curl_setup.h" #if !defined(CURL_DISABLE_HTTP) && !defined(CURL_DISABLE_CRYPTO_AUTH) /* this is for digest header input */ CURLcode Curl_input_digest(struct connectdata *conn, bool proxy, const char *header); /* this is for creating digest header output */ CURLcode Curl_output_digest(struct connectdata *conn, bool proxy, const unsigned char *request, const unsigned char *uripath); void Curl_http_auth_cleanup_digest(struct Curl_easy *data); #endif /* !CURL_DISABLE_HTTP && !CURL_DISABLE_CRYPTO_AUTH */ #endif /* HEADER_CURL_HTTP_DIGEST_H */
/* $Id$ */ /* * Copyright (C) 2008-2011 Teluu Inc. (http://www.teluu.com) * Copyright (C) 2003-2008 Benny Prijono <benny@prijono.org> * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */ #ifndef __PJMEDIA_SPLITCOMB_H__ #define __PJMEDIA_SPLITCOMB_H__ /** * @file splitcomb.h * @brief Media channel splitter/combiner port. */ #include <pjmedia/port.h> /** * @addtogroup PJMEDIA_SPLITCOMB Media channel splitter/combiner * @ingroup PJMEDIA_PORT * @brief Split and combine multiple mono-channel media ports into * a single multiple-channels media port * @{ * * This section describes media port to split and combine media * channels in the stream. * * A splitter/combiner splits a single stereo/multichannels audio frame into * multiple audio frames to each channel when put_frame() is called, * and combines mono frames from each channel into a stereo/multichannel * frame when get_frame() is called. A common application for the splitter/ * combiner is to split frames from stereo to mono and vise versa. */ PJ_BEGIN_DECL /** * Create a media splitter/combiner with the specified parameters. * When the splitter/combiner is created, it creates an instance of * pjmedia_port. This media port represents the stereo/multichannel side * of the splitter/combiner. Application needs to supply the splitter/ * combiner with a media port for each audio channels. * * @param pool Pool to allocate memory to create the splitter/ * combiner. * @param clock_rate Audio clock rate/sampling rate. * @param channel_count Number of channels. * @param samples_per_frame Number of samples per frame. * @param bits_per_sample Bits per sample. * @param options Optional flags. * @param p_splitcomb Pointer to receive the splitter/combiner. * * @return PJ_SUCCESS on success, or the appropriate * error code. */ PJ_DECL(pj_status_t) pjmedia_splitcomb_create(pj_pool_t *pool, unsigned clock_rate, unsigned channel_count, unsigned samples_per_frame, unsigned bits_per_sample, unsigned options, pjmedia_port **p_splitcomb); /** * Supply the splitter/combiner with media port for the specified channel * number. The media port will be called at the * same phase as the splitter/combiner; which means that when application * calls get_frame() of the splitter/combiner, it will call get_frame() * for all ports that have the same phase. And similarly for put_frame(). * * @param splitcomb The splitter/combiner. * @param ch_num Audio channel starting number (zero based). * @param options Must be zero at the moment. * @param port The media port. * * @return PJ_SUCCESS on success, or the appropriate error * code. */ PJ_DECL(pj_status_t) pjmedia_splitcomb_set_channel(pjmedia_port *splitcomb, unsigned ch_num, unsigned options, pjmedia_port *port); /** * Create a reverse phase media port for the specified channel number. * For channels with reversed phase, when application calls put_frame() to * the splitter/combiner, the splitter/combiner will only put the frame to * a buffer. Later on, when application calls get_frame() on the channel's * media port, it will return the frame that are available in the buffer. * The same process happens when application calls put_frame() to the * channel's media port, it will only put the frame to another buffer, which * will be returned when application calls get_frame() to the splitter's * media port. So this effectively reverse the phase of the media port. * * @param pool The pool to allocate memory for the port and * buffers. * @param splitcomb The splitter/combiner. * @param ch_num Audio channel starting number (zero based). * @param options Normally is zero, but the lower 8-bit of the * options can be used to specify the number of * buffers in the circular buffer. If zero, then * default number will be used (default: 8). * @param p_chport The media port created with reverse phase for * the specified audio channel. * * @return PJ_SUCCESS on success, or the appropriate error * code. */ PJ_DECL(pj_status_t) pjmedia_splitcomb_create_rev_channel( pj_pool_t *pool, pjmedia_port *splitcomb, unsigned ch_num, unsigned options, pjmedia_port **p_chport); PJ_END_DECL /** * @} */ #endif /* __PJMEDIA_SPLITCOMB_H__ */
// SPDX-License-Identifier: BSD-3-Clause // Copyright (c) 2020 Darby Johnston // All rights reserved. #pragma once #include <djvViewApp/IViewAppSystem.h> namespace djv { namespace ViewApp { //! This class provides the debugging system. class DebugSystem : public IViewAppSystem { DJV_NON_COPYABLE(DebugSystem); protected: void _init(const std::shared_ptr<System::Context>&); DebugSystem(); public: ~DebugSystem() override; static std::shared_ptr<DebugSystem> create(const std::shared_ptr<System::Context>&); std::map<std::string, std::shared_ptr<UI::Action> > getActions() const override; ActionData getToolActionData() const override; ToolWidgetData createToolWidget(const std::shared_ptr<UI::Action>&) override; void deleteToolWidget(const std::shared_ptr<UI::Action>&) override; protected: void _textUpdate() override; void _shortcutsUpdate() override; private: DJV_PRIVATE(); }; } // namespace ViewApp } // namespace djv
/** * This file is part of the "clip" project * Copyright (c) 2018 Paul Asmuth * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #pragma once #include <unordered_map> #include "graphics/color.h" #include "graphics/draw.h" #include "graphics/geometry.h" #include "return_code.h" #include "sexpr.h" namespace clip { using Marker = std::function< ReturnCode ( Context* ctx, const Point& pos, const Number& size, const Color& color)>; Marker marker_create_circle(double border_width); Marker marker_create_disk(); Marker marker_create_unicode(const std::string& u); ReturnCode marker_configure( const Expr* expr, Marker* marker); ReturnCode marker_configure_list( const Expr* expr, std::vector<Marker>* markers); } // namespace clip
// // Generated by class-dump 3.5 (64 bit). // // class-dump is Copyright (C) 1997-1998, 2000-2001, 2004-2013 by Steve Nygard. // #pragma mark - // // File: /Applications/Xcode.app/Contents/Developer/Platforms/MacOSX.platform/Developer/SDKs/MacOSX10.9.sdk/System/Library/PrivateFrameworks/MessageProtection.framework/Versions/A/MessageProtection // UUID: 4A712C3F-FD3F-38CF-95E6-E12AEDA8C1C0 // // Arch: x86_64 // Source version: 42.0.0.0.0 // Minimum Mac OS X version: 10.9.0 // SDK version: 10.9.0 // // // This file does not contain any Objective-C runtime information. //
#ifndef DYNET_NODE_MACROS_H_ #define DYNET_NODE_MACROS_H_ #include "dynet/dim.h" #include "dynet/except.h" #include <iostream> namespace dynet { inline bool LooksLikeVector(const Dim& d) { if (d.ndims() == 1) return true; if (d.ndims() > 1) { for (unsigned i = 1; i < d.ndims(); ++i) if (d[i] != 1) return false; } return true; } template <class T> inline std::string print_vec(const std::vector<T> & vec) { std::string sep = "["; std::ostringstream oss; for(auto f : vec) { oss << sep << f; sep = ","; } oss << "]"; return oss.str(); } template <class T> inline std::string print_vecs(const std::vector<std::vector<T> > & vec) { std::string sep = "["; std::ostringstream oss; for(auto & f : vec) { oss << sep << print_vec(f); sep = ","; } oss << "]"; return oss.str(); } } // A macro to dispatch things to the appropriate device #define DYNET_NODE_DEFINE_DEV_IMPL() \ std::string as_string(const std::vector<std::string>& arg_names) const override; \ Dim dim_forward(const std::vector<Dim>& xs) const override; \ void forward_impl(const std::vector<const Tensor*>& xs, Tensor& fx) const override; \ template <class MyDevice> \ void forward_dev_impl(const MyDevice & dev, const std::vector<const Tensor*>& xs, Tensor& fx) const; \ void backward_impl(const std::vector<const Tensor*>& xs, \ const Tensor& fx, \ const Tensor& dEdf, \ unsigned i, \ Tensor& dEdxi) const override; \ template <class MyDevice> \ void backward_dev_impl( \ const MyDevice & dev, \ const std::vector<const Tensor*>& xs, \ const Tensor& fx, \ const Tensor& dEdf, \ unsigned i, \ Tensor& dEdxi) const; // A macro to instantiate templated device functions // If the implementation is the same for both devices (using Eigen Tensors), // then this will instantiate both CPU and GPU implementations, and the // code can be the same. // If the implementation is different for both devices, use #ifdef __CUDACC__ // within the function, and create alternative code paths for CPU and GPU implementations #ifdef __CUDACC__ #define DYNET_NODE_INST_DEV_IMPL(MyNode) \ template void MyNode::forward_dev_impl<Device_GPU>(const Device_GPU & dev, const vector<const Tensor*>& xs, Tensor& fx) const; \ template void MyNode::backward_dev_impl<Device_GPU>(const Device_GPU & dev, \ const vector<const Tensor*>& xs, \ const Tensor& fx, \ const Tensor& dEdf, \ unsigned i, \ Tensor& dEdxi) const; #elif HAVE_CUDA // When we have CUDA, make sure we extern the GPU code to make sure that it is only // generated by CUDACC #define DYNET_NODE_INST_DEV_IMPL(MyNode) \ extern template void MyNode::forward_dev_impl<Device_GPU>(const Device_GPU & dev, const vector<const Tensor*>& xs, Tensor& fx) const; \ extern template void MyNode::backward_dev_impl<Device_GPU>(const Device_GPU & dev, \ const vector<const Tensor*>& xs, \ const Tensor& fx, \ const Tensor& dEdf, \ unsigned i, \ Tensor& dEdxi) const; \ template void MyNode::forward_dev_impl<Device_CPU>(const Device_CPU & dev, const vector<const Tensor*>& xs, Tensor& fx) const; \ template void MyNode::backward_dev_impl<Device_CPU>(const Device_CPU & dev, \ const vector<const Tensor*>& xs, \ const Tensor& fx, \ const Tensor& dEdf, \ unsigned i, \ Tensor& dEdxi) const; \ void MyNode::forward_impl(const std::vector<const Tensor*>& xs, Tensor& fx) const { \ DYNET_ASSERT(fx.device, "Device not allocated for expression"); \ if(fx.device->type == DeviceType::CPU) { forward_dev_impl<dynet::Device_CPU>(*(dynet::Device_CPU*)fx.device,xs,fx); } \ else if(fx.device->type == DeviceType::GPU) { forward_dev_impl<dynet::Device_GPU>(*(dynet::Device_GPU*)fx.device,xs,fx); } \ else { throw std::runtime_error("Invalid device in MyNode::forward_impl"); } \ } \ void MyNode::backward_impl(const std::vector<const Tensor*>& xs, \ const Tensor& fx, \ const Tensor& dEdf, \ unsigned i, \ Tensor& dEdxi) const { \ DYNET_ASSERT(fx.device, "Device not allocated for expression"); \ if(fx.device->type == DeviceType::CPU) { backward_dev_impl<dynet::Device_CPU>(*(dynet::Device_CPU*)fx.device,xs,fx,dEdf,i,dEdxi); } \ else if(fx.device->type == DeviceType::GPU) { backward_dev_impl<dynet::Device_GPU>(*(dynet::Device_GPU*)fx.device,xs,fx,dEdf,i,dEdxi); } \ else { throw std::runtime_error("Invalid device in MyNode::backward_impl"); } \ } #else #define DYNET_NODE_INST_DEV_IMPL(MyNode) \ template void MyNode::forward_dev_impl<Device_CPU>(const Device_CPU & dev, const vector<const Tensor*>& xs, Tensor& fx) const; \ template void MyNode::backward_dev_impl<Device_CPU>(const Device_CPU & dev, \ const vector<const Tensor*>& xs, \ const Tensor& fx, \ const Tensor& dEdf, \ unsigned i, \ Tensor& dEdxi) const; \ void MyNode::forward_impl(const std::vector<const Tensor*>& xs, Tensor& fx) const { \ DYNET_ASSERT(fx.device, "Device not allocated for expression"); \ if(fx.device->type == DeviceType::CPU) { forward_dev_impl<dynet::Device_CPU>(*(dynet::Device_CPU*)fx.device,xs,fx); } \ else { throw std::runtime_error("Invalid device in MyNode::forward_impl"); } \ } \ void MyNode::backward_impl(const std::vector<const Tensor*>& xs, \ const Tensor& fx, \ const Tensor& dEdf, \ unsigned i, \ Tensor& dEdxi) const { \ DYNET_ASSERT(fx.device, "Device not allocated for expression"); \ if(fx.device->type == DeviceType::CPU) { backward_dev_impl<dynet::Device_CPU>(*(dynet::Device_CPU*)fx.device,xs,fx,dEdf,i,dEdxi); } \ else { throw std::runtime_error("Invalid device in MyNode::backward_impl"); } \ } #endif #endif
// Chemfiles, a modern library for chemistry file reading and writing // Copyright (C) Guillaume Fraux and contributors -- BSD license #ifndef CHEMFILES_CHFL_RESIDUE_H #define CHEMFILES_CHFL_RESIDUE_H #include "chemfiles/capi/types.h" #ifdef __cplusplus extern "C" { #endif /// Create a new residue with the given `name`. /// /// The caller of this function should free the allocated memory using /// `chfl_free`. /// /// @example{tests/capi/doc/chfl_residue/chfl_residue.c} /// @return A pointer to the residue, or NULL in case of error. /// You can use `chfl_last_error` to learn about the error. CHFL_EXPORT CHFL_RESIDUE* chfl_residue(const char* name); /// Create a new residue with the given `name` and residue identifier `resid`. /// /// The caller of this function should free the allocated memory using /// `chfl_free`. /// /// @example{tests/capi/doc/chfl_residue/with_id.c} /// @return A pointer to the residue, or NULL in case of error. /// You can use `chfl_last_error` to learn about the error. CHFL_EXPORT CHFL_RESIDUE* chfl_residue_with_id(const char* name, uint64_t resid); /// Get access to the residue at index `i` in a `topology`. /// /// If `i` is bigger than the result of `chfl_topology_residues_count`, this /// function will return `NULL`. /// /// The residue index in the topology is not always the same as the residue /// `id`. /// /// The `topology` will be kept alive, even if `chfl_free(topology)` is called, /// until `chfl_free` is also called on the pointer returned by this function, /// unless the pointer returned by this function is `NULL`. /// /// The pointer returned by this function points directly inside the topology, /// and will be invalidated if `chfl_topology_add_residue` is called. Calling /// any function on an invalidated pointer is undefined behavior. Even if the /// pointer if invalidated, it stills needs to be released with `chfl_free`. /// /// @example{tests/capi/doc/chfl_residue/from_topology.c} /// @return A pointer to the residue, or NULL in case of error. You can use /// `chfl_last_error` to learn about the error. CHFL_EXPORT const CHFL_RESIDUE* chfl_residue_from_topology( const CHFL_TOPOLOGY* topology, uint64_t i ); /// Get access to the residue containing the atom at index `i` in the /// `topology`. /// /// This function will return `NULL` if the atom is not in a residue, or if the /// index `i` is bigger than `chfl_topology_atoms_count`. /// /// The `topology` will be kept alive, even if `chfl_free(topology)` is called, /// until `chfl_free` is also called on the pointer returned by this function. /// /// The pointer returned by this function points directly inside the topology, /// and will be invalidated if `chfl_topology_add_residue` is called. Calling /// any function on an invalidated pointer is undefined behavior. Even if the /// pointer if invalidated, it stills needs to be released with `chfl_free`. /// /// @example{tests/capi/doc/chfl_residue/for_atom.c} /// @return A pointer to the residue, or NULL in case of error. You can use /// `chfl_last_error` to learn about the error. CHFL_EXPORT const CHFL_RESIDUE* chfl_residue_for_atom( const CHFL_TOPOLOGY* topology, uint64_t i ); /// Get a copy of a `residue`. /// /// The caller of this function should free the associated memory using /// `chfl_free`. /// /// @example{tests/capi/doc/chfl_residue/copy.c} /// @return A pointer to the new residue, or NULL in case of error. /// You can use `chfl_last_error` to learn about the error. CHFL_EXPORT CHFL_RESIDUE* chfl_residue_copy(const CHFL_RESIDUE* residue); /// Get the number of atoms in a `residue` in the integer pointed to by `count`. /// /// @example{tests/capi/doc/chfl_residue/atoms_count.c} /// @return The operation status code. You can use `chfl_last_error` to learn /// about the error if the status code is not `CHFL_SUCCESS`. CHFL_EXPORT chfl_status chfl_residue_atoms_count( const CHFL_RESIDUE* residue, uint64_t* count ); /// Get the list of atoms in the `residue` in the pre-allocated array `atoms` /// of size `natoms`. /// /// The `atoms` array size must be passed in the `natoms` parameter, and be /// equal to the result of `chfl_residue_atoms_count`. The `atoms` array is /// sorted. /// /// @example{tests/capi/doc/chfl_residue/atoms.c} /// @return The operation status code. You can use `chfl_last_error` to learn /// about the error if the status code is not `CHFL_SUCCESS`. CHFL_EXPORT chfl_status chfl_residue_atoms( const CHFL_RESIDUE* residue, uint64_t atoms[], uint64_t natoms ); /// Get the identifier of a `residue` in the initial topology file in the /// integer pointed to by `id`. /// /// This function will return `CHFL_GENERIC_ERROR` if this residue does not /// have an associated identifier. /// /// @example{tests/capi/doc/chfl_residue/id.c} /// @return The operation status code. You can use `chfl_last_error` to learn /// about the error if the status code is not `CHFL_SUCCESS`. CHFL_EXPORT chfl_status chfl_residue_id( const CHFL_RESIDUE* residue, uint64_t* id ); /// Get the name of a `residue` in the string buffer `name`. /// /// The buffer size must be passed in `buffsize`. This function will truncate /// the residue name to fit in the buffer. /// /// @example{tests/capi/doc/chfl_residue/name.c} /// @return The operation status code. You can use `chfl_last_error` to learn /// about the error if the status code is not `CHFL_SUCCESS`. CHFL_EXPORT chfl_status chfl_residue_name( const CHFL_RESIDUE* residue, char* name, uint64_t buffsize ); /// Add the atom at index `i` in the `residue`. /// /// @example{tests/capi/doc/chfl_residue/add_atom.c} /// @return The operation status code. You can use `chfl_last_error` to learn /// about the error if the status code is not `CHFL_SUCCESS`. CHFL_EXPORT chfl_status chfl_residue_add_atom( CHFL_RESIDUE* residue, uint64_t i ); /// Check if the atom at index `i` is in the `residue`, and store the result in /// `result`. /// /// @example{tests/capi/doc/chfl_residue/contains.c} /// @return The operation status code. You can use `chfl_last_error` to learn /// about the error if the status code is not `CHFL_SUCCESS`. CHFL_EXPORT chfl_status chfl_residue_contains( const CHFL_RESIDUE* residue, uint64_t i, bool* result ); /// Get the number of properties associated with this `residue` in `count`. /// /// @example{tests/capi/doc/chfl_residue/properties_count.c} /// @return The operation status code. You can use `chfl_last_error` to learn /// about the error if the status code is not `CHFL_SUCCESS`. CHFL_EXPORT chfl_status chfl_residue_properties_count( const CHFL_RESIDUE* residue, uint64_t* count ); /// Get the names of all properties of this `residue` in the pre-allocated array /// `names` of size `count`. /// /// `names` size must be passed in the `count` parameter, and be equal to the /// result of `chfl_residue_properties_count`. /// /// The pointers in `names` are only valid until a new property is added to the /// residue with `chfl_residue_set_property`. /// /// @example{tests/capi/doc/chfl_residue/list_properties.c} /// @return The operation status code. You can use `chfl_last_error` to learn /// about the error if the status code is not `CHFL_SUCCESS`. CHFL_EXPORT chfl_status chfl_residue_list_properties( const CHFL_RESIDUE* residue, const char* names[], uint64_t count ); /// Add a new `property` with the given `name` to this `residue`. /// /// If a property with the same name already exists, this function override the /// existing property with the new one. /// /// @example{tests/capi/doc/chfl_residue/property.c} /// @return The operation status code. You can use `chfl_last_error` to learn /// about the error if the status code is not `CHFL_SUCCESS`. CHFL_EXPORT chfl_status chfl_residue_set_property( CHFL_RESIDUE* residue, const char* name, const CHFL_PROPERTY* property ); /// Get a property with the given `name` in this `residue`. /// /// This function returns `NULL` if no property exists with the given name. /// /// The user of this function is responsible to deallocate memory using the /// `chfl_free` function. /// /// @example{tests/capi/doc/chfl_residue/property.c} /// @return A pointer to the property, or NULL in case of error. /// You can use `chfl_last_error` to learn about the error. CHFL_EXPORT CHFL_PROPERTY* chfl_residue_get_property( const CHFL_RESIDUE* residue, const char* name ); #ifdef __cplusplus } #endif #endif
#ifndef __FUNCTIONKEYMAP_H__ #define __FUNCTIONKEYMAP_H__ #include "KeyState.h" #include <map> namespace CGrFunctionKeyMap { typedef std::map<CGrKeyboardState,std::tstring> FunctionMap; void add(LPCTSTR line, int len, FunctionMap &fmap); bool Load(LPCTSTR lpFileName, FunctionMap &fmap); bool Save(LPCTSTR lpFileName, const FunctionMap &fmap); }; #endif // __FUNCTIONKEYMAP_H__
/*============================================================================= Created by NxtChg (admin@nxtchg.com), 2017. License: Public Domain. =============================================================================*/ /* We rely here on INADDR_ANY == 0 and INADDR_NONE == 0xFFFFFFFF. */ class net_adr { private: class IP_Range{ public: uint start, end; bool owns(int ip){ return ((uint)ip >= start && (uint)ip <= end); } }; static IP_Range local_ips[]; public: int ip; ushort port; net_adr(int port = 0){ any(); this->port = (ushort)port; } net_adr(char *ip_str, int port = 0){ set(ip_str, port); } void any(){ ip = 0; } bool ok(){ return (ip != -1); } // and (p != 0)? bool valid(){ return (ok() && ip != 0 && port > 0 && !is_local()); } bool is_local(); bool set(char *ip_str, int def_port = 0); char* str(bool with_port = false, char dst[32] = null); bool operator == (net_adr &a){ return (ip == a.ip && port == a.port); } bool operator != (net_adr &a){ return (ip != a.ip || port != a.port); } };//___________________________________________________________________________ net_adr::IP_Range net_adr::local_ips[] = { { 0x00000000, 0x00FFFFFF }, // 0.0.0.0 - 0.255.255.255 { 0x0A000000, 0x0AFFFFFF }, // 10.0.0.0 - 10.255.255.255 { 0x64400000, 0x647FFFFF }, // 100.64.0.0 - 100.127.255.255 { 0x7F000000, 0x7FFFFFFF }, // 127.0.0.0 - 127.255.255.255 { 0xA9FE0000, 0xA9FEFFFF }, // 169.254.0.0 - 169.254.255.255 { 0xAC100000, 0xAC1FFFFF }, // 172.16.0.0 - 172.31.255.255 { 0xC0000000, 0xC0000007 }, // 192.0.0.0 - 192.0.0.7 { 0xC0000200, 0xC00002FF }, // 192.0.2.0 - 192.0.2.255 { 0xC0586300, 0xC05863FF }, // 192.88.99.0 - 192.88.99.255 { 0xC0A80000, 0xC0A8FFFF }, // 192.168.0.0 - 192.168.255.255 { 0xC6120000, 0xC613FFFF }, // 198.18.0.0 - 198.19.255.255 { 0xC6336400, 0xC63364FF }, //198.51.100.0 - 198.51.100.255 { 0xCB007100, 0xCB0071FF }, // 203.0.113.0 - 203.0.113.255 { 0xE0000000, 0xEFFFFFFF }, // 224.0.0.0 - 239.255.255.255 { 0xF0000000, 0xFFFFFFFE }, // 240.0.0.0 - 255.255.255.254 { 0xFFFFFFFF, 0xFFFFFFFF }, // 255.255.255.255 };//___________________________________________________________________________ bool net_adr::is_local() { till(dimof(local_ips)){ if(local_ips[i].owns(ip)) return true; } return false; }//____________________________________________________________________________ bool net_adr::set(char *ip_str, int def_port) { char *v = ip_str, tmp[8]; int t = 0; ip = -1; port = def_port; till(4) { v = str_read(v, tmp, 8, (i < 3 ? "." : ":")); if(!v) return false; int b = atoi(tmp); if((uint)b < 256){ t |= b << (24 - i * 8); } else return false; } ip = t; if(v){ v = str_read(v, tmp, 8); if(v){ t = atoi(tmp); if(t >= 0 && t < 0x10000) port = t; } } return ok(); }//____________________________________________________________________________ char* net_adr::str(bool with_port, char dst[32]) { static char out[32]; byte *i = (byte*)&ip; if(!dst) dst = out; sprintf(dst, (with_port ? "%u.%u.%u.%u:%u" : "%u.%u.%u.%u"), i[3], i[2], i[1], i[0], port); return dst; }
/** * Copyright (c) 2017 - 2018, Nordic Semiconductor ASA * * All rights reserved. * * Redistribution and use in source and binary forms, with or without modification, * are permitted provided that the following conditions are met: * * 1. Redistributions of source code must retain the above copyright notice, this * list of conditions and the following disclaimer. * * 2. Redistributions in binary form, except as embedded into a Nordic * Semiconductor ASA integrated circuit in a product or a software update for * such product, must reproduce the above copyright notice, this list of * conditions and the following disclaimer in the documentation and/or other * materials provided with the distribution. * * 3. Neither the name of Nordic Semiconductor ASA nor the names of its * contributors may be used to endorse or promote products derived from this * software without specific prior written permission. * * 4. This software, with or without modification, must only be used with a * Nordic Semiconductor ASA integrated circuit. * * 5. Any software provided in binary form under this license must not be reverse * engineered, decompiled, modified and/or disassembled. * * THIS SOFTWARE IS PROVIDED BY NORDIC SEMICONDUCTOR ASA "AS IS" AND ANY EXPRESS * OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES * OF MERCHANTABILITY, NONINFRINGEMENT, AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL NORDIC SEMICONDUCTOR ASA OR CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE * GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT * OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * */ #include <stdlib.h> #include <string.h> #include "ant_app.h" #include "ble_serialization.h" #include "ant_struct_serialization.h" #include "cond_field_serialization.h" #include "app_util.h" uint32_t ant_channel_period_get_req_enc(uint8_t channel, uint8_t * const p_buf, uint32_t * const p_buf_len) { uint32_t index = 0; uint32_t err_code = NRF_SUCCESS; SER_ASSERT_NOT_NULL(p_buf); SER_ASSERT_NOT_NULL(p_buf_len); p_buf[index++] = SVC_ANT_CHANNEL_PERIOD_GET; p_buf[index++] = channel; SER_ASSERT_LENGTH_LEQ(index, *p_buf_len); *p_buf_len = index; return err_code; } uint32_t ant_channel_period_get_rsp_dec(uint8_t const * const p_buf, uint32_t packet_len, void * p_period, uint32_t * const p_result_code) { SER_ASSERT_NOT_NULL(p_buf); SER_ASSERT_NOT_NULL(p_result_code); uint32_t index = 0; uint32_t err_code = ser_ble_cmd_rsp_result_code_dec(p_buf, &index, packet_len, SVC_ANT_CHANNEL_PERIOD_GET, p_result_code); SER_ASSERT(err_code == NRF_SUCCESS, err_code); if (*p_result_code != NRF_SUCCESS) { SER_ASSERT_LENGTH_EQ(index, packet_len); return NRF_SUCCESS; } err_code = uint16_t_dec(p_buf, packet_len, &index, p_period); SER_ASSERT(err_code == NRF_SUCCESS, err_code); SER_ASSERT_LENGTH_EQ(index, packet_len); return NRF_SUCCESS; }
#pragma once #include "logging/logger.h" #include "digital_meter/digital_meter.h" #include "digital_meter/decoder.h" #include "config/configuration.h" #include "config/configuration.h" #include "mqtt/i_publisher.h" #include "smart_meter/smart_digital_meter.h" #include "hardware/pcb.h" #include "helpers/ip_parser.h" #include "captive_portal/captive_portal.h" #include "config/configuration_manager.h" #include "status/device_status.h" #include "version.h" #include "system/system.h"
/* // Copyright (c) 2018 Intel Corporation // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in all // copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE // SOFTWARE. */ #pragma once enum CONTROL_TYPE { CONTROL_TYPE_INT = 0, CONTROL_TYPE_BOOL = 1, CONTROL_TYPE_STRING = 2, CONTROL_TYPE_SEPARATOR = 3, }; template<class T> static CONTROL_TYPE GetControlType() { return CONTROL_TYPE_INT; } template<> static CONTROL_TYPE GetControlType<bool>() { return CONTROL_TYPE_BOOL; } template<> static CONTROL_TYPE GetControlType<std::string>() { return CONTROL_TYPE_STRING; } template<class T> static const char* GetStringDefault( T dummy ) { return ""; } template<> static const char* GetStringDefault<const char*>( const char* init ) { return init; } template<class T> static const int GetIntDefault( T init ) { return init; } template<> static const int GetIntDefault<const char*>( const char* dummy ) { return 0; } struct VarDescription { CONTROL_TYPE Type; const std::string Name; const std::string defStrValue; int defIntValue; const std::string HelpText; }; #define CLI_CONTROL( _type, _name, _init, _desc ) \ { \ GetControlType<_type>(), \ #_name, \ GetStringDefault(_init), \ GetIntDefault(_init), \ _desc, \ }, #define CLI_CONTROL_SEPARATOR( _name ) \ { \ CONTROL_TYPE_SEPARATOR, \ #_name, \ "", \ 0, \ "", \ }, static const VarDescription cVars[] = { { CONTROL_TYPE_BOOL, "BreakOnLoad", "", 0, "If set to a nonzero value, the Intercept Layer for OpenCL Applications will break into the debugger when the DLL is loaded." }, #include "..\Src\controls.h" }; const int cNumVars = sizeof(cVars) / sizeof(cVars[0]); #undef CLI_CONTROL #undef CLI_CONTROL_SEPARATOR
//.............................................................................. // // This file is part of the Jancy toolkit. // // Jancy is distributed under the MIT license. // For details see accompanying license.txt file, // the public copy of which is also available at: // http://tibbo.com/downloads/archive/jancy/license.txt // //.............................................................................. #pragma once #include "jnc_ct_CastOp.h" namespace jnc { namespace ct { //.............................................................................. class Cast_Variant: public CastOperator { public: Cast_Variant() { m_opFlags = OpFlag_LoadArrayRef; } virtual CastKind getCastKind( const Value& opValue, Type* type ) { return CastKind_ImplicitCrossFamily; } virtual bool constCast( const Value& opValue, Type* type, void* dst ); virtual bool llvmCast( const Value& opValue, Type* type, Value* resultValue ); }; //.............................................................................. class Cast_FromVariant: public CastOperator { public: virtual CastKind getCastKind( const Value& opValue, Type* type ) { return CastKind_ImplicitCrossFamily; } virtual bool constCast( const Value& opValue, Type* type, void* dst ); virtual bool llvmCast( const Value& opValue, Type* type, Value* resultValue ); }; //.............................................................................. } // namespace ct } // namespace jnc
/****************************************************************************** * @file none.h * @brief Intrinsincs when no DSP extension available * @version V1.9.0 * @date 20. July 2020 ******************************************************************************/ /* * Copyright (c) 2010-2020 Arm Limited or its affiliates. All rights reserved. * * SPDX-License-Identifier: Apache-2.0 * * Licensed under the Apache License, Version 2.0 (the License); you may * not use this file except in compliance with the License. * You may obtain a copy of the License at * * www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an AS IS BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ /* Definitions in this file are allowing to reuse some versions of the CMSIS-DSP to build on a core (M0 for instance) or a host where DSP extension are not available. Ideally a pure C version should have been used instead. But those are not always available or use a restricted set of intrinsics. */ #ifndef _NONE_H_ #define _NONE_H_ #include "third_party/cmsis/CMSIS/DSP/Include/arm_math_types.h" #ifdef __cplusplus extern "C" { #endif /* Normally those kind of definitions are in a compiler file in Core or Core_A. But for MSVC compiler it is a bit special. The goal is very specific to CMSIS-DSP and only to allow the use of this library from other systems like Python or Matlab. MSVC is not going to be used to cross-compile to ARM. So, having a MSVC compiler file in Core or Core_A would not make sense. */ #if defined ( _MSC_VER ) || defined(__GNUC_PYTHON__) __STATIC_FORCEINLINE uint8_t __CLZ(uint32_t data) { if (data == 0U) { return 32U; } uint32_t count = 0U; uint32_t mask = 0x80000000U; while ((data & mask) == 0U) { count += 1U; mask = mask >> 1U; } return count; } __STATIC_FORCEINLINE int32_t __SSAT(int32_t val, uint32_t sat) { if ((sat >= 1U) && (sat <= 32U)) { const int32_t max = (int32_t)((1U << (sat - 1U)) - 1U); const int32_t min = -1 - max ; if (val > max) { return max; } else if (val < min) { return min; } } return val; } __STATIC_FORCEINLINE uint32_t __USAT(int32_t val, uint32_t sat) { if (sat <= 31U) { const uint32_t max = ((1U << sat) - 1U); if (val > (int32_t)max) { return max; } else if (val < 0) { return 0U; } } return (uint32_t)val; } /** \brief Rotate Right in unsigned value (32 bit) \details Rotate Right (immediate) provides the value of the contents of a register rotated by a variable number of bits. \param [in] op1 Value to rotate \param [in] op2 Number of Bits to rotate \return Rotated value */ __STATIC_FORCEINLINE uint32_t __ROR(uint32_t op1, uint32_t op2) { op2 %= 32U; if (op2 == 0U) { return op1; } return (op1 >> op2) | (op1 << (32U - op2)); } #endif /** * @brief Clips Q63 to Q31 values. */ __STATIC_FORCEINLINE q31_t clip_q63_to_q31( q63_t x) { return ((q31_t) (x >> 32) != ((q31_t) x >> 31)) ? ((0x7FFFFFFF ^ ((q31_t) (x >> 63)))) : (q31_t) x; } /** * @brief Clips Q63 to Q15 values. */ __STATIC_FORCEINLINE q15_t clip_q63_to_q15( q63_t x) { return ((q31_t) (x >> 32) != ((q31_t) x >> 31)) ? ((0x7FFF ^ ((q15_t) (x >> 63)))) : (q15_t) (x >> 15); } /** * @brief Clips Q31 to Q7 values. */ __STATIC_FORCEINLINE q7_t clip_q31_to_q7( q31_t x) { return ((q31_t) (x >> 24) != ((q31_t) x >> 23)) ? ((0x7F ^ ((q7_t) (x >> 31)))) : (q7_t) x; } /** * @brief Clips Q31 to Q15 values. */ __STATIC_FORCEINLINE q15_t clip_q31_to_q15( q31_t x) { return ((q31_t) (x >> 16) != ((q31_t) x >> 15)) ? ((0x7FFF ^ ((q15_t) (x >> 31)))) : (q15_t) x; } /** * @brief Multiplies 32 X 64 and returns 32 bit result in 2.30 format. */ __STATIC_FORCEINLINE q63_t mult32x64( q63_t x, q31_t y) { return ((((q63_t) (x & 0x00000000FFFFFFFF) * y) >> 32) + (((q63_t) (x >> 32) * y) ) ); } /* SMMLAR */ #define multAcc_32x32_keep32_R(a, x, y) \ a = (q31_t) (((((q63_t) a) << 32) + ((q63_t) x * y) + 0x80000000LL ) >> 32) /* SMMLSR */ #define multSub_32x32_keep32_R(a, x, y) \ a = (q31_t) (((((q63_t) a) << 32) - ((q63_t) x * y) + 0x80000000LL ) >> 32) /* SMMULR */ #define mult_32x32_keep32_R(a, x, y) \ a = (q31_t) (((q63_t) x * y + 0x80000000LL ) >> 32) /* SMMLA */ #define multAcc_32x32_keep32(a, x, y) \ a += (q31_t) (((q63_t) x * y) >> 32) /* SMMLS */ #define multSub_32x32_keep32(a, x, y) \ a -= (q31_t) (((q63_t) x * y) >> 32) /* SMMUL */ #define mult_32x32_keep32(a, x, y) \ a = (q31_t) (((q63_t) x * y ) >> 32) #ifndef ARM_MATH_DSP /** * @brief definition to pack two 16 bit values. */ #define __PKHBT(ARG1, ARG2, ARG3) ( (((int32_t)(ARG1) << 0) & (int32_t)0x0000FFFF) | \ (((int32_t)(ARG2) << ARG3) & (int32_t)0xFFFF0000) ) #define __PKHTB(ARG1, ARG2, ARG3) ( (((int32_t)(ARG1) << 0) & (int32_t)0xFFFF0000) | \ (((int32_t)(ARG2) >> ARG3) & (int32_t)0x0000FFFF) ) #endif /** * @brief definition to pack four 8 bit values. */ #ifndef ARM_MATH_BIG_ENDIAN #define __PACKq7(v0,v1,v2,v3) ( (((int32_t)(v0) << 0) & (int32_t)0x000000FF) | \ (((int32_t)(v1) << 8) & (int32_t)0x0000FF00) | \ (((int32_t)(v2) << 16) & (int32_t)0x00FF0000) | \ (((int32_t)(v3) << 24) & (int32_t)0xFF000000) ) #else #define __PACKq7(v0,v1,v2,v3) ( (((int32_t)(v3) << 0) & (int32_t)0x000000FF) | \ (((int32_t)(v2) << 8) & (int32_t)0x0000FF00) | \ (((int32_t)(v1) << 16) & (int32_t)0x00FF0000) | \ (((int32_t)(v0) << 24) & (int32_t)0xFF000000) ) #endif /* * @brief C custom defined intrinsic functions */ #if !defined (ARM_MATH_DSP) /* * @brief C custom defined QADD8 */ __STATIC_FORCEINLINE uint32_t __QADD8( uint32_t x, uint32_t y) { q31_t r, s, t, u; r = __SSAT(((((q31_t)x << 24) >> 24) + (((q31_t)y << 24) >> 24)), 8) & (int32_t)0x000000FF; s = __SSAT(((((q31_t)x << 16) >> 24) + (((q31_t)y << 16) >> 24)), 8) & (int32_t)0x000000FF; t = __SSAT(((((q31_t)x << 8) >> 24) + (((q31_t)y << 8) >> 24)), 8) & (int32_t)0x000000FF; u = __SSAT(((((q31_t)x ) >> 24) + (((q31_t)y ) >> 24)), 8) & (int32_t)0x000000FF; return ((uint32_t)((u << 24) | (t << 16) | (s << 8) | (r ))); } /* * @brief C custom defined QSUB8 */ __STATIC_FORCEINLINE uint32_t __QSUB8( uint32_t x, uint32_t y) { q31_t r, s, t, u; r = __SSAT(((((q31_t)x << 24) >> 24) - (((q31_t)y << 24) >> 24)), 8) & (int32_t)0x000000FF; s = __SSAT(((((q31_t)x << 16) >> 24) - (((q31_t)y << 16) >> 24)), 8) & (int32_t)0x000000FF; t = __SSAT(((((q31_t)x << 8) >> 24) - (((q31_t)y << 8) >> 24)), 8) & (int32_t)0x000000FF; u = __SSAT(((((q31_t)x ) >> 24) - (((q31_t)y ) >> 24)), 8) & (int32_t)0x000000FF; return ((uint32_t)((u << 24) | (t << 16) | (s << 8) | (r ))); } /* * @brief C custom defined QADD16 */ __STATIC_FORCEINLINE uint32_t __QADD16( uint32_t x, uint32_t y) { /* q31_t r, s; without initialisation 'arm_offset_q15 test' fails but 'intrinsic' tests pass! for armCC */ q31_t r = 0, s = 0; r = __SSAT(((((q31_t)x << 16) >> 16) + (((q31_t)y << 16) >> 16)), 16) & (int32_t)0x0000FFFF; s = __SSAT(((((q31_t)x ) >> 16) + (((q31_t)y ) >> 16)), 16) & (int32_t)0x0000FFFF; return ((uint32_t)((s << 16) | (r ))); } /* * @brief C custom defined SHADD16 */ __STATIC_FORCEINLINE uint32_t __SHADD16( uint32_t x, uint32_t y) { q31_t r, s; r = (((((q31_t)x << 16) >> 16) + (((q31_t)y << 16) >> 16)) >> 1) & (int32_t)0x0000FFFF; s = (((((q31_t)x ) >> 16) + (((q31_t)y ) >> 16)) >> 1) & (int32_t)0x0000FFFF; return ((uint32_t)((s << 16) | (r ))); } /* * @brief C custom defined QSUB16 */ __STATIC_FORCEINLINE uint32_t __QSUB16( uint32_t x, uint32_t y) { q31_t r, s; r = __SSAT(((((q31_t)x << 16) >> 16) - (((q31_t)y << 16) >> 16)), 16) & (int32_t)0x0000FFFF; s = __SSAT(((((q31_t)x ) >> 16) - (((q31_t)y ) >> 16)), 16) & (int32_t)0x0000FFFF; return ((uint32_t)((s << 16) | (r ))); } /* * @brief C custom defined SHSUB16 */ __STATIC_FORCEINLINE uint32_t __SHSUB16( uint32_t x, uint32_t y) { q31_t r, s; r = (((((q31_t)x << 16) >> 16) - (((q31_t)y << 16) >> 16)) >> 1) & (int32_t)0x0000FFFF; s = (((((q31_t)x ) >> 16) - (((q31_t)y ) >> 16)) >> 1) & (int32_t)0x0000FFFF; return ((uint32_t)((s << 16) | (r ))); } /* * @brief C custom defined QASX */ __STATIC_FORCEINLINE uint32_t __QASX( uint32_t x, uint32_t y) { q31_t r, s; r = __SSAT(((((q31_t)x << 16) >> 16) - (((q31_t)y ) >> 16)), 16) & (int32_t)0x0000FFFF; s = __SSAT(((((q31_t)x ) >> 16) + (((q31_t)y << 16) >> 16)), 16) & (int32_t)0x0000FFFF; return ((uint32_t)((s << 16) | (r ))); } /* * @brief C custom defined SHASX */ __STATIC_FORCEINLINE uint32_t __SHASX( uint32_t x, uint32_t y) { q31_t r, s; r = (((((q31_t)x << 16) >> 16) - (((q31_t)y ) >> 16)) >> 1) & (int32_t)0x0000FFFF; s = (((((q31_t)x ) >> 16) + (((q31_t)y << 16) >> 16)) >> 1) & (int32_t)0x0000FFFF; return ((uint32_t)((s << 16) | (r ))); } /* * @brief C custom defined QSAX */ __STATIC_FORCEINLINE uint32_t __QSAX( uint32_t x, uint32_t y) { q31_t r, s; r = __SSAT(((((q31_t)x << 16) >> 16) + (((q31_t)y ) >> 16)), 16) & (int32_t)0x0000FFFF; s = __SSAT(((((q31_t)x ) >> 16) - (((q31_t)y << 16) >> 16)), 16) & (int32_t)0x0000FFFF; return ((uint32_t)((s << 16) | (r ))); } /* * @brief C custom defined SHSAX */ __STATIC_FORCEINLINE uint32_t __SHSAX( uint32_t x, uint32_t y) { q31_t r, s; r = (((((q31_t)x << 16) >> 16) + (((q31_t)y ) >> 16)) >> 1) & (int32_t)0x0000FFFF; s = (((((q31_t)x ) >> 16) - (((q31_t)y << 16) >> 16)) >> 1) & (int32_t)0x0000FFFF; return ((uint32_t)((s << 16) | (r ))); } /* * @brief C custom defined SMUSDX */ __STATIC_FORCEINLINE uint32_t __SMUSDX( uint32_t x, uint32_t y) { return ((uint32_t)(((((q31_t)x << 16) >> 16) * (((q31_t)y ) >> 16)) - ((((q31_t)x ) >> 16) * (((q31_t)y << 16) >> 16)) )); } /* * @brief C custom defined SMUADX */ __STATIC_FORCEINLINE uint32_t __SMUADX( uint32_t x, uint32_t y) { return ((uint32_t)(((((q31_t)x << 16) >> 16) * (((q31_t)y ) >> 16)) + ((((q31_t)x ) >> 16) * (((q31_t)y << 16) >> 16)) )); } /* * @brief C custom defined QADD */ __STATIC_FORCEINLINE int32_t __QADD( int32_t x, int32_t y) { return ((int32_t)(clip_q63_to_q31((q63_t)x + (q31_t)y))); } /* * @brief C custom defined QSUB */ __STATIC_FORCEINLINE int32_t __QSUB( int32_t x, int32_t y) { return ((int32_t)(clip_q63_to_q31((q63_t)x - (q31_t)y))); } /* * @brief C custom defined SMLAD */ __STATIC_FORCEINLINE uint32_t __SMLAD( uint32_t x, uint32_t y, uint32_t sum) { return ((uint32_t)(((((q31_t)x << 16) >> 16) * (((q31_t)y << 16) >> 16)) + ((((q31_t)x ) >> 16) * (((q31_t)y ) >> 16)) + ( ((q31_t)sum ) ) )); } /* * @brief C custom defined SMLADX */ __STATIC_FORCEINLINE uint32_t __SMLADX( uint32_t x, uint32_t y, uint32_t sum) { return ((uint32_t)(((((q31_t)x << 16) >> 16) * (((q31_t)y ) >> 16)) + ((((q31_t)x ) >> 16) * (((q31_t)y << 16) >> 16)) + ( ((q31_t)sum ) ) )); } /* * @brief C custom defined SMLSDX */ __STATIC_FORCEINLINE uint32_t __SMLSDX( uint32_t x, uint32_t y, uint32_t sum) { return ((uint32_t)(((((q31_t)x << 16) >> 16) * (((q31_t)y ) >> 16)) - ((((q31_t)x ) >> 16) * (((q31_t)y << 16) >> 16)) + ( ((q31_t)sum ) ) )); } /* * @brief C custom defined SMLALD */ __STATIC_FORCEINLINE uint64_t __SMLALD( uint32_t x, uint32_t y, uint64_t sum) { /* return (sum + ((q15_t) (x >> 16) * (q15_t) (y >> 16)) + ((q15_t) x * (q15_t) y)); */ return ((uint64_t)(((((q31_t)x << 16) >> 16) * (((q31_t)y << 16) >> 16)) + ((((q31_t)x ) >> 16) * (((q31_t)y ) >> 16)) + ( ((q63_t)sum ) ) )); } /* * @brief C custom defined SMLALDX */ __STATIC_FORCEINLINE uint64_t __SMLALDX( uint32_t x, uint32_t y, uint64_t sum) { /* return (sum + ((q15_t) (x >> 16) * (q15_t) y)) + ((q15_t) x * (q15_t) (y >> 16)); */ return ((uint64_t)(((((q31_t)x << 16) >> 16) * (((q31_t)y ) >> 16)) + ((((q31_t)x ) >> 16) * (((q31_t)y << 16) >> 16)) + ( ((q63_t)sum ) ) )); } /* * @brief C custom defined SMUAD */ __STATIC_FORCEINLINE uint32_t __SMUAD( uint32_t x, uint32_t y) { return ((uint32_t)(((((q31_t)x << 16) >> 16) * (((q31_t)y << 16) >> 16)) + ((((q31_t)x ) >> 16) * (((q31_t)y ) >> 16)) )); } /* * @brief C custom defined SMUSD */ __STATIC_FORCEINLINE uint32_t __SMUSD( uint32_t x, uint32_t y) { return ((uint32_t)(((((q31_t)x << 16) >> 16) * (((q31_t)y << 16) >> 16)) - ((((q31_t)x ) >> 16) * (((q31_t)y ) >> 16)) )); } /* * @brief C custom defined SXTB16 */ __STATIC_FORCEINLINE uint32_t __SXTB16( uint32_t x) { return ((uint32_t)(((((q31_t)x << 24) >> 24) & (q31_t)0x0000FFFF) | ((((q31_t)x << 8) >> 8) & (q31_t)0xFFFF0000) )); } /* * @brief C custom defined SMMLA */ __STATIC_FORCEINLINE int32_t __SMMLA( int32_t x, int32_t y, int32_t sum) { return (sum + (int32_t) (((int64_t) x * y) >> 32)); } #endif /* !defined (ARM_MATH_DSP) */ #ifdef __cplusplus } #endif #endif /* ifndef _TRANSFORM_FUNCTIONS_H_ */
/* * Copyright 2016 Advanced Micro Devices, Inc. * * Permission is hereby granted, free of charge, to any person obtaining a * copy of this software and associated documentation files (the "Software"), * to deal in the Software without restriction, including without limitation * the rights to use, copy, modify, merge, publish, distribute, sublicense, * and/or sell copies of the Software, and to permit persons to whom the * Software is furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice (including the next * paragraph) shall be included in all copies or substantial portions of the * Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. * */ /* This file implements randomized SDMA texture blit tests. */ #include "r600_pipe_common.h" #include "util/u_surface.h" #include "util/rand_xor.h" static uint64_t seed_xorshift128plus[2]; #define RAND_NUM_SIZE 8 /* The GPU blits are emulated on the CPU using these CPU textures. */ struct cpu_texture { uint8_t *ptr; uint64_t size; uint64_t layer_stride; unsigned stride; }; static void alloc_cpu_texture(struct cpu_texture *tex, struct pipe_resource *templ, int bpp) { tex->stride = align(templ->width0 * bpp, RAND_NUM_SIZE); tex->layer_stride = (uint64_t)tex->stride * templ->height0; tex->size = tex->layer_stride * templ->array_size; tex->ptr = malloc(tex->size); assert(tex->ptr); } static void set_random_pixels(struct pipe_context *ctx, struct pipe_resource *tex, struct cpu_texture *cpu) { struct pipe_transfer *t; uint8_t *map; int x,y,z; map = pipe_transfer_map_3d(ctx, tex, 0, PIPE_TRANSFER_WRITE, 0, 0, 0, tex->width0, tex->height0, tex->array_size, &t); assert(map); for (z = 0; z < tex->array_size; z++) { for (y = 0; y < tex->height0; y++) { uint64_t *ptr = (uint64_t*) (map + t->layer_stride*z + t->stride*y); uint64_t *ptr_cpu = (uint64_t*) (cpu->ptr + cpu->layer_stride*z + cpu->stride*y); unsigned size = cpu->stride / RAND_NUM_SIZE; assert(t->stride % RAND_NUM_SIZE == 0); assert(cpu->stride % RAND_NUM_SIZE == 0); for (x = 0; x < size; x++) { *ptr++ = *ptr_cpu++ = rand_xorshift128plus(seed_xorshift128plus); } } } pipe_transfer_unmap(ctx, t); } static bool compare_textures(struct pipe_context *ctx, struct pipe_resource *tex, struct cpu_texture *cpu, int bpp) { struct pipe_transfer *t; uint8_t *map; int y,z; bool pass = true; map = pipe_transfer_map_3d(ctx, tex, 0, PIPE_TRANSFER_READ, 0, 0, 0, tex->width0, tex->height0, tex->array_size, &t); assert(map); for (z = 0; z < tex->array_size; z++) { for (y = 0; y < tex->height0; y++) { uint8_t *ptr = map + t->layer_stride*z + t->stride*y; uint8_t *cpu_ptr = cpu->ptr + cpu->layer_stride*z + cpu->stride*y; if (memcmp(ptr, cpu_ptr, tex->width0 * bpp)) { pass = false; goto done; } } } done: pipe_transfer_unmap(ctx, t); return pass; } static enum pipe_format get_format_from_bpp(int bpp) { switch (bpp) { case 1: return PIPE_FORMAT_R8_UINT; case 2: return PIPE_FORMAT_R16_UINT; case 4: return PIPE_FORMAT_R32_UINT; case 8: return PIPE_FORMAT_R32G32_UINT; case 16: return PIPE_FORMAT_R32G32B32A32_UINT; default: assert(0); return PIPE_FORMAT_NONE; } } static const char *array_mode_to_string(struct r600_common_screen *rscreen, struct radeon_surf *surf) { if (rscreen->chip_class >= GFX9) { /* TODO */ return " UNKNOWN"; } else { switch (surf->u.legacy.level[0].mode) { case RADEON_SURF_MODE_LINEAR_ALIGNED: return "LINEAR_ALIGNED"; case RADEON_SURF_MODE_1D: return "1D_TILED_THIN1"; case RADEON_SURF_MODE_2D: return "2D_TILED_THIN1"; default: assert(0); return " UNKNOWN"; } } } static unsigned generate_max_tex_side(unsigned max_tex_side) { switch (rand() % 4) { case 0: /* Try to hit large sizes in 1/4 of the cases. */ return max_tex_side; case 1: /* Try to hit 1D tiling in 1/4 of the cases. */ return 128; default: /* Try to hit common sizes in 2/4 of the cases. */ return 2048; } } void si_test_dma(struct r600_common_screen *rscreen) { struct pipe_screen *screen = &rscreen->b; struct pipe_context *ctx = screen->context_create(screen, NULL, 0); struct r600_common_context *rctx = (struct r600_common_context*)ctx; uint64_t max_alloc_size; unsigned i, iterations, num_partial_copies, max_levels, max_tex_side; unsigned num_pass = 0, num_fail = 0; max_levels = screen->get_param(screen, PIPE_CAP_MAX_TEXTURE_2D_LEVELS); max_tex_side = 1 << (max_levels - 1); /* Max 128 MB allowed for both textures. */ max_alloc_size = 128 * 1024 * 1024; /* the seed for random test parameters */ srand(0x9b47d95b); /* the seed for random pixel data */ s_rand_xorshift128plus(seed_xorshift128plus, false); iterations = 1000000000; /* just kill it when you are bored */ num_partial_copies = 30; /* These parameters are randomly generated per test: * - whether to do one whole-surface copy or N partial copies per test * - which tiling modes to use (LINEAR_ALIGNED, 1D, 2D) * - which texture dimensions to use * - whether to use VRAM (all tiling modes) and GTT (staging, linear * only) allocations * - random initial pixels in src * - generate random subrectangle copies for partial blits */ for (i = 0; i < iterations; i++) { struct pipe_resource tsrc = {}, tdst = {}, *src, *dst; struct r600_texture *rdst; struct r600_texture *rsrc; struct cpu_texture src_cpu, dst_cpu; unsigned bpp, max_width, max_height, max_depth, j, num; unsigned gfx_blits = 0, dma_blits = 0, max_tex_side_gen; unsigned max_tex_layers; bool pass; bool do_partial_copies = rand() & 1; /* generate a random test case */ tsrc.target = tdst.target = PIPE_TEXTURE_2D_ARRAY; tsrc.depth0 = tdst.depth0 = 1; bpp = 1 << (rand() % 5); tsrc.format = tdst.format = get_format_from_bpp(bpp); max_tex_side_gen = generate_max_tex_side(max_tex_side); max_tex_layers = rand() % 4 ? 1 : 5; tsrc.width0 = (rand() % max_tex_side_gen) + 1; tsrc.height0 = (rand() % max_tex_side_gen) + 1; tsrc.array_size = (rand() % max_tex_layers) + 1; /* Have a 1/4 chance of getting power-of-two dimensions. */ if (rand() % 4 == 0) { tsrc.width0 = util_next_power_of_two(tsrc.width0); tsrc.height0 = util_next_power_of_two(tsrc.height0); } if (!do_partial_copies) { /* whole-surface copies only, same dimensions */ tdst = tsrc; } else { max_tex_side_gen = generate_max_tex_side(max_tex_side); max_tex_layers = rand() % 4 ? 1 : 5; /* many partial copies, dimensions can be different */ tdst.width0 = (rand() % max_tex_side_gen) + 1; tdst.height0 = (rand() % max_tex_side_gen) + 1; tdst.array_size = (rand() % max_tex_layers) + 1; /* Have a 1/4 chance of getting power-of-two dimensions. */ if (rand() % 4 == 0) { tdst.width0 = util_next_power_of_two(tdst.width0); tdst.height0 = util_next_power_of_two(tdst.height0); } } /* check texture sizes */ if ((uint64_t)tsrc.width0 * tsrc.height0 * tsrc.array_size * bpp + (uint64_t)tdst.width0 * tdst.height0 * tdst.array_size * bpp > max_alloc_size) { /* too large, try again */ i--; continue; } /* VRAM + the tiling mode depends on dimensions (3/4 of cases), * or GTT + linear only (1/4 of cases) */ tsrc.usage = rand() % 4 ? PIPE_USAGE_DEFAULT : PIPE_USAGE_STAGING; tdst.usage = rand() % 4 ? PIPE_USAGE_DEFAULT : PIPE_USAGE_STAGING; /* Allocate textures (both the GPU and CPU copies). * The CPU will emulate what the GPU should be doing. */ src = screen->resource_create(screen, &tsrc); dst = screen->resource_create(screen, &tdst); assert(src); assert(dst); rdst = (struct r600_texture*)dst; rsrc = (struct r600_texture*)src; alloc_cpu_texture(&src_cpu, &tsrc, bpp); alloc_cpu_texture(&dst_cpu, &tdst, bpp); printf("%4u: dst = (%5u x %5u x %u, %s), " " src = (%5u x %5u x %u, %s), bpp = %2u, ", i, tdst.width0, tdst.height0, tdst.array_size, array_mode_to_string(rscreen, &rdst->surface), tsrc.width0, tsrc.height0, tsrc.array_size, array_mode_to_string(rscreen, &rsrc->surface), bpp); fflush(stdout); /* set src pixels */ set_random_pixels(ctx, src, &src_cpu); /* clear dst pixels */ rctx->clear_buffer(ctx, dst, 0, rdst->surface.surf_size, 0, true); memset(dst_cpu.ptr, 0, dst_cpu.layer_stride * tdst.array_size); /* preparation */ max_width = MIN2(tsrc.width0, tdst.width0); max_height = MIN2(tsrc.height0, tdst.height0); max_depth = MIN2(tsrc.array_size, tdst.array_size); num = do_partial_copies ? num_partial_copies : 1; for (j = 0; j < num; j++) { int width, height, depth; int srcx, srcy, srcz, dstx, dsty, dstz; struct pipe_box box; unsigned old_num_draw_calls = rctx->num_draw_calls; unsigned old_num_dma_calls = rctx->num_dma_calls; if (!do_partial_copies) { /* copy whole src to dst */ width = max_width; height = max_height; depth = max_depth; srcx = srcy = srcz = dstx = dsty = dstz = 0; } else { /* random sub-rectangle copies from src to dst */ depth = (rand() % max_depth) + 1; srcz = rand() % (tsrc.array_size - depth + 1); dstz = rand() % (tdst.array_size - depth + 1); /* special code path to hit the tiled partial copies */ if (!rsrc->surface.is_linear && !rdst->surface.is_linear && rand() & 1) { if (max_width < 8 || max_height < 8) continue; width = ((rand() % (max_width / 8)) + 1) * 8; height = ((rand() % (max_height / 8)) + 1) * 8; srcx = rand() % (tsrc.width0 - width + 1) & ~0x7; srcy = rand() % (tsrc.height0 - height + 1) & ~0x7; dstx = rand() % (tdst.width0 - width + 1) & ~0x7; dsty = rand() % (tdst.height0 - height + 1) & ~0x7; } else { /* just make sure that it doesn't divide by zero */ assert(max_width > 0 && max_height > 0); width = (rand() % max_width) + 1; height = (rand() % max_height) + 1; srcx = rand() % (tsrc.width0 - width + 1); srcy = rand() % (tsrc.height0 - height + 1); dstx = rand() % (tdst.width0 - width + 1); dsty = rand() % (tdst.height0 - height + 1); } /* special code path to hit out-of-bounds reads in L2T */ if (rsrc->surface.is_linear && !rdst->surface.is_linear && rand() % 4 == 0) { srcx = 0; srcy = 0; srcz = 0; } } /* GPU copy */ u_box_3d(srcx, srcy, srcz, width, height, depth, &box); rctx->dma_copy(ctx, dst, 0, dstx, dsty, dstz, src, 0, &box); /* See which engine was used. */ gfx_blits += rctx->num_draw_calls > old_num_draw_calls; dma_blits += rctx->num_dma_calls > old_num_dma_calls; /* CPU copy */ util_copy_box(dst_cpu.ptr, tdst.format, dst_cpu.stride, dst_cpu.layer_stride, dstx, dsty, dstz, width, height, depth, src_cpu.ptr, src_cpu.stride, src_cpu.layer_stride, srcx, srcy, srcz); } pass = compare_textures(ctx, dst, &dst_cpu, bpp); if (pass) num_pass++; else num_fail++; printf("BLITs: GFX = %2u, DMA = %2u, %s [%u/%u]\n", gfx_blits, dma_blits, pass ? "pass" : "fail", num_pass, num_pass+num_fail); /* cleanup */ pipe_resource_reference(&src, NULL); pipe_resource_reference(&dst, NULL); free(src_cpu.ptr); free(dst_cpu.ptr); } ctx->destroy(ctx); exit(0); }
// David Eberly, Geometric Tools, Redmond WA 98052 // Copyright (c) 1998-2019 // Distributed under the Boost Software License, Version 1.0. // https://www.boost.org/LICENSE_1_0.txt // https://www.geometrictools.com/License/Boost/LICENSE_1_0.txt // Version: 4.0.2019.08.13 #pragma once #include <Mathematics/BasisFunction.h> #include <Mathematics/ParametricSurface.h> #include <Mathematics/Vector.h> namespace gte { template <int N, typename Real> class NURBSSurface : public ParametricSurface<N, Real> { public: // Construction. If the input controls is non-null, a copy is made of // the controls. To defer setting the control points or weights, pass // null pointers and later access the control points or weights via // GetControls(), GetWeights(), SetControl(), or SetWeight() member // functions. The 'controls' and 'weights' must be stored in // row-major order, attribute[i0 + numControls0*i1]. As a 2D array, // this corresponds to attribute2D[i1][i0]. NURBSSurface(BasisFunctionInput<Real> const& input0, BasisFunctionInput<Real> const& input1, Vector<N, Real> const* controls, Real const* weights) : ParametricSurface<N, Real>((Real)0, (Real)1, (Real)0, (Real)1, true) { BasisFunctionInput<Real> const* input[2] = { &input0, &input1 }; for (int i = 0; i < 2; ++i) { mNumControls[i] = input[i]->numControls; mBasisFunction[i].Create(*input[i]); } // The mBasisFunction stores the domain but so does // ParametricSurface. this->mUMin = mBasisFunction[0].GetMinDomain(); this->mUMax = mBasisFunction[0].GetMaxDomain(); this->mVMin = mBasisFunction[1].GetMinDomain(); this->mVMax = mBasisFunction[1].GetMaxDomain(); // The replication of control points for periodic splines is // avoided by wrapping the i-loop index in Evaluate. int numControls = mNumControls[0] * mNumControls[1]; mControls.resize(numControls); mWeights.resize(numControls); if (controls) { std::copy(controls, controls + numControls, mControls.begin()); } else { std::memset(mControls.data(), 0, mControls.size() * sizeof(mControls[0])); } if (weights) { std::copy(weights, weights + numControls, mWeights.begin()); } else { std::memset(mWeights.data(), 0, mWeights.size() * sizeof(mWeights[0])); } this->mConstructed = true; } // Member access. The index 'dim' must be in {0,1}. inline BasisFunction<Real> const& GetBasisFunction(int dim) const { return mBasisFunction[dim]; } inline int GetNumControls(int dim) const { return mNumControls[dim]; } inline Vector<N, Real> const* GetControls() const { return mControls.data(); } inline Vector<N, Real>* GetControls() { return mControls.data(); } inline Real const* GetWeights() const { return mWeights.data(); } inline Real* GetWeights() { return mWeights.data(); } void SetControl(int i0, int i1, Vector<N, Real> const& control) { if (0 <= i0 && i0 < GetNumControls(0) && 0 <= i1 && i1 < GetNumControls(1)) { mControls[i0 + mNumControls[0] * i1] = control; } } Vector<N, Real> const& GetControl(int i0, int i1) const { if (0 <= i0 && i0 < GetNumControls(0) && 0 <= i1 && i1 < GetNumControls(1)) { return mControls[i0 + mNumControls[0] * i1]; } else { return mControls[0]; } } void SetWeight(int i0, int i1, Real weight) { if (0 <= i0 && i0 < GetNumControls(0) && 0 <= i1 && i1 < GetNumControls(1)) { mWeights[i0 + mNumControls[0] * i1] = weight; } } Real const& GetWeight(int i0, int i1) const { if (0 <= i0 && i0 < GetNumControls(0) && 0 <= i1 && i1 < GetNumControls(1)) { return mWeights[i0 + mNumControls[0] * i1]; } else { return mWeights[0]; } } // Evaluation of the surface. The function supports derivative // calculation through order 2; that is, order <= 2 is required. If // you want only the position, pass in order of 0. If you want the // position and first-order derivatives, pass in order of 1, and so // on. The output array 'jet' must have enough storage to support the // maximum order. The values are ordered as: position X; first-order // derivatives dX/du, dX/dv; second-order derivatives d2X/du2, // d2X/dudv, d2X/dv2. virtual void Evaluate(Real u, Real v, unsigned int order, Vector<N, Real>* jet) const override { unsigned int const supOrder = ParametricSurface<N, Real>::SUP_ORDER; if (!this->mConstructed || order >= supOrder) { // Return a zero-valued jet for invalid state. for (unsigned int i = 0; i < supOrder; ++i) { jet[i].MakeZero(); } return; } int iumin, iumax, ivmin, ivmax; mBasisFunction[0].Evaluate(u, order, iumin, iumax); mBasisFunction[1].Evaluate(v, order, ivmin, ivmax); // Compute position. Vector<N, Real> X; Real w; Compute(0, 0, iumin, iumax, ivmin, ivmax, X, w); Real invW = (Real)1 / w; jet[0] = invW * X; if (order >= 1) { // Compute first-order derivatives. Vector<N, Real> XDerU; Real wDerU; Compute(1, 0, iumin, iumax, ivmin, ivmax, XDerU, wDerU); jet[1] = invW * (XDerU - wDerU * jet[0]); Vector<N, Real> XDerV; Real wDerV; Compute(0, 1, iumin, iumax, ivmin, ivmax, XDerV, wDerV); jet[2] = invW * (XDerV - wDerV * jet[0]); if (order >= 2) { // Compute second-order derivatives. Vector<N, Real> XDerUU; Real wDerUU; Compute(2, 0, iumin, iumax, ivmin, ivmax, XDerUU, wDerUU); jet[3] = invW * (XDerUU - (Real)2 * wDerU * jet[1] - wDerUU * jet[0]); Vector<N, Real> XDerUV; Real wDerUV; Compute(1, 1, iumin, iumax, ivmin, ivmax, XDerUV, wDerUV); jet[4] = invW * (XDerUV - wDerU * jet[2] - wDerV * jet[1] - wDerUV * jet[0]); Vector<N, Real> XDerVV; Real wDerVV; Compute(0, 2, iumin, iumax, ivmin, ivmax, XDerVV, wDerVV); jet[5] = invW * (XDerVV - (Real)2 * wDerV * jet[2] - wDerVV * jet[0]); } } } protected: // Support for Evaluate(...). void Compute(unsigned int uOrder, unsigned int vOrder, int iumin, int iumax, int ivmin, int ivmax, Vector<N, Real>& X, Real& w) const { // The j*-indices introduce a tiny amount of overhead in order to handle // both aperiodic and periodic splines. For aperiodic splines, j* = i* // always. int const numControls0 = mNumControls[0]; int const numControls1 = mNumControls[1]; X.MakeZero(); w = (Real)0; for (int iv = ivmin; iv <= ivmax; ++iv) { Real tmpv = mBasisFunction[1].GetValue(vOrder, iv); int jv = (iv >= numControls1 ? iv - numControls1 : iv); for (int iu = iumin; iu <= iumax; ++iu) { Real tmpu = mBasisFunction[0].GetValue(uOrder, iu); int ju = (iu >= numControls0 ? iu - numControls0 : iu); int index = ju + numControls0 * jv; Real tmp = tmpu * tmpv * mWeights[index]; X += tmp * mControls[index]; w += tmp; } } } std::array<BasisFunction<Real>, 2> mBasisFunction; std::array<int, 2> mNumControls; std::vector<Vector<N, Real>> mControls; std::vector<Real> mWeights; }; }
#include <tchar.h> #include <windows.h> #define SCR_W 1536 #define SCR_H 864 #define COLOR RGB(0, 0, 0) #define ALPHA 127 #define INTERVAL 200 #define IDT_TIMER_TOPMOST 0 HWND hwnd; /* A 'HANDLE', hence the H, or a pointer to our window */ HBRUSH hbrush; /* handle to the background brush */ /* This is where all the input to the window goes to */ LRESULT CALLBACK WndProc(HWND hwnd, UINT Message, WPARAM wParam, LPARAM lParam) { switch (Message) { case WM_TIMER: /* Set to the topmost repeatly */ if (wParam == IDT_TIMER_TOPMOST) SetWindowPos(hwnd, HWND_TOPMOST, 0, 0, 0, 0, SWP_NOSIZE | SWP_NOMOVE | SWP_NOACTIVATE); break; case WM_DESTROY: /* Upon destruction, tell the main thread to stop */ DeleteObject(hbrush); KillTimer(hwnd, IDT_TIMER_TOPMOST); PostQuitMessage(0); break; default: /* All other messages (a lot of them) are processed using default procedures */ return DefWindowProc(hwnd, Message, wParam, lParam); } return 0; } /* The 'main' function of Win32 GUI programs: this is where execution starts */ int WINAPI WinMain(HINSTANCE hInstance, HINSTANCE hPrevInstance, LPSTR lpCmdLine, int nCmdShow) { WNDCLASSEX wc; /* A properties struct of our window */ MSG msg; /* A temporary location for all messages */ /* zero out the struct and set the stuff we want to modify */ memset(&wc, 0, sizeof(wc)); wc.cbSize = sizeof(WNDCLASSEX); wc.lpfnWndProc = WndProc; /* This is where we will send messages to */ wc.hInstance = hInstance; wc.hCursor = LoadCursor(NULL, IDC_ARROW); wc.hbrBackground = hbrush = CreateSolidBrush(COLOR); wc.lpszClassName = _T("GrayWindow"); wc.hIcon = LoadIcon(NULL, IDI_APPLICATION); /* Load a standard icon */ wc.hIconSm = LoadIcon(NULL, IDI_APPLICATION); /* use the name "A" to use the project icon */ if (!RegisterClassEx(&wc)) { MessageBox(NULL, _T("Window Registration Failed!"), _T("Error!"), MB_ICONEXCLAMATION | MB_OK); return 0; } hwnd = CreateWindowEx(WS_EX_LAYERED | WS_EX_TOPMOST | WS_EX_TRANSPARENT | WS_EX_TOOLWINDOW, _T("GrayWindow"), _T("GrayScreen"), WS_VISIBLE | WS_POPUP, CW_USEDEFAULT, /* x */ CW_USEDEFAULT, /* y */ SCR_W, /* width */ SCR_H, /* height */ NULL, NULL, hInstance, NULL); if (hwnd == NULL) { MessageBox(NULL, _T("Window Creation Failed!"), _T("Error!"), MB_ICONEXCLAMATION | MB_OK); return 0; } SetLayeredWindowAttributes(hwnd, 0, ALPHA, LWA_ALPHA); /* Set the alpha */ SetTimer(hwnd, IDT_TIMER_TOPMOST, INTERVAL, NULL); /* Start the timer */ /* This is the heart of our program where all input is processed and sent to WndProc. Note that GetMessage blocks code flow until it receives something, so this loop will not produce unreasonably high CPU usage */ while (GetMessage(&msg, NULL, 0, 0) > 0) { /* If no error is received... */ TranslateMessage(&msg); /* Translate key codes to chars if present */ DispatchMessage(&msg); /* Send it to WndProc */ } return msg.wParam; }
// Copyright [2021] [FORTH-ICS] // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. #pragma once #include <stdint.h> typedef void *par_handle; typedef void *par_scanner; typedef enum par_seek_mode { PAR_GREATER, PAR_GREATER_OR_EQUAL, PAR_FETCH_FIRST } par_seek_mode; typedef enum par_ret_code { PAR_SUCCESS = 0, PAR_FAILURE, PAR_KEY_NOT_FOUND, PAR_GET_NOT_ENOUGH_BUFFER_SPACE } par_ret_code; typedef enum par_db_initializers { PAR_CREATE_DB = 4, PAR_DONOT_CREATE_DB = 5 } par_db_initializers; // par_db_options contains the basic metadata to initialize a DB. typedef struct par_db_options { char *volume_name; /*File or a block device to store the DB's data*/ const char *db_name; /*DB name*/ uint64_t volume_start; /* Base offset to the file or device to write data */ uint64_t volume_size; /* File or device size */ /** *With PAR_CREATE_DB the DB if is created if it does not exist. With PAR_DONOT_CREATE_DB the DB is not created if it exists */ enum par_db_initializers create_flag; } par_db_options; struct par_key { uint32_t size; const char *data; }; struct par_value { uint32_t val_buffer_size; uint32_t val_size; char *val_buffer; }; struct par_key_value { struct par_key k; struct par_value v; }; /** * Calls the device formatting function of Parallax to initialize the volume's metadata. It does the same job as kv_format.parallax. * @param device_name Raw device or file to XFS filesystem. e.g /dev/sdc or /home/test/test.dat * @param max_regions_num Maximum regions that will be needed in this deployment it should always be > 1. * */ void par_format(char *device_name, uint32_t max_regions_num); /** *Opens a DB based on the options provided. */ par_handle par_open(par_db_options *options); /** * Closes the DB referenced by handle. Syncs data to the file or device before exiting. */ void par_close(par_handle handle); /** * Inserts the key in the DB if it does not exist else this becomes an update internally. */ par_ret_code par_put(par_handle handle, struct par_key_value *key_value); /** * Inserts a serialized key value pair by using the buffer provided by the user. * @param serialized_key_value is a buffer containing the serialized key value pair. * The format of the key value pair is | key_size | key | value_size | value |, where {key,value}_size is uint32_t. * */ par_ret_code par_put_serialized(par_handle handle, char *serialized_key_value); /** * Takes as input a key and searches for it. If the key exists in the DB then, it allocates the value if it is NULL and the client is responsible to release the memory. * Otherwise it copies the data to the existing data buffer provided by the value pointer. * @return PAR_GET_NOT_ENOUGH_BUFFER_SPACE when the user provided buffer does not have enough space to store the value. */ par_ret_code par_get(par_handle handle, struct par_key *key, struct par_value *value); /** * Searches for a key and returns if the key exists in the DB. */ par_ret_code par_exists(par_handle handle, struct par_key *key); /** * Deletes an existing key in the DB. */ par_ret_code par_delete(par_handle handle, struct par_key *key); /** * scanner API. At the current state scanner supports snapshot isolation. The lifetime of a scanner start with * a call to par_init_scanner and ends with par_close_scanner. Currently, to provide snapshot isolation during * an active scanner no updates or insers can be performed in the DB. We will add other types of scanner with * relaxed semantics for higher concurrency soon */ par_scanner par_init_scanner(par_handle handle, struct par_key *key, par_seek_mode mode); void par_close_scanner(par_scanner sc); /** * Advances the scanner iterator to the next key-value. */ int par_get_next(par_scanner sc); /** * Checks the scanner if the current key-value is valid else we reached the end of database. */ int par_is_valid(par_scanner sc); /** * Takes a scanner and returns the current key size + key in the iterator. */ struct par_key par_get_key(par_scanner sc); /** * Takes a scanner and returns the current value size + value in the iterator. */ struct par_value par_get_value(par_scanner sc); /** * Syncs data to the file or device. */ par_ret_code par_sync(par_handle handle); /* #endif // __PARALLAX_H_ */
/* $FreeBSD: releng/11.0/lib/libiconv_modules/VIQR/citrus_viqr.c 281550 2015-04-15 09:09:20Z tijl $ */ /* $NetBSD: citrus_viqr.c,v 1.5 2011/11/19 18:20:13 tnozaki Exp $ */ /*- * Copyright (c)2006 Citrus Project, * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF * SUCH DAMAGE. * */ #include <sys/cdefs.h> #include <sys/queue.h> #include <sys/types.h> #include <assert.h> #include <errno.h> #include <limits.h> #include <stddef.h> #include <stdint.h> #include <stdlib.h> #include <string.h> #include <wchar.h> #include "citrus_namespace.h" #include "citrus_types.h" #include "citrus_bcs.h" #include "citrus_module.h" #include "citrus_stdenc.h" #include "citrus_viqr.h" #define ESCAPE '\\' /* * this table generated from RFC 1456. */ static const char *mnemonic_rfc1456[0x100] = { NULL , NULL , "A(?", NULL , NULL , "A(~", "A^~", NULL , NULL , NULL , NULL , NULL , NULL , NULL , NULL , NULL , NULL , NULL , NULL , NULL , "Y?" , NULL , NULL , NULL , NULL , "Y~" , NULL , NULL , NULL , NULL , "Y." , NULL , NULL , NULL , NULL , NULL , NULL , NULL , NULL , NULL , NULL , NULL , NULL , NULL , NULL , NULL , NULL , NULL , NULL , NULL , NULL , NULL , NULL , NULL , NULL , NULL , NULL , NULL , NULL , NULL , NULL , NULL , NULL , NULL , NULL , NULL , NULL , NULL , NULL , NULL , NULL , NULL , NULL , NULL , NULL , NULL , NULL , NULL , NULL , NULL , NULL , NULL , NULL , NULL , NULL , NULL , NULL , NULL , NULL , NULL , NULL , NULL , NULL , NULL , NULL , NULL , NULL , NULL , NULL , NULL , NULL , NULL , NULL , NULL , NULL , NULL , NULL , NULL , NULL , NULL , NULL , NULL , NULL , NULL , NULL , NULL , NULL , NULL , NULL , NULL , NULL , NULL , NULL , NULL , NULL , NULL , NULL , NULL , "A." , "A('", "A(`", "A(.", "A^'", "A^`", "A^?", "A^.", "E~" , "E." , "E^'", "E^`", "E^?", "E^~", "E^.", "O^'", "O^`", "O^?", "O^~", "O^.", "O+.", "O+'", "O+`", "O+?", "I." , "O?" , "O." , "I?" , "U?" , "U~" , "U." , "Y`" , "O~" , "a('", "a(`", "a(.", "a^'", "a^`", "a^?", "a^.", "e~" , "e." , "e^'", "e^`", "e^?", "e^~", "e^.", "o^'", "o^`", "o^?", "o^~", "O+~", "O+" , "o^.", "o+`", "o+?", "i." , "U+.", "U+'", "U+`", "U+?", "o+" , "o+'", "U+" , "A`" , "A'" , "A^" , "A~" , "A?" , "A(" , "a(?", "a(~", "E`" , "E'" , "E^" , "E?" , "I`" , "I'" , "I~" , "y`" , "DD" , "u+'", "O`" , "O'" , "O^" , "a." , "y?" , "u+`", "u+?", "U`" , "U'" , "y~" , "y." , "Y'" , "o+~", "u+" , "a`" , "a'" , "a^" , "a~" , "a?" , "a(" , "u+~", "a^~", "e`" , "e'" , "e^" , "e?" , "i`" , "i'" , "i~" , "i?" , "dd" , "u+.", "o`" , "o'" , "o^" , "o~" , "o?" , "o." , "u." , "u`" , "u'" , "u~" , "u?" , "y'" , "o+.", "U+~", }; typedef struct { const char *name; wchar_t value; } mnemonic_def_t; static const mnemonic_def_t mnemonic_ext[] = { /* add extra mnemonic here (should be sorted by wchar_t order). */ }; static const size_t mnemonic_ext_size = sizeof(mnemonic_ext) / sizeof(mnemonic_def_t); static const char * mnemonic_ext_find(wchar_t wc, const mnemonic_def_t *head, size_t n) { const mnemonic_def_t *mid; for (; n > 0; n >>= 1) { mid = head + (n >> 1); if (mid->value == wc) return (mid->name); else if (mid->value < wc) { head = mid + 1; --n; } } return (NULL); } struct mnemonic_t; typedef TAILQ_HEAD(mnemonic_list_t, mnemonic_t) mnemonic_list_t; typedef struct mnemonic_t { TAILQ_ENTRY(mnemonic_t) entry; struct mnemonic_t *parent; mnemonic_list_t child; wchar_t value; int ascii; } mnemonic_t; static mnemonic_t * mnemonic_list_find(mnemonic_list_t *ml, int ch) { mnemonic_t *m; TAILQ_FOREACH(m, ml, entry) { if (m->ascii == ch) return (m); } return (NULL); } static mnemonic_t * mnemonic_create(mnemonic_t *parent, int ascii, wchar_t value) { mnemonic_t *m; m = malloc(sizeof(*m)); if (m != NULL) { m->parent = parent; m->ascii = ascii; m->value = value; TAILQ_INIT(&m->child); } return (m); } static int mnemonic_append_child(mnemonic_t *m, const char *s, wchar_t value, wchar_t invalid) { mnemonic_t *m0; int ch; ch = (unsigned char)*s++; if (ch == '\0') return (EINVAL); m0 = mnemonic_list_find(&m->child, ch); if (m0 == NULL) { m0 = mnemonic_create(m, ch, (wchar_t)ch); if (m0 == NULL) return (ENOMEM); TAILQ_INSERT_TAIL(&m->child, m0, entry); } m = m0; for (m0 = NULL; (ch = (unsigned char)*s) != '\0'; ++s) { m0 = mnemonic_list_find(&m->child, ch); if (m0 == NULL) { m0 = mnemonic_create(m, ch, invalid); if (m0 == NULL) return (ENOMEM); TAILQ_INSERT_TAIL(&m->child, m0, entry); } m = m0; } if (m0 == NULL) return (EINVAL); m0->value = value; return (0); } static void mnemonic_destroy(mnemonic_t *m) { mnemonic_t *m0; TAILQ_FOREACH(m0, &m->child, entry) mnemonic_destroy(m0); free(m); } typedef struct { mnemonic_t *mroot; wchar_t invalid; size_t mb_cur_max; } _VIQREncodingInfo; typedef struct { int chlen; char ch[MB_LEN_MAX]; } _VIQRState; #define _CEI_TO_EI(_cei_) (&(_cei_)->ei) #define _CEI_TO_STATE(_cei_, _func_) (_cei_)->states.s_##_func_ #define _FUNCNAME(m) _citrus_VIQR_##m #define _ENCODING_INFO _VIQREncodingInfo #define _ENCODING_STATE _VIQRState #define _ENCODING_MB_CUR_MAX(_ei_) (_ei_)->mb_cur_max #define _ENCODING_IS_STATE_DEPENDENT 1 #define _STATE_NEEDS_EXPLICIT_INIT(_ps_) 0 static __inline void /*ARGSUSED*/ _citrus_VIQR_init_state(_VIQREncodingInfo * __restrict ei __unused, _VIQRState * __restrict psenc) { psenc->chlen = 0; } #if 0 static __inline void /*ARGSUSED*/ _citrus_VIQR_pack_state(_VIQREncodingInfo * __restrict ei __unused, void *__restrict pspriv, const _VIQRState * __restrict psenc) { memcpy(pspriv, (const void *)psenc, sizeof(*psenc)); } static __inline void /*ARGSUSED*/ _citrus_VIQR_unpack_state(_VIQREncodingInfo * __restrict ei __unused, _VIQRState * __restrict psenc, const void * __restrict pspriv) { memcpy((void *)psenc, pspriv, sizeof(*psenc)); } #endif static int _citrus_VIQR_mbrtowc_priv(_VIQREncodingInfo * __restrict ei, wchar_t * __restrict pwc, char ** __restrict s, size_t n, _VIQRState * __restrict psenc, size_t * __restrict nresult) { mnemonic_t *m, *m0; char *s0; wchar_t wc; ssize_t i; int ch, escape; if (*s == NULL) { _citrus_VIQR_init_state(ei, psenc); *nresult = (size_t)_ENCODING_IS_STATE_DEPENDENT; return (0); } s0 = *s; i = 0; m = ei->mroot; for (escape = 0;;) { if (psenc->chlen == i) { if (n-- < 1) { *s = s0; *nresult = (size_t)-2; return (0); } psenc->ch[psenc->chlen++] = *s0++; } ch = (unsigned char)psenc->ch[i++]; if (ch == ESCAPE) { if (m != ei->mroot) break; escape = 1; continue; } if (escape != 0) break; m0 = mnemonic_list_find(&m->child, ch); if (m0 == NULL) break; m = m0; } while (m != ei->mroot) { --i; if (m->value != ei->invalid) break; m = m->parent; } if (ch == ESCAPE && m != ei->mroot) ++i; psenc->chlen -= i; memmove(&psenc->ch[0], &psenc->ch[i], psenc->chlen); wc = (m == ei->mroot) ? (wchar_t)ch : m->value; if (pwc != NULL) *pwc = wc; *nresult = (size_t)(wc == 0 ? 0 : s0 - *s); *s = s0; return (0); } static int _citrus_VIQR_wcrtomb_priv(_VIQREncodingInfo * __restrict ei, char * __restrict s, size_t n, wchar_t wc, _VIQRState * __restrict psenc, size_t * __restrict nresult) { mnemonic_t *m; const char *p; int ch = 0; switch (psenc->chlen) { case 0: case 1: break; default: return (EINVAL); } m = NULL; if ((uint32_t)wc <= 0xFF) { p = mnemonic_rfc1456[wc & 0xFF]; if (p != NULL) goto mnemonic_found; if (n-- < 1) goto e2big; ch = (unsigned int)wc; m = ei->mroot; if (psenc->chlen > 0) { m = mnemonic_list_find(&m->child, psenc->ch[0]); if (m == NULL) return (EINVAL); psenc->ch[0] = ESCAPE; } if (mnemonic_list_find(&m->child, ch) == NULL) { psenc->chlen = 0; m = NULL; } psenc->ch[psenc->chlen++] = ch; } else { p = mnemonic_ext_find(wc, &mnemonic_ext[0], mnemonic_ext_size); if (p == NULL) { *nresult = (size_t)-1; return (EILSEQ); } else { mnemonic_found: psenc->chlen = 0; while (*p != '\0') { if (n-- < 1) goto e2big; psenc->ch[psenc->chlen++] = *p++; } } } memcpy(s, psenc->ch, psenc->chlen); *nresult = psenc->chlen; if (m == ei->mroot) { psenc->ch[0] = ch; psenc->chlen = 1; } else psenc->chlen = 0; return (0); e2big: *nresult = (size_t)-1; return (E2BIG); } static int /* ARGSUSED */ _citrus_VIQR_put_state_reset(_VIQREncodingInfo * __restrict ei __unused, char * __restrict s __unused, size_t n __unused, _VIQRState * __restrict psenc, size_t * __restrict nresult) { switch (psenc->chlen) { case 0: case 1: break; default: return (EINVAL); } *nresult = 0; psenc->chlen = 0; return (0); } static __inline int /*ARGSUSED*/ _citrus_VIQR_stdenc_wctocs(_VIQREncodingInfo * __restrict ei __unused, _csid_t * __restrict csid, _index_t * __restrict idx, wchar_t wc) { *csid = 0; *idx = (_index_t)wc; return (0); } static __inline int /*ARGSUSED*/ _citrus_VIQR_stdenc_cstowc(_VIQREncodingInfo * __restrict ei __unused, wchar_t * __restrict pwc, _csid_t csid, _index_t idx) { if (csid != 0) return (EILSEQ); *pwc = (wchar_t)idx; return (0); } static void _citrus_VIQR_encoding_module_uninit(_VIQREncodingInfo *ei) { mnemonic_destroy(ei->mroot); } static int /*ARGSUSED*/ _citrus_VIQR_encoding_module_init(_VIQREncodingInfo * __restrict ei, const void * __restrict var __unused, size_t lenvar __unused) { const char *s; size_t i, n; int errnum; ei->mb_cur_max = 1; ei->invalid = (wchar_t)-1; ei->mroot = mnemonic_create(NULL, '\0', ei->invalid); if (ei->mroot == NULL) return (ENOMEM); for (i = 0; i < sizeof(mnemonic_rfc1456) / sizeof(const char *); ++i) { s = mnemonic_rfc1456[i]; if (s == NULL) continue; n = strlen(s); if (ei->mb_cur_max < n) ei->mb_cur_max = n; errnum = mnemonic_append_child(ei->mroot, s, (wchar_t)i, ei->invalid); if (errnum != 0) { _citrus_VIQR_encoding_module_uninit(ei); return (errnum); } } /* a + 1 < b + 1 here to silence gcc warning about unsigned < 0. */ for (i = 0; i + 1 < mnemonic_ext_size + 1; ++i) { const mnemonic_def_t *p; p = &mnemonic_ext[i]; n = strlen(p->name); if (ei->mb_cur_max < n) ei->mb_cur_max = n; errnum = mnemonic_append_child(ei->mroot, p->name, p->value, ei->invalid); if (errnum != 0) { _citrus_VIQR_encoding_module_uninit(ei); return (errnum); } } return (0); } static __inline int /*ARGSUSED*/ _citrus_VIQR_stdenc_get_state_desc_generic(_VIQREncodingInfo * __restrict ei __unused, _VIQRState * __restrict psenc, int * __restrict rstate) { *rstate = (psenc->chlen == 0) ? _STDENC_SDGEN_INITIAL : _STDENC_SDGEN_INCOMPLETE_CHAR; return (0); } /* ---------------------------------------------------------------------- * public interface for stdenc */ _CITRUS_STDENC_DECLS(VIQR); _CITRUS_STDENC_DEF_OPS(VIQR); #include "citrus_stdenc_template.h"
/***************************************************************************** * * netapp.h - CC3000 Host Driver Implementation. * Copyright (C) 2011 Texas Instruments Incorporated - http://www.ti.com/ * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the * distribution. * * Neither the name of Texas Instruments Incorporated nor the names of * its contributors may be used to endorse or promote products derived * from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * *****************************************************************************/ #ifndef __NETAPP_H__ #define __NETAPP_H__ #include "cc3000_common.h" //***************************************************************************** // // If building with a C++ compiler, make all of the definitions in this header // have a C binding. // //***************************************************************************** #ifdef __cplusplus extern "C" { #endif //***************************************************************************** // //! \addtogroup netapp_api //! @{ // //***************************************************************************** //***************************************************************************** // //! netapp_config_mac_adrress //! //! @param mac device mac address, 6 bytes. Saved: yes //! //! @return return on success 0, otherwise error. //! //! @brief Configure device MAC address and store it in NVMEM. //! The value of the MAC address configured through the API will //! be stored in CC3000 non volatile memory, thus preserved //! over resets. // //***************************************************************************** extern long netapp_config_mac_adrress( unsigned char *mac ); //***************************************************************************** // //! netapp_dhcp //! //! @param aucIP device mac address, 6 bytes. Saved: yes //! @param aucSubnetMask device mac address, 6 bytes. Saved: yes //! @param aucDefaultGateway device mac address, 6 bytes. Saved: yes //! @param aucDNSServer device mac address, 6 bytes. Saved: yes //! //! @return return on success 0, otherwise error. //! //! @brief netapp_dhcp is used to configure the network interface, //! static or dynamic (DHCP).\n In order to activate DHCP mode, //! aucIP, aucSubnetMask, aucDefaultGateway must be 0. //! The default mode of CC3000 is DHCP mode. //! Note that the configuration is saved in non volatile memory //! and thus preserved over resets. //! //! @note If the mode is altered a reset of CC3000 device is required //! in order to apply changes.\nAlso note that asynchronous event //! of DHCP_EVENT, which is generated when an IP address is //! allocated either by the DHCP server or due to static //! allocation is generated only upon a connection to the //! AP was established. //! //***************************************************************************** extern long netapp_dhcp(unsigned long *aucIP, unsigned long *aucSubnetMask,unsigned long *aucDefaultGateway, unsigned long *aucDNSServer); //***************************************************************************** // //! netapp_timeout_values //! //! @param aucDHCP DHCP lease time request, also impact //! the DHCP renew timeout. Range: [0-0xffffffff] seconds, //! 0 or 0xffffffff == infinity lease timeout. //! Resolution:10 seconds. Influence: only after //! reconnecting to the AP. //! Minimal bound value: MIN_TIMER_VAL_SECONDS - 20 seconds. //! The parameter is saved into the CC3000 NVMEM. //! The default value on CC3000 is 14400 seconds. //! //! @param aucARP ARP refresh timeout, if ARP entry is not updated by //! incoming packet, the ARP entry will be deleted by //! the end of the timeout. //! Range: [0-0xffffffff] seconds, 0 == infinity ARP timeout //! Resolution: 10 seconds. Influence: on runtime. //! Minimal bound value: MIN_TIMER_VAL_SECONDS - 20 seconds //! The parameter is saved into the CC3000 NVMEM. //! The default value on CC3000 is 3600 seconds. //! //! @param aucKeepalive Keepalive event sent by the end of keepalive timeout //! Range: [0-0xffffffff] seconds, 0 == infinity timeout //! Resolution: 10 seconds. //! Influence: on runtime. //! Minimal bound value: MIN_TIMER_VAL_SECONDS - 20 sec //! The parameter is saved into the CC3000 NVMEM. //! The default value on CC3000 is 10 seconds. //! //! @param aucInactivity Socket inactivity timeout, socket timeout is //! refreshed by incoming or outgoing packet, by the //! end of the socket timeout the socket will be closed //! Range: [0-0xffffffff] sec, 0 == infinity timeout. //! Resolution: 10 seconds. Influence: on runtime. //! Minimal bound value: MIN_TIMER_VAL_SECONDS - 20 sec //! The parameter is saved into the CC3000 NVMEM. //! The default value on CC3000 is 60 seconds. //! //! @return return on success 0, otherwise error. //! //! @brief Set new timeout values. Function set new timeout values for: //! DHCP lease timeout, ARP refresh timeout, keepalive event //! timeout and socket inactivity timeout //! //! @note If a parameter set to non zero value which is less than 20s, //! it will be set automatically to 20s. //! //***************************************************************************** #ifndef CC3000_TINY_DRIVER extern long netapp_timeout_values(unsigned long *aucDHCP, unsigned long *aucARP, unsigned long *aucKeepalive, unsigned long *aucInactivity); #endif //***************************************************************************** // //! netapp_ping_send //! //! @param ip destination IP address //! @param pingAttempts number of echo requests to send //! @param pingSize send buffer size which may be up to 1400 bytes //! @param pingTimeout Time to wait for a response,in milliseconds. //! //! @return return on success 0, otherwise error. //! //! @brief send ICMP ECHO_REQUEST to network hosts //! //! @note If an operation finished successfully asynchronous ping report //! event will be generated. The report structure is as defined //! by structure netapp_pingreport_args_t. //! //! @warning Calling this function while a previous Ping Requests are in //! progress will stop the previous ping request. //***************************************************************************** #ifndef CC3000_TINY_DRIVER extern long netapp_ping_send(unsigned long *ip, unsigned long ulPingAttempts, unsigned long ulPingSize, unsigned long ulPingTimeout); #endif //***************************************************************************** // //! netapp_ping_stop //! //! @param none //! //! @return On success, zero is returned. On error, -1 is returned. //! //! @brief Stop any ping request. //! //! //***************************************************************************** #ifndef CC3000_TINY_DRIVER extern void netapp_ping_report(); #endif //***************************************************************************** // //! netapp_ping_report //! //! @param none //! //! @return none //! //! @brief Request for ping status. This API triggers the CC3000 to send //! asynchronous events: HCI_EVNT_WLAN_ASYNC_PING_REPORT. //! This event will carry the report structure: //! netapp_pingreport_args_t. This structure is filled in with ping //! results up till point of triggering API. //! netapp_pingreport_args_t:\n packets_sent - echo sent, //! packets_received - echo reply, min_round_time - minimum //! round time, max_round_time - max round time, //! avg_round_time - average round time //! //! @note When a ping operation is not active, the returned structure //! fields are 0. //! //***************************************************************************** #ifndef CC3000_TINY_DRIVER extern long netapp_ping_stop(); #endif //***************************************************************************** // //! netapp_ipconfig //! //! @param[out] ipconfig This argument is a pointer to a //! tNetappIpconfigRetArgs structure. This structure is //! filled in with the network interface configuration. //! tNetappIpconfigRetArgs:\n aucIP - ip address, //! aucSubnetMask - mask, aucDefaultGateway - default //! gateway address, aucDHCPServer - dhcp server address //! aucDNSServer - dns server address, uaMacAddr - mac //! address, uaSSID - connected AP ssid //! //! @return none //! //! @brief Obtain the CC3000 Network interface information. //! Note that the information is available only after the WLAN //! connection was established. Calling this function before //! associated, will cause non-defined values to be returned. //! //! @note The function is useful for figuring out the IP Configuration of //! the device when DHCP is used and for figuring out the SSID of //! the Wireless network the device is associated with. //! //***************************************************************************** extern void netapp_ipconfig( tNetappIpconfigRetArgs * ipconfig ); //***************************************************************************** // //! netapp_arp_flush //! //! @param none //! //! @return none //! //! @brief Flushes ARP table //! //***************************************************************************** #ifndef CC3000_TINY_DRIVER extern long netapp_arp_flush(); #endif //***************************************************************************** // //! netapp_set_debug_level //! //! @param[in] level debug level. Bitwise [0-8], //! 0(disable)or 1(enable).\n Bitwise map: 0 - Critical //! message, 1 information message, 2 - core messages, 3 - //! HCI messages, 4 - Network stack messages, 5 - wlan //! messages, 6 - wlan driver messages, 7 - epprom messages, //! 8 - general messages. Default: 0x13f. Saved: no //! //! @return On success, zero is returned. On error, -1 is returned //! //! @brief Debug messages sent via the UART debug channel, this function //! enable/disable the debug level //! //***************************************************************************** #ifndef CC3000_TINY_DRIVER extern long netapp_set_debug_level(unsigned long ulLevel); #endif //***************************************************************************** // // Close the Doxygen group. //! @} // //***************************************************************************** //***************************************************************************** // // Mark the end of the C bindings section for C++ compilers. // //***************************************************************************** #ifdef __cplusplus } #endif // __cplusplus #endif // __NETAPP_H__
/* * Copyright (C) 2012 Google Inc. All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * THIS SOFTWARE IS PROVIDED BY APPLE INC. AND ITS CONTRIBUTORS ``AS IS'' AND ANY * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL APPLE INC. OR ITS CONTRIBUTORS BE LIABLE FOR ANY * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON * ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #ifndef RTCStatsResponse_h #define RTCStatsResponse_h #include "bindings/core/v8/ScriptWrappable.h" #include "modules/peerconnection/RTCStatsReport.h" #include "platform/heap/Handle.h" #include "platform/peerconnection/RTCStatsResponseBase.h" #include "wtf/HashMap.h" #include "wtf/Vector.h" #include "wtf/text/WTFString.h" namespace blink { class RTCStatsResponse final : public RTCStatsResponseBase, public ScriptWrappable { DEFINE_WRAPPERTYPEINFO(); public: static RTCStatsResponse* create(); const HeapVector<Member<RTCStatsReport>>& result() const { return m_result; } RTCStatsReport* namedItem(const AtomicString& name); size_t addReport(const String& id, const String& type, double timestamp) override; void addStatistic(size_t report, const String& name, const String& value) override; DECLARE_VIRTUAL_TRACE(); private: RTCStatsResponse(); HeapVector<Member<RTCStatsReport>> m_result; HashMap<String, int> m_idmap; }; } // namespace blink #endif // RTCStatsResponse_h
#ifndef _SDO_SAP_STACK_H_ #define _SDO_SAP_STACK_H_ #include <vector> #include <string> #include <map> #include "SapRecord.h" #include "SapServiceInfo.h" using std::string; using std::vector; using std::map; class CSessionManager; class CSapStack { public: static CSapStack *Instance(); void Start(int nThread=3); void Stop(); int LoadConfig(const char* pConfig="config.xml"); int LoadServiceConfig(); int LoadVirtualService(); int LoadAsyncVirtualService(); int LoadAsyncVirtualClientService(); int InstallVirtualService(const string& strName); int UnInstallVirtualService(const string& strName); CSessionManager * GetThread(); void HandleRequest(void *pBuffer, int nLen); void GetThreadStatus(int &nThreads,int &nDeadThread); void GetConnStatus(SConnectData &oData); const string GetPluginInfo(); const string GetConfigInfo(); void SetAllConfig(const void* buffer, const int nLen); void Dump(); bool IsClosed(); private: void Init(int visAuthSoc,int visVerifySocSignature,int visSocEnc,const string &vstrLocalKey); void LoadSos(const vector<SSosStruct> & vecSos); void LoadSuperSoc(const vector<string> & vecSoc,const vector<string> & strPrivelege); int LoadDataServerConfig(map<SComposeKey, vector<unsigned> >& mapDataServerId, const char* pConfig = "DataServer.xml"); private: CSapStack(); static CSapStack * sm_instance; CSessionManager ** ppThreads; int m_nThread; unsigned int m_dwIndex; unsigned int m_minDataServiceId; public: static int isAsc; static int isLocalPrivilege; static int isAuthSoc; static int isVerifySocSignature; static int isSocEnc; static string strLocalKey; static int nLogType; }; #endif
unsigned long long patch_pico = 0x1406833D0ULL; unsigned long long iret_funcs[] = { 0x14014AF67ULL, 0x14014B1ACULL, 0x14014B54BULL, 0x14014B7CFULL, 0x14014BEFFULL, 0x14014C0FFULL, 0x14014C2FFULL, 0x14014C4F7ULL, 0x14014C733ULL, 0x14014D29CULL, 0x14014DC7BULL, 0x14014DF61ULL, 0x14014E314ULL, 0x14014E671ULL, 0x14014E9D1ULL, 0x14014ED31ULL, 0x14014F091ULL, 0x14014F367ULL, 0x14014FE06ULL, 0x140152179ULL, 0x140152CB3ULL, 0x140153280ULL, 0x1401534BFULL, 0x140153EEDULL, 0x1401544A3ULL, 0x14015482DULL, 0x140155663ULL, 0x140155A12ULL, 0x140155CB4ULL }; unsigned long long intr_funcs[] = { 0x14014CFF9ULL, 0x14014DB2EULL, 0x14014DE1EULL, 0x14014E05EULL, 0x14014E3CEULL, 0x14014E72EULL, 0x14014EA8EULL, 0x14014EDEEULL, 0x14014F15EULL, 0x14014FC0DULL, 0x140151F2EULL, 0x14015283DULL, 0x14015293DULL, 0x140152B6CULL, 0x140152EBDULL, 0x140152FBDULL, 0x1401530BDULL, 0x14015333DULL, 0x14015357DULL, 0x140153639ULL, 0x1401536FDULL, 0x1401537B9ULL, 0x140153879ULL, 0x1401539B9ULL, 0x140153AF9ULL, 0x140153BF9ULL, 0x140153FBDULL, 0x140154139ULL, 0x1401542ACULL, 0x1401546BDULL, 0x1401548FDULL, 0x140154AC2ULL, 0x140154BC2ULL, 0x140154CC1ULL, 0x140154E64ULL }; unsigned long long sysret_funcs[] = { 0x14014D470ULL, 0x14015555EULL, 0x140155F21ULL }; unsigned long long syscall_funcs[] = { 0x1401550E4ULL };
//===--- Linking.h - Named declarations and how to link to them -*- C++ -*-===// // // This source file is part of the Swift.org open source project // // Copyright (c) 2014 - 2017 Apple Inc. and the Swift project authors // Licensed under Apache License v2.0 with Runtime Library Exception // // See https://swift.org/LICENSE.txt for license information // See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors // //===----------------------------------------------------------------------===// #ifndef SWIFT_IRGEN_LINKING_H #define SWIFT_IRGEN_LINKING_H #include "swift/AST/Decl.h" #include "swift/AST/ProtocolAssociations.h" #include "swift/AST/ProtocolConformance.h" #include "swift/AST/Types.h" #include "swift/IRGen/ValueWitness.h" #include "swift/SIL/SILFunction.h" #include "swift/SIL/SILGlobalVariable.h" #include "swift/SIL/SILModule.h" #include "llvm/ADT/DenseMapInfo.h" #include "llvm/IR/GlobalValue.h" namespace llvm { class Triple; } namespace swift { namespace irgen { class IRGenModule; /// Determine if the triple uses the DLL storage. bool useDllStorage(const llvm::Triple &triple); class UniversalLinkageInfo { public: bool IsELFObject; bool UseDLLStorage; /// True iff are multiple llvm modules. bool HasMultipleIGMs; bool IsWholeModule; UniversalLinkageInfo(IRGenModule &IGM); UniversalLinkageInfo(const llvm::Triple &triple, bool hasMultipleIGMs, bool isWholeModule); /// In case of multiple llvm modules (in multi-threaded compilation) all /// private decls must be visible from other files. bool shouldAllPrivateDeclsBeVisibleFromOtherFiles() const { return HasMultipleIGMs; } /// In case of multipe llvm modules, private lazy protocol /// witness table accessors could be emitted by two different IGMs during /// IRGen into different object files and the linker would complain about /// duplicate symbols. bool needLinkerToMergeDuplicateSymbols() const { return HasMultipleIGMs; } }; /// Selector for type metadata symbol kinds. enum class TypeMetadataAddress { AddressPoint, FullMetadata, }; /// A link entity is some sort of named declaration, combined with all /// the information necessary to distinguish specific implementations /// of the declaration from each other. /// /// For example, functions may be uncurried at different levels, each of /// which potentially creates a different top-level function. class LinkEntity { /// ValueDecl*, SILFunction*, or TypeBase*, depending on Kind. void *Pointer; /// ProtocolConformance*, depending on Kind. void *SecondaryPointer; /// A hand-rolled bitfield with the following layout: unsigned Data; enum : unsigned { KindShift = 0, KindMask = 0xFF, // This field appears in the ValueWitness kind. ValueWitnessShift = 8, ValueWitnessMask = 0xFF00, // This field appears in the TypeMetadata kind. MetadataAddressShift = 8, MetadataAddressMask = 0x0300, // This field appears in associated type access functions. AssociatedTypeIndexShift = 8, AssociatedTypeIndexMask = ~KindMask, // This field appears in associated conformance access functions. AssociatedConformanceIndexShift = 8, AssociatedConformanceIndexMask = ~KindMask, }; #define LINKENTITY_SET_FIELD(field, value) (value << field##Shift) #define LINKENTITY_GET_FIELD(value, field) ((value & field##Mask) >> field##Shift) enum class Kind { /// A method dispatch thunk. The pointer is a FuncDecl* inside a protocol /// or a class. DispatchThunk, /// A method dispatch thunk for an initializing constructor. The pointer /// is a ConstructorDecl* inside a class. DispatchThunkInitializer, /// A method dispatch thunk for an allocating constructor. The pointer is a /// ConstructorDecl* inside a protocol or a class. DispatchThunkAllocator, /// A field offset. The pointer is a VarDecl*. FieldOffset, /// An Objective-C class reference. The pointer is a ClassDecl*. ObjCClass, /// An Objective-C class reference reference. The pointer is a ClassDecl*. ObjCClassRef, /// An Objective-C metaclass reference. The pointer is a ClassDecl*. ObjCMetaclass, /// A swift metaclass-stub reference. The pointer is a ClassDecl*. SwiftMetaclassStub, /// A class metadata base offset global variable. This stores the offset /// of the immediate members of a class (generic parameters, field offsets, /// vtable offsets) in the class's metadata. The immediate members begin /// immediately after the superclass members end. /// /// The pointer is a ClassDecl*. ClassMetadataBaseOffset, /// The property descriptor for a public property or subscript. /// The pointer is an AbstractStorageDecl*. PropertyDescriptor, /// The nominal type descriptor for a nominal type. /// The pointer is a NominalTypeDecl*. NominalTypeDescriptor, /// The metadata pattern for a generic nominal type. /// The pointer is a NominalTypeDecl*. TypeMetadataPattern, /// The instantiation cache for a generic nominal type. /// The pointer is a NominalTypeDecl*. TypeMetadataInstantiationCache, /// The instantiation function for a generic nominal type. /// The pointer is a NominalTypeDecl*. TypeMetadataInstantiationFunction, /// The completion function for a generic or resilient nominal type. /// The pointer is a NominalTypeDecl*. TypeMetadataCompletionFunction, /// The module descriptor for a module. /// The pointer is a ModuleDecl*. ModuleDescriptor, /// The protocol descriptor for a protocol type. /// The pointer is a ProtocolDecl*. ProtocolDescriptor, /// A SIL function. The pointer is a SILFunction*. SILFunction, /// The descriptor for an extension. /// The pointer is an ExtensionDecl*. ExtensionDescriptor, /// The descriptor for a runtime-anonymous context. /// The pointer is the DeclContext* of a child of the context that should /// be considered private. AnonymousDescriptor, /// A SIL global variable. The pointer is a SILGlobalVariable*. SILGlobalVariable, // These next few are protocol-conformance kinds. /// A direct protocol witness table. The secondary pointer is a /// ProtocolConformance*. DirectProtocolWitnessTable, /// A witness accessor function. The secondary pointer is a /// ProtocolConformance*. ProtocolWitnessTableAccessFunction, /// A generic protocol witness table cache. The secondary pointer is a /// ProtocolConformance*. GenericProtocolWitnessTableCache, /// The instantiation function for a generic protocol witness table. /// The secondary pointer is a ProtocolConformance*. GenericProtocolWitnessTableInstantiationFunction, /// A function which returns the type metadata for the associated type /// of a protocol. The secondary pointer is a ProtocolConformance*. /// The index of the associated type declaration is stored in the data. AssociatedTypeMetadataAccessFunction, /// A function which returns the witness table for a protocol-constrained /// associated type of a protocol. The secondary pointer is a /// ProtocolConformance*. The index of the associated conformance /// requirement is stored in the data. AssociatedTypeWitnessTableAccessFunction, /// A reflection metadata descriptor for the associated type witnesses of a /// nominal type in a protocol conformance. ReflectionAssociatedTypeDescriptor, /// The protocol conformance descriptor for a conformance. /// The pointer is a NormalProtocolConformance*. ProtocolConformanceDescriptor, // These are both type kinds and protocol-conformance kinds. /// A lazy protocol witness accessor function. The pointer is a /// canonical TypeBase*, and the secondary pointer is a /// ProtocolConformance*. ProtocolWitnessTableLazyAccessFunction, /// A lazy protocol witness cache variable. The pointer is a /// canonical TypeBase*, and the secondary pointer is a /// ProtocolConformance*. ProtocolWitnessTableLazyCacheVariable, // Everything following this is a type kind. /// A value witness for a type. /// The pointer is a canonical TypeBase*. ValueWitness, /// The value witness table for a type. /// The pointer is a canonical TypeBase*. ValueWitnessTable, /// The metadata or metadata template for a type. /// The pointer is a canonical TypeBase*. TypeMetadata, /// An access function for type metadata. /// The pointer is a canonical TypeBase*. TypeMetadataAccessFunction, /// A lazy cache variable for type metadata. /// The pointer is a canonical TypeBase*. TypeMetadataLazyCacheVariable, /// A foreign type metadata candidate. /// The pointer is a canonical TypeBase*. ForeignTypeMetadataCandidate, /// A reflection metadata descriptor for a builtin or imported type. ReflectionBuiltinDescriptor, /// A reflection metadata descriptor for a struct, enum, class or protocol. ReflectionFieldDescriptor, /// A coroutine continuation prototype function. CoroutineContinuationPrototype, }; friend struct llvm::DenseMapInfo<LinkEntity>; Kind getKind() const { return Kind(LINKENTITY_GET_FIELD(Data, Kind)); } static bool isDeclKind(Kind k) { return k <= Kind::ProtocolDescriptor; } static bool isTypeKind(Kind k) { return k >= Kind::ProtocolWitnessTableLazyAccessFunction; } static bool isProtocolConformanceKind(Kind k) { return (k >= Kind::DirectProtocolWitnessTable && k <= Kind::ProtocolWitnessTableLazyCacheVariable); } void setForDecl(Kind kind, const ValueDecl *decl) { assert(isDeclKind(kind)); Pointer = const_cast<void*>(static_cast<const void*>(decl)); SecondaryPointer = nullptr; Data = LINKENTITY_SET_FIELD(Kind, unsigned(kind)); } void setForProtocolConformance(Kind kind, const ProtocolConformance *c) { assert(isProtocolConformanceKind(kind) && !isTypeKind(kind)); Pointer = nullptr; SecondaryPointer = const_cast<void*>(static_cast<const void*>(c)); Data = LINKENTITY_SET_FIELD(Kind, unsigned(kind)); } void setForProtocolConformanceAndType(Kind kind, const ProtocolConformance *c, CanType type) { assert(isProtocolConformanceKind(kind) && isTypeKind(kind)); Pointer = type.getPointer(); SecondaryPointer = const_cast<void*>(static_cast<const void*>(c)); Data = LINKENTITY_SET_FIELD(Kind, unsigned(kind)); } void setForProtocolConformanceAndAssociatedType(Kind kind, const ProtocolConformance *c, AssociatedTypeDecl *associate) { assert(isProtocolConformanceKind(kind)); Pointer = nullptr; SecondaryPointer = const_cast<void*>(static_cast<const void*>(c)); Data = LINKENTITY_SET_FIELD(Kind, unsigned(kind)) | LINKENTITY_SET_FIELD(AssociatedTypeIndex, getAssociatedTypeIndex(c, associate)); } void setForProtocolConformanceAndAssociatedConformance(Kind kind, const ProtocolConformance *c, CanType associatedType, ProtocolDecl *associatedProtocol) { assert(isProtocolConformanceKind(kind)); Pointer = associatedProtocol; SecondaryPointer = const_cast<void*>(static_cast<const void*>(c)); Data = LINKENTITY_SET_FIELD(Kind, unsigned(kind)) | LINKENTITY_SET_FIELD(AssociatedConformanceIndex, getAssociatedConformanceIndex(c, associatedType, associatedProtocol)); } // We store associated types using their index in their parent protocol // in order to avoid bloating LinkEntity out to three key pointers. static unsigned getAssociatedTypeIndex(const ProtocolConformance *conformance, AssociatedTypeDecl *associate) { assert(conformance->getProtocol() == associate->getProtocol()); unsigned result = 0; for (auto requirement : associate->getProtocol()->getMembers()) { if (requirement == associate) return result; if (isa<AssociatedTypeDecl>(requirement)) result++; } llvm_unreachable("didn't find associated type in protocol?"); } static AssociatedTypeDecl * getAssociatedTypeByIndex(const ProtocolConformance *conformance, unsigned index) { for (auto requirement : conformance->getProtocol()->getMembers()) { if (auto associate = dyn_cast<AssociatedTypeDecl>(requirement)) { if (index == 0) return associate; index--; } } llvm_unreachable("didn't find associated type in protocol?"); } // We store associated conformances using their index in the requirement // list of the requirement signature of the conformance's protocol. static unsigned getAssociatedConformanceIndex( const ProtocolConformance *conformance, CanType associatedType, ProtocolDecl *requirement) { unsigned index = 0; for (const auto &reqt : conformance->getProtocol()->getRequirementSignature()) { if (reqt.getKind() == RequirementKind::Conformance && reqt.getFirstType()->getCanonicalType() == associatedType && reqt.getSecondType()->castTo<ProtocolType>()->getDecl() == requirement) { return index; } ++index; } llvm_unreachable("requirement not found in protocol"); } static std::pair<CanType, ProtocolDecl*> getAssociatedConformanceByIndex(const ProtocolConformance *conformance, unsigned index) { auto &reqt = conformance->getProtocol()->getRequirementSignature()[index]; assert(reqt.getKind() == RequirementKind::Conformance); return { reqt.getFirstType()->getCanonicalType(), reqt.getSecondType()->castTo<ProtocolType>()->getDecl() }; } void setForType(Kind kind, CanType type) { assert(isTypeKind(kind)); Pointer = type.getPointer(); SecondaryPointer = nullptr; Data = LINKENTITY_SET_FIELD(Kind, unsigned(kind)); } LinkEntity() = default; public: static LinkEntity forDispatchThunk(SILDeclRef declRef) { assert(!declRef.isForeign && !declRef.isDirectReference && !declRef.isCurried); LinkEntity::Kind kind; auto *decl = declRef.getDecl(); assert(isa<ClassDecl>(decl->getDeclContext()) || isa<ProtocolDecl>(decl->getDeclContext())); switch (declRef.kind) { case SILDeclRef::Kind::Func: kind = Kind::DispatchThunk; break; case SILDeclRef::Kind::Initializer: kind = Kind::DispatchThunkInitializer; break; case SILDeclRef::Kind::Allocator: kind = Kind::DispatchThunkAllocator; break; default: llvm_unreachable("Bad SILDeclRef for dispatch thunk"); } LinkEntity entity; entity.setForDecl(kind, decl); return entity; } static LinkEntity forFieldOffset(VarDecl *decl) { LinkEntity entity; entity.setForDecl(Kind::FieldOffset, decl); return entity; } static LinkEntity forObjCClassRef(ClassDecl *decl) { LinkEntity entity; entity.setForDecl(Kind::ObjCClassRef, decl); return entity; } static LinkEntity forObjCClass(ClassDecl *decl) { LinkEntity entity; entity.setForDecl(Kind::ObjCClass, decl); return entity; } static LinkEntity forObjCMetaclass(ClassDecl *decl) { LinkEntity entity; entity.setForDecl(Kind::ObjCMetaclass, decl); return entity; } static LinkEntity forSwiftMetaclassStub(ClassDecl *decl) { LinkEntity entity; entity.setForDecl(Kind::SwiftMetaclassStub, decl); return entity; } static LinkEntity forTypeMetadata(CanType concreteType, TypeMetadataAddress addr) { LinkEntity entity; entity.Pointer = concreteType.getPointer(); entity.SecondaryPointer = nullptr; entity.Data = LINKENTITY_SET_FIELD(Kind, unsigned(Kind::TypeMetadata)) | LINKENTITY_SET_FIELD(MetadataAddress, unsigned(addr)); return entity; } static LinkEntity forTypeMetadataPattern(NominalTypeDecl *decl) { LinkEntity entity; entity.setForDecl(Kind::TypeMetadataPattern, decl); return entity; } static LinkEntity forTypeMetadataAccessFunction(CanType type) { LinkEntity entity; entity.setForType(Kind::TypeMetadataAccessFunction, type); return entity; } static LinkEntity forTypeMetadataInstantiationCache(NominalTypeDecl *decl) { LinkEntity entity; entity.setForDecl(Kind::TypeMetadataInstantiationCache, decl); return entity; } static LinkEntity forTypeMetadataInstantiationFunction(NominalTypeDecl *decl){ LinkEntity entity; entity.setForDecl(Kind::TypeMetadataInstantiationFunction, decl); return entity; } static LinkEntity forTypeMetadataCompletionFunction(NominalTypeDecl *decl) { LinkEntity entity; entity.setForDecl(Kind::TypeMetadataCompletionFunction, decl); return entity; } static LinkEntity forTypeMetadataLazyCacheVariable(CanType type) { LinkEntity entity; entity.setForType(Kind::TypeMetadataLazyCacheVariable, type); return entity; } static LinkEntity forForeignTypeMetadataCandidate(CanType type) { LinkEntity entity; entity.setForType(Kind::ForeignTypeMetadataCandidate, type); return entity; } static LinkEntity forClassMetadataBaseOffset(ClassDecl *decl) { LinkEntity entity; entity.setForDecl(Kind::ClassMetadataBaseOffset, decl); return entity; } static LinkEntity forNominalTypeDescriptor(NominalTypeDecl *decl) { LinkEntity entity; entity.setForDecl(Kind::NominalTypeDescriptor, decl); return entity; } static LinkEntity forPropertyDescriptor(AbstractStorageDecl *decl) { LinkEntity entity; entity.setForDecl(Kind::PropertyDescriptor, decl); return entity; } static LinkEntity forModuleDescriptor(ModuleDecl *decl) { LinkEntity entity; entity.setForDecl(Kind::ModuleDescriptor, decl); return entity; } static LinkEntity forExtensionDescriptor(ExtensionDecl *decl) { LinkEntity entity; entity.Pointer = const_cast<void*>(static_cast<const void*>(decl)); entity.SecondaryPointer = nullptr; entity.Data = LINKENTITY_SET_FIELD(Kind, unsigned(Kind::ExtensionDescriptor)); return entity; } static LinkEntity forAnonymousDescriptor(DeclContext *dc) { LinkEntity entity; entity.Pointer = const_cast<void*>(static_cast<const void*>(dc)); entity.SecondaryPointer = nullptr; entity.Data = LINKENTITY_SET_FIELD(Kind, unsigned(Kind::AnonymousDescriptor)); return entity; } static LinkEntity forProtocolDescriptor(ProtocolDecl *decl) { LinkEntity entity; entity.setForDecl(Kind::ProtocolDescriptor, decl); return entity; } static LinkEntity forValueWitness(CanType concreteType, ValueWitness witness) { LinkEntity entity; entity.Pointer = concreteType.getPointer(); entity.Data = LINKENTITY_SET_FIELD(Kind, unsigned(Kind::ValueWitness)) | LINKENTITY_SET_FIELD(ValueWitness, unsigned(witness)); return entity; } static LinkEntity forValueWitnessTable(CanType type) { LinkEntity entity; entity.setForType(Kind::ValueWitnessTable, type); return entity; } static LinkEntity forSILFunction(SILFunction *F) { LinkEntity entity; entity.Pointer = F; entity.SecondaryPointer = nullptr; entity.Data = LINKENTITY_SET_FIELD(Kind, unsigned(Kind::SILFunction)); return entity; } static LinkEntity forSILGlobalVariable(SILGlobalVariable *G) { LinkEntity entity; entity.Pointer = G; entity.SecondaryPointer = nullptr; entity.Data = LINKENTITY_SET_FIELD(Kind, unsigned(Kind::SILGlobalVariable)); return entity; } static LinkEntity forDirectProtocolWitnessTable(const ProtocolConformance *C) { LinkEntity entity; entity.setForProtocolConformance(Kind::DirectProtocolWitnessTable, C); return entity; } static LinkEntity forProtocolWitnessTableAccessFunction(const ProtocolConformance *C) { LinkEntity entity; entity.setForProtocolConformance(Kind::ProtocolWitnessTableAccessFunction, C); return entity; } static LinkEntity forGenericProtocolWitnessTableCache(const ProtocolConformance *C) { LinkEntity entity; entity.setForProtocolConformance(Kind::GenericProtocolWitnessTableCache, C); return entity; } static LinkEntity forGenericProtocolWitnessTableInstantiationFunction( const ProtocolConformance *C) { LinkEntity entity; entity.setForProtocolConformance( Kind::GenericProtocolWitnessTableInstantiationFunction, C); return entity; } static LinkEntity forProtocolWitnessTableLazyAccessFunction(const ProtocolConformance *C, CanType type) { LinkEntity entity; entity.setForProtocolConformanceAndType( Kind::ProtocolWitnessTableLazyAccessFunction, C, type); return entity; } static LinkEntity forProtocolWitnessTableLazyCacheVariable(const ProtocolConformance *C, CanType type) { LinkEntity entity; entity.setForProtocolConformanceAndType( Kind::ProtocolWitnessTableLazyCacheVariable, C, type); return entity; } static LinkEntity forAssociatedTypeMetadataAccessFunction(const ProtocolConformance *C, AssociatedType association) { LinkEntity entity; entity.setForProtocolConformanceAndAssociatedType( Kind::AssociatedTypeMetadataAccessFunction, C, association.getAssociation()); return entity; } static LinkEntity forAssociatedTypeWitnessTableAccessFunction(const ProtocolConformance *C, const AssociatedConformance &association) { LinkEntity entity; entity.setForProtocolConformanceAndAssociatedConformance( Kind::AssociatedTypeWitnessTableAccessFunction, C, association.getAssociation(), association.getAssociatedRequirement()); return entity; } static LinkEntity forReflectionBuiltinDescriptor(CanType type) { LinkEntity entity; entity.setForType(Kind::ReflectionBuiltinDescriptor, type); return entity; } static LinkEntity forReflectionFieldDescriptor(CanType type) { LinkEntity entity; entity.setForType(Kind::ReflectionFieldDescriptor, type); return entity; } static LinkEntity forReflectionAssociatedTypeDescriptor(const ProtocolConformance *C) { LinkEntity entity; entity.setForProtocolConformance( Kind::ReflectionAssociatedTypeDescriptor, C); return entity; } static LinkEntity forProtocolConformanceDescriptor(const NormalProtocolConformance *C) { LinkEntity entity; entity.setForProtocolConformance( Kind::ProtocolConformanceDescriptor, C); return entity; } static LinkEntity forCoroutineContinuationPrototype(CanSILFunctionType type) { LinkEntity entity; entity.setForType(Kind::CoroutineContinuationPrototype, type); return entity; } void mangle(llvm::raw_ostream &out) const; void mangle(SmallVectorImpl<char> &buffer) const; std::string mangleAsString() const; SILLinkage getLinkage(ForDefinition_t isDefinition) const; /// Returns true if this function or global variable is potentially defined /// in a different module. /// bool isAvailableExternally(IRGenModule &IGM) const; const ValueDecl *getDecl() const { assert(isDeclKind(getKind())); return reinterpret_cast<ValueDecl*>(Pointer); } const ExtensionDecl *getExtension() const { assert(getKind() == Kind::ExtensionDescriptor); return reinterpret_cast<ExtensionDecl*>(Pointer); } const DeclContext *getDeclContext() const { assert(getKind() == Kind::AnonymousDescriptor); return reinterpret_cast<DeclContext*>(Pointer); } SILFunction *getSILFunction() const { assert(getKind() == Kind::SILFunction); return reinterpret_cast<SILFunction*>(Pointer); } SILGlobalVariable *getSILGlobalVariable() const { assert(getKind() == Kind::SILGlobalVariable); return reinterpret_cast<SILGlobalVariable*>(Pointer); } const ProtocolConformance *getProtocolConformance() const { assert(isProtocolConformanceKind(getKind())); return reinterpret_cast<ProtocolConformance*>(SecondaryPointer); } AssociatedTypeDecl *getAssociatedType() const { assert(getKind() == Kind::AssociatedTypeMetadataAccessFunction); return getAssociatedTypeByIndex(getProtocolConformance(), LINKENTITY_GET_FIELD(Data, AssociatedTypeIndex)); } std::pair<CanType, ProtocolDecl *> getAssociatedConformance() const { assert(getKind() == Kind::AssociatedTypeWitnessTableAccessFunction); return getAssociatedConformanceByIndex(getProtocolConformance(), LINKENTITY_GET_FIELD(Data, AssociatedConformanceIndex)); } ProtocolDecl *getAssociatedProtocol() const { assert(getKind() == Kind::AssociatedTypeWitnessTableAccessFunction); return reinterpret_cast<ProtocolDecl*>(Pointer); } bool isValueWitness() const { return getKind() == Kind::ValueWitness; } CanType getType() const { assert(isTypeKind(getKind())); return CanType(reinterpret_cast<TypeBase*>(Pointer)); } ValueWitness getValueWitness() const { assert(getKind() == Kind::ValueWitness); return ValueWitness(LINKENTITY_GET_FIELD(Data, ValueWitness)); } TypeMetadataAddress getMetadataAddress() const { assert(getKind() == Kind::TypeMetadata); return (TypeMetadataAddress)LINKENTITY_GET_FIELD(Data, MetadataAddress); } bool isForeignTypeMetadataCandidate() const { return getKind() == Kind::ForeignTypeMetadataCandidate; } /// Determine whether this entity will be weak-imported. bool isWeakImported(ModuleDecl *module) const { if (getKind() == Kind::SILGlobalVariable && getSILGlobalVariable()->getDecl()) return getSILGlobalVariable()->getDecl()->isWeakImported(module); if (getKind() == Kind::SILFunction) { if (auto clangOwner = getSILFunction()->getClangNodeOwner()) return clangOwner->isWeakImported(module); if (getSILFunction()->isWeakLinked()) return getSILFunction()->isAvailableExternally(); } if (!isDeclKind(getKind())) return false; return getDecl()->isWeakImported(module); } #undef LINKENTITY_GET_FIELD #undef LINKENTITY_SET_FIELD }; /// Encapsulated information about the linkage of an entity. class LinkInfo { LinkInfo() = default; llvm::SmallString<32> Name; llvm::GlobalValue::LinkageTypes Linkage; llvm::GlobalValue::VisibilityTypes Visibility; llvm::GlobalValue::DLLStorageClassTypes DLLStorageClass; ForDefinition_t ForDefinition; public: /// Compute linkage information for the given static LinkInfo get(const UniversalLinkageInfo &linkInfo, ModuleDecl *swiftModule, const LinkEntity &entity, ForDefinition_t forDefinition); static LinkInfo get(IRGenModule &IGM, const LinkEntity &entity, ForDefinition_t forDefinition); static LinkInfo get(const UniversalLinkageInfo &linkInfo, StringRef name, SILLinkage linkage, ForDefinition_t isDefinition, bool isWeakImported); StringRef getName() const { return Name.str(); } llvm::GlobalValue::LinkageTypes getLinkage() const { return Linkage; } llvm::GlobalValue::VisibilityTypes getVisibility() const { return Visibility; } llvm::GlobalValue::DLLStorageClassTypes getDLLStorage() const { return DLLStorageClass; } bool isForDefinition() const { return ForDefinition; } bool isUsed() const { return ForDefinition && isUsed(Linkage, Visibility, DLLStorageClass); } static bool isUsed(llvm::GlobalValue::LinkageTypes Linkage, llvm::GlobalValue::VisibilityTypes Visibility, llvm::GlobalValue::DLLStorageClassTypes DLLStorage); }; } } /// Allow LinkEntity to be used as a key for a DenseMap. template <> struct llvm::DenseMapInfo<swift::irgen::LinkEntity> { typedef swift::irgen::LinkEntity LinkEntity; static LinkEntity getEmptyKey() { LinkEntity entity; entity.Pointer = nullptr; entity.SecondaryPointer = nullptr; entity.Data = 0; return entity; } static LinkEntity getTombstoneKey() { LinkEntity entity; entity.Pointer = nullptr; entity.SecondaryPointer = nullptr; entity.Data = 1; return entity; } static unsigned getHashValue(const LinkEntity &entity) { return DenseMapInfo<void *>::getHashValue(entity.Pointer) ^ DenseMapInfo<void *>::getHashValue(entity.SecondaryPointer) ^ entity.Data; } static bool isEqual(const LinkEntity &LHS, const LinkEntity &RHS) { return LHS.Pointer == RHS.Pointer && LHS.SecondaryPointer == RHS.SecondaryPointer && LHS.Data == RHS.Data; } }; #endif
//////////////////////////////////////////////////////////////////////////// // // Copyright 2014 Realm Inc. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // //////////////////////////////////////////////////////////////////////////// #import <Foundation/Foundation.h> @class RLMObjectSchema, RLMProperty, RLMObjectBase, RLMProperty; #ifdef __cplusplus typedef NSUInteger RLMCreationOptions; #else typedef NS_OPTIONS(NSUInteger, RLMCreationOptions); #endif NS_ASSUME_NONNULL_BEGIN // // Accessors Class Creation/Caching // // get accessor classes for an object class - generates classes if not cached Class RLMAccessorClassForObjectClass(Class objectClass, RLMObjectSchema *schema, NSString *prefix); Class RLMUnmanagedAccessorClassForObjectClass(Class objectClass, RLMObjectSchema *schema); // Check if a given class is a generated accessor class bool RLMIsGeneratedClass(Class cls); // // Dynamic getters/setters // FOUNDATION_EXTERN void RLMDynamicValidatedSet(RLMObjectBase *obj, NSString *propName, id __nullable val); FOUNDATION_EXTERN id __nullable RLMDynamicGet(RLMObjectBase *obj, RLMProperty *prop); FOUNDATION_EXTERN id __nullable RLMDynamicGetByName(RLMObjectBase *obj, NSString *propName, bool asList); // by property/column void RLMDynamicSet(RLMObjectBase *obj, RLMProperty *prop, id val, RLMCreationOptions options); // // Class modification // // Replace className method for the given class void RLMReplaceClassNameMethod(Class accessorClass, NSString *className); // Replace sharedSchema method for the given class void RLMReplaceSharedSchemaMethod(Class accessorClass, RLMObjectSchema * __nullable schema); NS_ASSUME_NONNULL_END
/** \file policy_earliest_arrival_util.c * \brief Helper functions for earliest arrival policy * * \copyright Copyright 2013-2016 Philipp S. Tiesel, Theresa Enghardt, and Mirko Palmer. * All rights reserved. This project is released under the New BSD License. */ #include "policy_earliest_arrival.h" /** Returns the default prefix, if any exists, otherwise NULL */ struct src_prefix_list *get_default_prefix(request_context_t *rctx, GSList *in4_enabled, GSList *in6_enabled, strbuf_t *sb) { GSList *spl = NULL; struct src_prefix_list *cur = NULL; struct eafirst_info *info = NULL; // If address family is specified, only look in its list, else look in both (v4 first) if (rctx->ctx->domain == AF_INET) spl = in4_enabled; else if (rctx->ctx->domain == AF_INET6) spl = in6_enabled; else spl = g_slist_concat(in4_enabled, in6_enabled); // Go through list of src prefixes while (spl != NULL) { // Look at per-prefix policy information cur = spl->data; info = (struct eafirst_info *)cur->policy_info; if (info != NULL && info->is_default) { // This prefix is configured as default. Return it strbuf_printf(sb, "\tFound default prefix "); _muacc_print_sockaddr(sb, cur->if_addrs->addr, cur->if_addrs->addr_len); strbuf_printf(sb, "\n"); return cur; } spl = spl->next; } strbuf_printf(sb, "\tDid not find a default prefix %s%s\n", (rctx->ctx->domain == AF_INET) ? "for IPv4" : "", (rctx->ctx->domain == AF_INET6) ? "for IPv6" : ""); return NULL; }
// BlockFarmland.h // Declares the cBlcokFarmlandHandler representing the block handler for farmland #pragma once #include "BlockHandler.h" #include "../BlockArea.h" class cBlockFarmlandHandler final : public cBlockHandler { using Super = cBlockHandler; public: using Super::Super; private: virtual cItems ConvertToPickups(NIBBLETYPE a_BlockMeta, const cEntity * a_Digger, const cItem * a_Tool) const override { return cItem(E_BLOCK_DIRT, 1, 0); } virtual void OnUpdate( cChunkInterface & a_ChunkInterface, cWorldInterface & a_WorldInterface, cBlockPluginInterface & a_PluginInterface, cChunk & a_Chunk, const Vector3i a_RelPos ) const override { auto BlockMeta = a_Chunk.GetMeta(a_RelPos); if (IsWaterInNear(a_Chunk, a_RelPos)) { // Water was found, set block meta to 7 a_Chunk.FastSetBlock(a_RelPos, m_BlockType, 7); return; } // Water wasn't found, de-hydrate block: if (BlockMeta > 0) { a_Chunk.FastSetBlock(a_RelPos, E_BLOCK_FARMLAND, --BlockMeta); return; } // Farmland too dry. If nothing is growing on top, turn back to dirt: auto UpperBlock = cChunkDef::IsValidHeight(a_RelPos.y + 1) ? a_Chunk.GetBlock(a_RelPos.addedY(1)) : E_BLOCK_AIR; switch (UpperBlock) { case E_BLOCK_BEETROOTS: case E_BLOCK_CROPS: case E_BLOCK_POTATOES: case E_BLOCK_CARROTS: case E_BLOCK_MELON_STEM: case E_BLOCK_PUMPKIN_STEM: { // Produce on top, don't revert break; } default: { a_Chunk.SetBlock(a_RelPos, E_BLOCK_DIRT, 0); break; } } } virtual void OnNeighborChanged(cChunkInterface & a_ChunkInterface, Vector3i a_BlockPos, eBlockFace a_WhichNeighbor) const override { // Don't care about any neighbor but the one above us (fix recursion loop in #2213): if (a_WhichNeighbor != BLOCK_FACE_YP) { return; } // Don't care about anything if we're at the top of the world: if (a_BlockPos.y >= cChunkDef::Height) { return; } // Check whether we should revert to dirt: auto upperBlock = a_ChunkInterface.GetBlock(a_BlockPos.addedY(1)); if (cBlockInfo::FullyOccupiesVoxel(upperBlock)) { a_ChunkInterface.SetBlock(a_BlockPos, E_BLOCK_DIRT, 0); } } /** Returns true if there's either a water source block close enough to hydrate the specified position, or it's raining there. */ static bool IsWaterInNear(const cChunk & a_Chunk, const Vector3i a_RelPos) { const auto WorldPos = a_Chunk.RelativeToAbsolute(a_RelPos); if (a_Chunk.GetWorld()->IsWeatherWetAtXYZ(WorldPos)) { // Rain hydrates farmland, too return true; } // Search for water in a close proximity: // Ref.: https://minecraft.gamepedia.com/Farmland#Hydration // TODO: Rewrite this to use the chunk and its neighbors directly cBlockArea Area; if (!Area.Read(*a_Chunk.GetWorld(), WorldPos - Vector3i(4, 0, 4), WorldPos + Vector3i(4, 1, 4))) { // Too close to the world edge, cannot check surroundings return false; } size_t NumBlocks = Area.GetBlockCount(); BLOCKTYPE * BlockTypes = Area.GetBlockTypes(); for (size_t i = 0; i < NumBlocks; i++) { if (IsBlockWater(BlockTypes[i])) { return true; } } // for i - BlockTypes[] return false; } virtual bool CanSustainPlant(BLOCKTYPE a_Plant) const override { return ( (a_Plant == E_BLOCK_BEETROOTS) || (a_Plant == E_BLOCK_CROPS) || (a_Plant == E_BLOCK_CARROTS) || (a_Plant == E_BLOCK_POTATOES) || (a_Plant == E_BLOCK_MELON_STEM) || (a_Plant == E_BLOCK_PUMPKIN_STEM) ); } } ;
/****************************************************************************** * * * Notepad2 * * Helpers.c * General helper functions * Parts taken from SciTE, (c) Neil Hodgson, http://www.scintilla.org * MinimizeToTray (c) 2000 Matthew Ellis * * See Readme.txt for more information about this source code. * Please send me your comments to this work. * * See License.txt for details about distribution and modification. * * (c) Florian Balmer 1996-2011 * florian.balmer@gmail.com * http://www.flos-freeware.ch * * ******************************************************************************/ #define _WIN32_WINNT 0x501 #include <windows.h> #include <shlobj.h> #include <shlwapi.h> #include <commctrl.h> #include <uxtheme.h> #include <stdio.h> #include <string.h> #include "scintilla.h" #include "helpers.h" #include "resource.h" #include "Extension/Utils.h" extern BOOL fExpandEnvVariables; //============================================================================= // // Manipulation of (cached) ini file sections // int IniSectionGetString( LPCWSTR lpCachedIniSection, LPCWSTR lpName, LPCWSTR lpDefault, LPWSTR lpReturnedString, int cchReturnedString) { WCHAR *p = (WCHAR *)lpCachedIniSection; WCHAR tch[256]; int ich; if (p) { lstrcpy(tch, lpName); lstrcat(tch, L"="); ich = lstrlen(tch); while (*p) { if (StrCmpNI(p, tch, ich) == 0) { lstrcpyn(lpReturnedString, p + ich, cchReturnedString); return (lstrlen(lpReturnedString)); } else p = StrEnd(p) + 1; } } lstrcpyn(lpReturnedString, lpDefault, cchReturnedString); return (lstrlen(lpReturnedString)); } int IniSectionGetInt( LPCWSTR lpCachedIniSection, LPCWSTR lpName, int iDefault) { WCHAR *p = (WCHAR *)lpCachedIniSection; WCHAR tch[256]; int ich; int i; if (p) { lstrcpy(tch, lpName); lstrcat(tch, L"="); ich = lstrlen(tch); while (*p) { if (StrCmpNI(p, tch, ich) == 0) { if (swscanf(p + ich, L"%i", &i) == 1) return (i); else return (iDefault); } else p = StrEnd(p) + 1; } } return (iDefault); } BOOL IniSectionSetString(LPWSTR lpCachedIniSection, LPCWSTR lpName, LPCWSTR lpString) { WCHAR tch[32 + 512 * 3 + 32]; WCHAR *p = lpCachedIniSection; if (p) { while (*p) { p = StrEnd(p) + 1; } wsprintf(tch, L"%s=%s", lpName, lpString); lstrcpy(p, tch); p = StrEnd(p) + 1; *p = 0; return (TRUE); } return (FALSE); } //============================================================================= // // PrivateIsAppThemed() // extern HMODULE hModUxTheme; BOOL PrivateIsAppThemed() { FARPROC pfnIsAppThemed; BOOL bIsAppThemed = FALSE; if (hModUxTheme) { pfnIsAppThemed = GetProcAddress(hModUxTheme, "IsAppThemed"); if (pfnIsAppThemed) bIsAppThemed = (BOOL)pfnIsAppThemed(); } return bIsAppThemed; } //============================================================================= // // PrivateSetCurrentProcessExplicitAppUserModelID() // HRESULT PrivateSetCurrentProcessExplicitAppUserModelID(PCWSTR AppID) { FARPROC pfnSetCurrentProcessExplicitAppUserModelID; if (lstrlen(AppID) == 0) return (S_OK); if (lstrcmpi(AppID, L"(default)") == 0) return (S_OK); pfnSetCurrentProcessExplicitAppUserModelID = GetProcAddress(GetModuleHandleA("shell32.dll"), "SetCurrentProcessExplicitAppUserModelID"); if (pfnSetCurrentProcessExplicitAppUserModelID) return ((HRESULT)pfnSetCurrentProcessExplicitAppUserModelID(AppID)); else return (S_OK); } //============================================================================= // // IsElevated() // BOOL IsElevated() { BOOL bIsElevated = FALSE; HANDLE hToken = NULL; if (!IsVista()) { return (FALSE); } if (OpenProcessToken(GetCurrentProcess(), TOKEN_QUERY, &hToken)) { struct { DWORD TokenIsElevated; } te; DWORD dwReturnLength = 0; if (GetTokenInformation(hToken, 20, &te, sizeof(te), &dwReturnLength)) { if (dwReturnLength == sizeof(te)) bIsElevated = te.TokenIsElevated; } CloseHandle(hToken); } return bIsElevated; } //============================================================================= // // BitmapMergeAlpha() // Merge alpha channel into color channel // BOOL BitmapMergeAlpha(HBITMAP hbmp, COLORREF crDest) { BITMAP bmp; if (GetObject(hbmp, sizeof(BITMAP), &bmp)) { if (bmp.bmBitsPixel == 32) { int x, y; RGBQUAD *prgba = bmp.bmBits; for (y = 0; y < bmp.bmHeight; y++) { for (x = 0; x < bmp.bmWidth; x++) { BYTE alpha = prgba[x].rgbReserved; prgba[x].rgbRed = ((prgba[x].rgbRed * alpha) + (GetRValue(crDest) * (255 - alpha))) >> 8; prgba[x].rgbGreen = ((prgba[x].rgbGreen * alpha) + (GetGValue(crDest) * (255 - alpha))) >> 8; prgba[x].rgbBlue = ((prgba[x].rgbBlue * alpha) + (GetBValue(crDest) * (255 - alpha))) >> 8; prgba[x].rgbReserved = 0xFF; } prgba = (RGBQUAD *)((LPBYTE)prgba + bmp.bmWidthBytes); } return TRUE; } } return FALSE; } //============================================================================= // // BitmapAlphaBlend() // Perform alpha blending to color channel only // BOOL BitmapAlphaBlend(HBITMAP hbmp, COLORREF crDest, BYTE alpha) { BITMAP bmp; if (GetObject(hbmp, sizeof(BITMAP), &bmp)) { if (bmp.bmBitsPixel == 32) { int x, y; RGBQUAD *prgba = bmp.bmBits; for (y = 0; y < bmp.bmHeight; y++) { for (x = 0; x < bmp.bmWidth; x++) { prgba[x].rgbRed = ((prgba[x].rgbRed * alpha) + (GetRValue(crDest) * (255 - alpha))) >> 8; prgba[x].rgbGreen = ((prgba[x].rgbGreen * alpha) + (GetGValue(crDest) * (255 - alpha))) >> 8; prgba[x].rgbBlue = ((prgba[x].rgbBlue * alpha) + (GetBValue(crDest) * (255 - alpha))) >> 8; } prgba = (RGBQUAD *)((LPBYTE)prgba + bmp.bmWidthBytes); } return TRUE; } } return FALSE; } //============================================================================= // // BitmapGrayScale() // Gray scale color channel only // BOOL BitmapGrayScale(HBITMAP hbmp) { BITMAP bmp; if (GetObject(hbmp, sizeof(BITMAP), &bmp)) { if (bmp.bmBitsPixel == 32) { int x, y; RGBQUAD *prgba = bmp.bmBits; for (y = 0; y < bmp.bmHeight; y++) { for (x = 0; x < bmp.bmWidth; x++) { prgba[x].rgbRed = prgba[x].rgbGreen = prgba[x].rgbBlue = (((BYTE)((prgba[x].rgbRed * 38 + prgba[x].rgbGreen * 75 + prgba[x].rgbBlue * 15) >> 7) * 0x80) + (0xD0 * (255 - 0x80))) >> 8; } prgba = (RGBQUAD *)((LPBYTE)prgba + bmp.bmWidthBytes); } return TRUE; } } return FALSE; } //============================================================================= // // VerifyContrast() // Check if two colors can be distinguished // BOOL VerifyContrast(COLORREF cr1, COLORREF cr2) { BYTE r1 = GetRValue(cr1); BYTE g1 = GetGValue(cr1); BYTE b1 = GetBValue(cr1); BYTE r2 = GetRValue(cr2); BYTE g2 = GetGValue(cr2); BYTE b2 = GetBValue(cr2); return ( ((abs((3 * r1 + 5 * g1 + 1 * b1) - (3 * r2 + 6 * g2 + 1 * b2))) >= 400) || ((abs(r1 - r2) + abs(b1 - b2) + abs(g1 - g2)) >= 400)); } //============================================================================= // // IsFontAvailable() // Test if a certain font is installed on the system // int CALLBACK EnumFontsProc(CONST LOGFONT *plf, CONST TEXTMETRIC *ptm, DWORD FontType, LPARAM lParam) { *((PBOOL)lParam) = TRUE; return (FALSE); } BOOL IsFontAvailable(LPCWSTR lpszFontName) { BOOL fFound = FALSE; HDC hDC = GetDC(NULL); EnumFonts(hDC, lpszFontName, EnumFontsProc, (LPARAM)&fFound); ReleaseDC(NULL, hDC); return (fFound); } //============================================================================= // // SetWindowTitle() // BOOL bFreezeAppTitle = FALSE; BOOL SetWindowTitle(HWND hwnd, UINT uIDAppName, BOOL bIsPasteBoard, BOOL bIsElevated, UINT uIDUntitled, LPCWSTR lpszFile, enum EPathNameFormat nPathNameFormat, BOOL bModified, UINT uIDReadOnly, BOOL bReadOnly, LPCWSTR lpszExcerpt) { WCHAR szUntitled[128]; WCHAR szExcrptQuot[256]; WCHAR szExcrptFmt[32]; WCHAR szAppName[128]; WCHAR szElevatedAppName[128]; WCHAR szReadOnly[32]; WCHAR szTitle[512]; static WCHAR szCachedFile[MAX_PATH]; static WCHAR szCachedDisplayName[MAX_PATH]; static const WCHAR *pszSep = L" - "; static const WCHAR *pszMod = L"* "; if (bFreezeAppTitle) return FALSE; if (!GetString(uIDAppName, szAppName, COUNTOF(szAppName)) || !GetString(uIDUntitled, szUntitled, COUNTOF(szUntitled))) return FALSE; // [2e]: Build info #195 if (bIsPasteBoard) { FormatString(szElevatedAppName, COUNTOF(szElevatedAppName), IDS_APPTITLE_PASTEBOARD, szAppName); StrCpyN(szAppName, szElevatedAppName, COUNTOF(szAppName)); } // [/2e] if (bIsElevated) { FormatString(szElevatedAppName, COUNTOF(szElevatedAppName), IDS_APPTITLE_ELEVATED, szAppName); StrCpyN(szAppName, szElevatedAppName, COUNTOF(szAppName)); } if (bModified) lstrcpy(szTitle, pszMod); else lstrcpy(szTitle, L""); if (lstrlen(lpszExcerpt)) { GetString(IDS_TITLEEXCERPT, szExcrptFmt, COUNTOF(szExcrptFmt)); wsprintf(szExcrptQuot, szExcrptFmt, lpszExcerpt); StrCat(szTitle, szExcrptQuot); } else if (lstrlen(lpszFile)) { if (nPathNameFormat < PNM_FULLPATH && !PathIsRoot(lpszFile)) { if (lstrcmp(szCachedFile, lpszFile) != 0) { SHFILEINFO shfi; lstrcpy(szCachedFile, lpszFile); if (SHGetFileInfo2(lpszFile, 0, &shfi, sizeof(SHFILEINFO), SHGFI_DISPLAYNAME)) lstrcpy(szCachedDisplayName, shfi.szDisplayName); else lstrcpy(szCachedDisplayName, PathFindFileName(lpszFile)); } lstrcat(szTitle, szCachedDisplayName); if (nPathNameFormat == PNM_FILENAMEFIRST) { WCHAR tchPath[MAX_PATH]; StrCpyN(tchPath, lpszFile, COUNTOF(tchPath)); PathRemoveFileSpec(tchPath); StrCat(szTitle, L" ["); StrCat(szTitle, tchPath); StrCat(szTitle, L"]"); } } else lstrcat(szTitle, lpszFile); } else { lstrcpy(szCachedFile, L""); lstrcpy(szCachedDisplayName, L""); lstrcat(szTitle, szUntitled); } if (bReadOnly && GetString(uIDReadOnly, szReadOnly, COUNTOF(szReadOnly))) { lstrcat(szTitle, L" "); lstrcat(szTitle, szReadOnly); } lstrcat(szTitle, pszSep); lstrcat(szTitle, szAppName); // [2e]: Language indication #86 switch (iShowLanguageInTitle) { case LIT_HIDE: break; case LIT_SHOW: case LIT_SHOW_NON_US: { WCHAR lang[MAX_PATH]; const HKL hkl = GetKeyboardLayout(0); const int len = GetLocaleInfo((LCID)LOWORD(hkl), LOCALE_SISO639LANGNAME, lang, _countof(lang)-1); for (int i = 0; i < len-1; ++i) { lang[i] = toupper(lang[i]); } if ((iShowLanguageInTitle == LIT_SHOW) || (lstrcmp(lang, L"EN") != 0)) { lstrcat(szTitle, L" ["); lstrcat(szTitle, lang); lstrcat(szTitle, L"]"); } } break; } // [/2e] return SetWindowText(hwnd, szTitle); } //============================================================================= // // SetWindowTransparentMode() // void SetWindowTransparentMode(HWND hwnd, BOOL bTransparentMode) { FARPROC fp; int iAlphaPercent; BYTE bAlpha; if (bTransparentMode) { if (fp = GetProcAddress(GetModuleHandle(L"User32"), "SetLayeredWindowAttributes")) { SetWindowLongPtr(hwnd, GWL_EXSTYLE, GetWindowLongPtr(hwnd, GWL_EXSTYLE) | WS_EX_LAYERED); // get opacity level from registry iAlphaPercent = IniGetInt(L"Settings2", L"OpacityLevel", 75); if (iAlphaPercent < 0 || iAlphaPercent > 100) iAlphaPercent = 75; bAlpha = iAlphaPercent * 255 / 100; fp(hwnd, 0, bAlpha, LWA_ALPHA); } } else SetWindowLongPtr(hwnd, GWL_EXSTYLE, GetWindowLongPtr(hwnd, GWL_EXSTYLE) & ~WS_EX_LAYERED); } //============================================================================= // // CenterDlgInParent() // void CenterDlgInParent(HWND hDlg) { RECT rcDlg; HWND hParent; RECT rcParent; MONITORINFO mi; HMONITOR hMonitor; int xMin, yMin, xMax, yMax, x, y; GetWindowRect(hDlg, &rcDlg); hParent = GetParent(hDlg); GetWindowRect(hParent, &rcParent); hMonitor = MonitorFromRect(&rcParent, MONITOR_DEFAULTTONEAREST); mi.cbSize = sizeof(mi); GetMonitorInfo(hMonitor, &mi); xMin = mi.rcWork.left; yMin = mi.rcWork.top; xMax = (mi.rcWork.right) - (rcDlg.right - rcDlg.left); yMax = (mi.rcWork.bottom) - (rcDlg.bottom - rcDlg.top); if ((rcParent.right - rcParent.left) - (rcDlg.right - rcDlg.left) > 20) x = rcParent.left + (((rcParent.right - rcParent.left) - (rcDlg.right - rcDlg.left)) / 2); else x = rcParent.left + 70; if ((rcParent.bottom - rcParent.top) - (rcDlg.bottom - rcDlg.top) > 20) y = rcParent.top + (((rcParent.bottom - rcParent.top) - (rcDlg.bottom - rcDlg.top)) / 2); else y = rcParent.top + 60; SetWindowPos(hDlg, NULL, max(xMin, min(xMax, x)), max(yMin, min(yMax, y)), 0, 0, SWP_NOZORDER | SWP_NOSIZE); } //============================================================================= // // GetDlgPos() // void GetDlgPos(HWND hDlg, LPINT xDlg, LPINT yDlg) { RECT rcDlg; HWND hParent; RECT rcParent; GetWindowRect(hDlg, &rcDlg); hParent = GetParent(hDlg); GetWindowRect(hParent, &rcParent); // return positions relative to parent window *xDlg = rcDlg.left - rcParent.left; *yDlg = rcDlg.top - rcParent.top; } //============================================================================= // // SetDlgPos() // void SetDlgPos(HWND hDlg, int xDlg, int yDlg) { RECT rcDlg; HWND hParent; RECT rcParent; MONITORINFO mi; HMONITOR hMonitor; int xMin, yMin, xMax, yMax, x, y; GetWindowRect(hDlg, &rcDlg); hParent = GetParent(hDlg); GetWindowRect(hParent, &rcParent); hMonitor = MonitorFromRect(&rcParent, MONITOR_DEFAULTTONEAREST); mi.cbSize = sizeof(mi); GetMonitorInfo(hMonitor, &mi); xMin = mi.rcWork.left; yMin = mi.rcWork.top; xMax = (mi.rcWork.right) - (rcDlg.right - rcDlg.left); yMax = (mi.rcWork.bottom) - (rcDlg.bottom - rcDlg.top); // desired positions relative to parent window x = rcParent.left + xDlg; y = rcParent.top + yDlg; SetWindowPos(hDlg, NULL, max(xMin, min(xMax, x)), max(yMin, min(yMax, y)), 0, 0, SWP_NOZORDER | SWP_NOSIZE); } //============================================================================= // // Resize Dialog Helpers() // typedef struct _resizedlg { int cxClient; int cyClient; int cxFrame; int cyFrame; int mmiPtMinX; int mmiPtMinY; } RESIZEDLG, *PRESIZEDLG; void ResizeDlg_Init(HWND hwnd, int cxFrame, int cyFrame, int nIdGrip) { RECT rc; WCHAR wch[64]; int cGrip; RESIZEDLG *pm = LocalAlloc(LPTR, sizeof(RESIZEDLG)); GetClientRect(hwnd, &rc); pm->cxClient = rc.right - rc.left; pm->cyClient = rc.bottom - rc.top; pm->cxFrame = cxFrame; pm->cyFrame = cyFrame; AdjustWindowRectEx(&rc, GetWindowLong(hwnd, GWL_STYLE) | WS_THICKFRAME, FALSE, 0); pm->mmiPtMinX = rc.right - rc.left; pm->mmiPtMinY = rc.bottom - rc.top; if (pm->cxFrame < (rc.right - rc.left)) pm->cxFrame = rc.right - rc.left; if (pm->cyFrame < (rc.bottom - rc.top)) pm->cyFrame = rc.bottom - rc.top; SetProp(hwnd, L"ResizeDlg", (HANDLE)pm); SetWindowPos(hwnd, NULL, rc.left, rc.top, pm->cxFrame, pm->cyFrame, SWP_NOZORDER); SetWindowLongPtr(hwnd, GWL_STYLE, GetWindowLongPtr(hwnd, GWL_STYLE) | WS_THICKFRAME); SetWindowPos(hwnd, NULL, 0, 0, 0, 0, SWP_NOZORDER | SWP_NOMOVE | SWP_NOSIZE | SWP_FRAMECHANGED); GetMenuString(GetSystemMenu(GetParent(hwnd), FALSE), SC_SIZE, wch, COUNTOF(wch), MF_BYCOMMAND); InsertMenu(GetSystemMenu(hwnd, FALSE), SC_CLOSE, MF_BYCOMMAND | MF_STRING | MF_ENABLED, SC_SIZE, wch); InsertMenu(GetSystemMenu(hwnd, FALSE), SC_CLOSE, MF_BYCOMMAND | MF_SEPARATOR, 0, NULL); SetWindowLongPtr(GetDlgItem(hwnd, nIdGrip), GWL_STYLE, GetWindowLongPtr(GetDlgItem(hwnd, nIdGrip), GWL_STYLE) | SBS_SIZEGRIP | WS_CLIPSIBLINGS); cGrip = GetSystemMetrics(SM_CXHTHUMB); SetWindowPos(GetDlgItem(hwnd, nIdGrip), NULL, pm->cxClient - cGrip, pm->cyClient - cGrip, cGrip, cGrip, SWP_NOZORDER); } void ResizeDlg_Destroy(HWND hwnd, int *cxFrame, int *cyFrame) { RECT rc; PRESIZEDLG pm = GetProp(hwnd, L"ResizeDlg"); GetWindowRect(hwnd, &rc); *cxFrame = rc.right - rc.left; *cyFrame = rc.bottom - rc.top; RemoveProp(hwnd, L"ResizeDlg"); LocalFree(pm); } void ResizeDlg_Size(HWND hwnd, LPARAM lParam, int *cx, int *cy) { PRESIZEDLG pm = GetProp(hwnd, L"ResizeDlg"); *cx = LOWORD(lParam) - pm->cxClient; *cy = HIWORD(lParam) - pm->cyClient; pm->cxClient = LOWORD(lParam); pm->cyClient = HIWORD(lParam); } void ResizeDlg_GetMinMaxInfo(HWND hwnd, LPARAM lParam) { PRESIZEDLG pm = GetProp(hwnd, L"ResizeDlg"); LPMINMAXINFO lpmmi = (LPMINMAXINFO)lParam; lpmmi->ptMinTrackSize.x = pm->mmiPtMinX; lpmmi->ptMinTrackSize.y = pm->mmiPtMinY; } HDWP DeferCtlPos(HDWP hdwp, HWND hwndDlg, int nCtlId, int dx, int dy, UINT uFlags) { RECT rc; HWND hwndCtl = GetDlgItem(hwndDlg, nCtlId); GetWindowRect(hwndCtl, &rc); MapWindowPoints(NULL, hwndDlg, (LPPOINT)&rc, 2); if (uFlags & SWP_NOSIZE) return (DeferWindowPos(hdwp, hwndCtl, NULL, rc.left + dx, rc.top + dy, 0, 0, SWP_NOZORDER | SWP_NOSIZE)); else return (DeferWindowPos(hdwp, hwndCtl, NULL, 0, 0, rc.right - rc.left + dx, rc.bottom - rc.top + dy, SWP_NOZORDER | SWP_NOMOVE)); } //============================================================================= // // MakeBitmapButton() // void MakeBitmapButton(HWND hwnd, int nCtlId, HINSTANCE hInstance, UINT uBmpId) { HWND hwndCtl = GetDlgItem(hwnd, nCtlId); BITMAP bmp; BUTTON_IMAGELIST bi; HBITMAP hBmp = LoadImage(hInstance, MAKEINTRESOURCE(uBmpId), IMAGE_BITMAP, 0, 0, LR_CREATEDIBSECTION); GetObject(hBmp, sizeof(BITMAP), &bmp); bi.himl = ImageList_Create(bmp.bmWidth, bmp.bmHeight, ILC_COLOR32 | ILC_MASK, 1, 0); ImageList_AddMasked(bi.himl, hBmp, CLR_DEFAULT); DeleteObject(hBmp); SetRect(&bi.margin, 0, 0, 0, 0); bi.uAlign = BUTTON_IMAGELIST_ALIGN_CENTER; SendMessage(hwndCtl, BCM_SETIMAGELIST, 0, (LPARAM)&bi); } //============================================================================= // // MakeColorPickButton() // void MakeColorPickButton(HWND hwnd, int nCtlId, HINSTANCE hInstance, COLORREF crColor) { HWND hwndCtl = GetDlgItem(hwnd, nCtlId); BUTTON_IMAGELIST bi; HIMAGELIST himlOld = NULL; HBITMAP hBmp; COLORMAP colormap[2]; if (SendMessage(hwndCtl, BCM_GETIMAGELIST, 0, (LPARAM)&bi)) himlOld = bi.himl; if (IsWindowEnabled(hwndCtl) && crColor != -1) { colormap[0].from = RGB(0x00, 0x00, 0x00); colormap[0].to = GetSysColor(COLOR_3DSHADOW); } else { colormap[0].from = RGB(0x00, 0x00, 0x00); colormap[0].to = RGB(0xFF, 0xFF, 0xFF); } if (IsWindowEnabled(hwndCtl) && crColor != -1) { if (crColor == RGB(0xFF, 0xFF, 0xFF)) crColor = RGB(0xFF, 0xFF, 0xFE); colormap[1].from = RGB(0xFF, 0xFF, 0xFF); colormap[1].to = crColor; } else { colormap[1].from = RGB(0xFF, 0xFF, 0xFF); colormap[1].to = RGB(0xFF, 0xFF, 0xFF); } hBmp = CreateMappedBitmap(hInstance, IDB_PICK, 0, colormap, 2); bi.himl = ImageList_Create(10, 10, ILC_COLORDDB | ILC_MASK, 1, 0); ImageList_AddMasked(bi.himl, hBmp, RGB(0xFF, 0xFF, 0xFF)); DeleteObject(hBmp); SetRect(&bi.margin, 0, 0, 4, 0); bi.uAlign = BUTTON_IMAGELIST_ALIGN_RIGHT; SendMessage(hwndCtl, BCM_SETIMAGELIST, 0, (LPARAM)&bi); InvalidateRect(hwndCtl, NULL, TRUE); if (himlOld) ImageList_Destroy(himlOld); } //============================================================================= // // DeleteBitmapButton() // void DeleteBitmapButton(HWND hwnd, int nCtlId) { HWND hwndCtl = GetDlgItem(hwnd, nCtlId); BUTTON_IMAGELIST bi; if (SendMessage(hwndCtl, BCM_GETIMAGELIST, 0, (LPARAM)&bi)) ImageList_Destroy(bi.himl); } //============================================================================= // // StatusSetText() // BOOL StatusSetText(HWND hwnd, UINT nPart, LPCWSTR lpszText) { UINT uFlags = (nPart == 255) ? nPart | SBT_NOBORDERS : nPart; return (BOOL)SendMessage(hwnd, SB_SETTEXT, uFlags, (LPARAM)lpszText); } //============================================================================= // // SendWMSize() // LRESULT SendWMSize(HWND hwnd) { RECT rc; GetClientRect(hwnd, &rc); return (SendMessage(hwnd, WM_SIZE, SIZE_RESTORED, MAKELPARAM(rc.right, rc.bottom))); } //============================================================================= // // StatusSetTextID() // BOOL StatusSetTextID(HWND hwnd, UINT nPart, UINT uID) { WCHAR szText[256]; UINT uFlags = (nPart == 255) ? nPart | SBT_NOBORDERS : nPart; if (!uID) { SendMessage(hwnd, SB_SETTEXT, uFlags, 0); return TRUE; } if (!GetString(uID, szText, 256)) return FALSE; return (BOOL)SendMessage(hwnd, SB_SETTEXT, uFlags, (LPARAM)szText); } //============================================================================= // // StatusCalcPaneWidth() // int StatusCalcPaneWidth(HWND hwnd, LPCWSTR lpsz) { SIZE size; HDC hdc = GetDC(hwnd); HFONT hfont = (HFONT)SendMessage(hwnd, WM_GETFONT, 0, 0); HFONT hfold = SelectObject(hdc, hfont); int mmode = SetMapMode(hdc, MM_TEXT); GetTextExtentPoint32(hdc, lpsz, lstrlen(lpsz), &size); SetMapMode(hdc, mmode); SelectObject(hdc, hfold); ReleaseDC(hwnd, hdc); return (size.cx + 9); } //============================================================================= // // Toolbar_Get/SetButtons() // int Toolbar_GetButtons(HWND hwnd, int cmdBase, LPWSTR lpszButtons, int cchButtons) { WCHAR tchButtons[512]; WCHAR tchItem[32]; int i, c; TBBUTTON tbb; lstrcpy(tchButtons, L""); c = min(50, (int)SendMessage(hwnd, TB_BUTTONCOUNT, 0, 0)); for (i = 0; i < c; i++) { SendMessage(hwnd, TB_GETBUTTON, (WPARAM)i, (LPARAM)&tbb); wsprintf(tchItem, L"%i ", (tbb.idCommand == 0) ? 0 : tbb.idCommand - cmdBase + 1); lstrcat(tchButtons, tchItem); } TrimString(tchButtons); lstrcpyn(lpszButtons, tchButtons, cchButtons); return (c); } int Toolbar_SetButtons(HWND hwnd, int cmdBase, LPCWSTR lpszButtons, LPCTBBUTTON ptbb, int ctbb) { WCHAR tchButtons[512]; WCHAR *p; int i, c; int iCmd; ZeroMemory(tchButtons, COUNTOF(tchButtons) * sizeof(tchButtons[0])); lstrcpyn(tchButtons, lpszButtons, COUNTOF(tchButtons) - 2); TrimString(tchButtons); while (p = StrStr(tchButtons, L" ")) MoveMemory((WCHAR *)p, (WCHAR *)p + 1, (lstrlen(p) + 1) * sizeof(WCHAR)); c = (int)SendMessage(hwnd, TB_BUTTONCOUNT, 0, 0); for (i = 0; i < c; i++) SendMessage(hwnd, TB_DELETEBUTTON, 0, 0); for (i = 0; i < COUNTOF(tchButtons); i++) if (tchButtons[i] == L' ') tchButtons[i] = 0; p = tchButtons; while (*p) { if (swscanf(p, L"%i", &iCmd) == 1) { iCmd = (iCmd == 0) ? 0 : iCmd + cmdBase - 1; for (i = 0; i < ctbb; i++) { if (ptbb[i].idCommand == iCmd) { SendMessage(hwnd, TB_ADDBUTTONS, (WPARAM)1, (LPARAM)&ptbb[i]); break; } } } p = StrEnd(p) + 1; } return ((int)SendMessage(hwnd, TB_BUTTONCOUNT, 0, 0)); } //============================================================================= // // IsCmdEnabled() // BOOL IsCmdEnabled(HWND hwnd, UINT uId) { HMENU hmenu; UINT ustate; hmenu = GetMenu(hwnd); SendMessage(hwnd, WM_INITMENU, (WPARAM)hmenu, 0); ustate = GetMenuState(hmenu, uId, MF_BYCOMMAND); if (ustate == 0xFFFFFFFF) return TRUE; else return (!(ustate & (MF_GRAYED | MF_DISABLED))); } //============================================================================= // // FormatString() // int FormatString(LPWSTR lpOutput, int nOutput, UINT uIdFormat, ...) { va_list arguments; va_start(arguments, uIdFormat); WCHAR *p = LocalAlloc(LPTR, sizeof(WCHAR) * nOutput); if (GetString(uIdFormat, p, nOutput)) { // [2e]: "Evaluate selection"-feature, use vswprintf to support floating-point type specifiers vswprintf(lpOutput, nOutput, p, arguments); } va_end(arguments); LocalFree(p); return lstrlen(lpOutput); } //============================================================================= // // PathRelativeToApp() // void PathRelativeToApp( LPWSTR lpszSrc, LPWSTR lpszDest, int cchDest, BOOL bSrcIsFile, BOOL bUnexpandEnv, BOOL bUnexpandMyDocs) { WCHAR wchAppPath[MAX_PATH]; WCHAR wchWinDir[MAX_PATH]; WCHAR wchUserFiles[MAX_PATH]; WCHAR wchPath[MAX_PATH]; WCHAR wchResult[MAX_PATH]; DWORD dwAttrTo = (bSrcIsFile) ? 0 : FILE_ATTRIBUTE_DIRECTORY; GetModuleFileName(NULL, wchAppPath, COUNTOF(wchAppPath)); PathRemoveFileSpec(wchAppPath); GetWindowsDirectory(wchWinDir, COUNTOF(wchWinDir)); SHGetFolderPath(NULL, CSIDL_PERSONAL, NULL, SHGFP_TYPE_CURRENT, wchUserFiles); if (bUnexpandMyDocs && !PathIsRelative(lpszSrc) && !PathIsPrefix(wchUserFiles, wchAppPath) && PathIsPrefix(wchUserFiles, lpszSrc) && PathRelativePathTo(wchPath, wchUserFiles, FILE_ATTRIBUTE_DIRECTORY, lpszSrc, dwAttrTo)) { lstrcpy(wchUserFiles, L"%CSIDL:MYDOCUMENTS%"); PathAppend(wchUserFiles, wchPath); lstrcpy(wchPath, wchUserFiles); } else if (PathIsRelative(lpszSrc) || PathCommonPrefix(wchAppPath, wchWinDir, NULL)) lstrcpyn(wchPath, lpszSrc, COUNTOF(wchPath)); else { if (!PathRelativePathTo(wchPath, wchAppPath, FILE_ATTRIBUTE_DIRECTORY, lpszSrc, dwAttrTo)) lstrcpyn(wchPath, lpszSrc, COUNTOF(wchPath)); } // [2e]: Don't interpret %envvars% in pathname when opening file #193 if (bUnexpandEnv && fExpandEnvVariables) { if (!PathUnExpandEnvStrings(wchPath, wchResult, COUNTOF(wchResult))) lstrcpyn(wchResult, wchPath, COUNTOF(wchResult)); } else lstrcpyn(wchResult, wchPath, COUNTOF(wchResult)); if (lpszDest == NULL || lpszSrc == lpszDest) lstrcpyn(lpszSrc, wchResult, (cchDest == 0) ? MAX_PATH : cchDest); else lstrcpyn(lpszDest, wchResult, (cchDest == 0) ? MAX_PATH : cchDest); } //============================================================================= // // PathAbsoluteFromApp() // void PathAbsoluteFromApp(LPWSTR lpszSrc, LPWSTR lpszDest, int cchDest, BOOL bExpandEnv) { WCHAR wchPath[MAX_PATH]; WCHAR wchResult[MAX_PATH]; if (StrCmpNI(lpszSrc, L"%CSIDL:MYDOCUMENTS%", CSTRLEN("%CSIDL:MYDOCUMENTS%")) == 0) { SHGetFolderPath(NULL, CSIDL_PERSONAL, NULL, SHGFP_TYPE_CURRENT, wchPath); PathAppend(wchPath, lpszSrc + CSTRLEN("%CSIDL:MYDOCUMENTS%")); } else lstrcpyn(wchPath, lpszSrc, COUNTOF(wchPath)); if (bExpandEnv) ExpandEnvironmentStringsEx(wchPath, COUNTOF(wchPath)); if (PathIsRelative(wchPath)) { GetModuleFileName(NULL, wchResult, COUNTOF(wchResult)); PathRemoveFileSpec(wchResult); PathAppend(wchResult, wchPath); } else lstrcpyn(wchResult, wchPath, COUNTOF(wchResult)); PathCanonicalizeEx(wchResult); if (PathGetDriveNumber(wchResult) != -1) CharUpperBuff(wchResult, 1); if (lpszDest == NULL || lpszSrc == lpszDest) lstrcpyn(lpszSrc, wchResult, (cchDest == 0) ? MAX_PATH : cchDest); else lstrcpyn(lpszDest, wchResult, (cchDest == 0) ? MAX_PATH : cchDest); } /////////////////////////////////////////////////////////////////////////////// // // // Name: PathIsLnkFile() // // Purpose: Determine whether pszPath is a Windows Shell Link File by // comparing the filename extension with L".lnk" // // Manipulates: // BOOL PathIsLnkFile(LPCWSTR pszPath) { WCHAR tchResPath[256]; if (!pszPath || !*pszPath) return FALSE; if (lstrcmpi(PathFindExtension(pszPath), L".lnk")) return FALSE; else return PathGetLnkPath(pszPath, tchResPath, COUNTOF(tchResPath)); } /////////////////////////////////////////////////////////////////////////////// // // // Name: PathGetLnkPath() // // Purpose: Try to get the path to which a lnk-file is linked // // // Manipulates: pszResPath // BOOL PathGetLnkPath(LPCWSTR pszLnkFile, LPWSTR pszResPath, int cchResPath) { IShellLink *psl; WIN32_FIND_DATA fd; BOOL bSucceeded = FALSE; if (SUCCEEDED(CoCreateInstance(&CLSID_ShellLink, NULL, CLSCTX_INPROC_SERVER, &IID_IShellLink, &psl))) { IPersistFile *ppf; if (SUCCEEDED(psl->lpVtbl->QueryInterface(psl, &IID_IPersistFile, &ppf))) { WORD wsz[MAX_PATH]; lstrcpy(wsz, pszLnkFile); if (SUCCEEDED(ppf->lpVtbl->Load(ppf, wsz, STGM_READ))) { if (NOERROR == psl->lpVtbl->GetPath(psl, pszResPath, cchResPath, &fd, 0)) bSucceeded = TRUE; } ppf->lpVtbl->Release(ppf); } psl->lpVtbl->Release(psl); } // This additional check seems reasonable if (!lstrlen(pszResPath)) bSucceeded = FALSE; if (bSucceeded) { ExpandEnvironmentStringsEx(pszResPath, cchResPath); PathCanonicalizeEx(pszResPath); } return (bSucceeded); } /////////////////////////////////////////////////////////////////////////////// // // // Name: PathIsLnkToDirectory() // // Purpose: Determine whether pszPath is a Windows Shell Link File which // refers to a directory // // Manipulates: pszResPath // BOOL PathIsLnkToDirectory(LPCWSTR pszPath, LPWSTR pszResPath, int cchResPath) { WCHAR tchResPath[MAX_PATH]; if (PathIsLnkFile(pszPath)) { if (PathGetLnkPath(pszPath, tchResPath, sizeof(WCHAR) *COUNTOF(tchResPath))) { if (PathIsDirectory(tchResPath)) { lstrcpyn(pszResPath, tchResPath, cchResPath); return (TRUE); } else return FALSE; } else return FALSE; } else return FALSE; } /////////////////////////////////////////////////////////////////////////////// // // // Name: PathCreateDeskLnk() // // Purpose: Modified to create a desktop link to Notepad2 // // Manipulates: // BOOL PathCreateDeskLnk(LPCWSTR pszDocument) { WCHAR tchExeFile[MAX_PATH]; WCHAR tchDocTemp[MAX_PATH]; WCHAR tchArguments[MAX_PATH + 16]; WCHAR tchLinkDir[MAX_PATH]; WCHAR tchDescription[64]; WCHAR tchLnkFileName[MAX_PATH]; IShellLink *psl; BOOL bSucceeded = FALSE; BOOL fMustCopy; if (!pszDocument || lstrlen(pszDocument) == 0) return TRUE; // init strings GetModuleFileName(NULL, tchExeFile, COUNTOF(tchExeFile)); lstrcpy(tchDocTemp, pszDocument); PathQuoteSpaces(tchDocTemp); lstrcpy(tchArguments, L"-n "); lstrcat(tchArguments, tchDocTemp); SHGetSpecialFolderPath(NULL, tchLinkDir, CSIDL_DESKTOPDIRECTORY, TRUE); GetString(IDS_LINKDESCRIPTION, tchDescription, COUNTOF(tchDescription)); // Try to construct a valid filename... if (!SHGetNewLinkInfo(pszDocument, tchLinkDir, tchLnkFileName, &fMustCopy, SHGNLI_PREFIXNAME)) return (FALSE); if (SUCCEEDED(CoCreateInstance(&CLSID_ShellLink, NULL, CLSCTX_INPROC_SERVER, &IID_IShellLink, &psl))) { IPersistFile *ppf; if (SUCCEEDED(psl->lpVtbl->QueryInterface(psl, &IID_IPersistFile, &ppf))) { WORD wsz[MAX_PATH]; lstrcpy(wsz, tchLnkFileName); psl->lpVtbl->SetPath(psl, tchExeFile); psl->lpVtbl->SetArguments(psl, tchArguments); psl->lpVtbl->SetDescription(psl, tchDescription); if (SUCCEEDED(ppf->lpVtbl->Save(ppf, wsz, TRUE))) bSucceeded = TRUE; ppf->lpVtbl->Release(ppf); } psl->lpVtbl->Release(psl); } return (bSucceeded); } /////////////////////////////////////////////////////////////////////////////// // // // Name: PathCreateFavLnk() // // Purpose: Modified to create a Notepad2 favorites link // // Manipulates: // BOOL PathCreateFavLnk(LPCWSTR pszName, LPCWSTR pszTarget, LPCWSTR pszDir) { WCHAR tchLnkFileName[MAX_PATH]; IShellLink *psl; BOOL bSucceeded = FALSE; if (!pszName || lstrlen(pszName) == 0) return TRUE; lstrcpy(tchLnkFileName, pszDir); PathAppend(tchLnkFileName, pszName); lstrcat(tchLnkFileName, L".lnk"); if (PathFileExists(tchLnkFileName)) return FALSE; if (SUCCEEDED(CoCreateInstance(&CLSID_ShellLink, NULL, CLSCTX_INPROC_SERVER, &IID_IShellLink, &psl))) { IPersistFile *ppf; if (SUCCEEDED(psl->lpVtbl->QueryInterface(psl, &IID_IPersistFile, &ppf))) { WORD wsz[MAX_PATH]; lstrcpy(wsz, tchLnkFileName); psl->lpVtbl->SetPath(psl, pszTarget); if (SUCCEEDED(ppf->lpVtbl->Save(ppf, wsz, TRUE))) bSucceeded = TRUE; ppf->lpVtbl->Release(ppf); } psl->lpVtbl->Release(psl); } return (bSucceeded); } //============================================================================= // // StrLTrim() // BOOL StrLTrim(LPWSTR pszSource, LPCWSTR pszTrimChars) { LPWSTR psz; if (!pszSource || !*pszSource) return FALSE; psz = pszSource; while (StrChrI(pszTrimChars, *psz)) psz++; MoveMemory(pszSource, psz, sizeof(WCHAR) * (lstrlen(psz) + 1)); return TRUE; } //============================================================================= // // TrimString() // BOOL TrimString(LPWSTR lpString) { LPWSTR psz; if (!lpString || !*lpString) return FALSE; // Trim left psz = lpString; while (*psz == L' ') psz = CharNext(psz); MoveMemory(lpString, psz, sizeof(WCHAR) * (lstrlen(psz) + 1)); // Trim right psz = StrEnd(lpString); while (*(psz = CharPrev(lpString, psz)) == L' ') *psz = L'\0'; return TRUE; } //============================================================================= // // ExtractFirstArgument() // BOOL ExtractFirstArgument(LPCWSTR lpArgs, LPWSTR lpArg1, LPWSTR lpArg2) { LPWSTR psz; BOOL bQuoted = FALSE; lstrcpy(lpArg1, lpArgs); if (lpArg2) *lpArg2 = L'\0'; if (!TrimString(lpArg1)) return FALSE; if (*lpArg1 == L'\"') { *lpArg1 = L' '; TrimString(lpArg1); bQuoted = TRUE; } if (bQuoted) psz = StrChr(lpArg1, L'\"'); else psz = StrChr(lpArg1, L' '); if (psz) { *psz = L'\0'; if (lpArg2) lstrcpy(lpArg2, psz + 1); } TrimString(lpArg1); if (lpArg2) TrimString(lpArg2); return TRUE; } //============================================================================= // // PrepareFilterStr() // void PrepareFilterStr(LPWSTR lpFilter) { LPWSTR psz = StrEnd(lpFilter); while (psz != lpFilter) { if (*(psz = CharPrev(lpFilter, psz)) == L'|') *psz = L'\0'; } } //============================================================================= // // StrTab2Space() - in place conversion // void StrTab2Space(LPWSTR lpsz) { WCHAR *c = lpsz; while (c = StrChr(lpsz, L'\t')) *c = L' '; } //============================================================================= // // PathFixBackslashes() - in place conversion // void PathFixBackslashes(LPWSTR lpsz) { WCHAR *c = lpsz; while (c = StrChr(c, L'/')) { if (*CharPrev(lpsz, c) == L':' && *CharNext(c) == L'/') c += 2; else *c = L'\\'; } } //============================================================================= // // ExpandEnvironmentStringsEx() // // Adjusted for Windows 95 // void ExpandEnvironmentStringsEx(LPWSTR lpSrc, DWORD dwSrc) { WCHAR szBuf[312]; // [2e]: Don't interpret %envvars% in pathname when opening file #193 if (fExpandEnvVariables && ExpandEnvironmentStrings(lpSrc, szBuf, COUNTOF(szBuf))) lstrcpyn(lpSrc, szBuf, dwSrc); } //============================================================================= // // PathCanonicalizeEx() // // void PathCanonicalizeEx(LPWSTR lpSrc) { WCHAR szDst[MAX_PATH]; if (PathCanonicalize(szDst, lpSrc)) lstrcpy(lpSrc, szDst); } //============================================================================= // // GetLongPathNameEx() // // DWORD GetLongPathNameEx(LPWSTR lpszPath, DWORD cchBuffer) { DWORD dwRet = GetLongPathName(lpszPath, lpszPath, cchBuffer); if (dwRet) { if (PathGetDriveNumber(lpszPath) != -1) CharUpperBuff(lpszPath, 1); return (dwRet); } return (0); } //============================================================================= // // SHGetFileInfo2() // // Return a default name when the file has been removed, and always append // a filename extension // DWORD_PTR SHGetFileInfo2(LPCWSTR pszPath, DWORD dwFileAttributes, SHFILEINFO *psfi, UINT cbFileInfo, UINT uFlags) { if (PathFileExists(pszPath)) { DWORD_PTR dw = SHGetFileInfo(pszPath, dwFileAttributes, psfi, cbFileInfo, uFlags); if (lstrlen(psfi->szDisplayName) < lstrlen(PathFindFileName(pszPath))) StrCatBuff(psfi->szDisplayName, PathFindExtension(pszPath), COUNTOF(psfi->szDisplayName)); return (dw); } else { DWORD_PTR dw = SHGetFileInfo(pszPath, FILE_ATTRIBUTE_NORMAL, psfi, cbFileInfo, uFlags | SHGFI_USEFILEATTRIBUTES); if (lstrlen(psfi->szDisplayName) < lstrlen(PathFindFileName(pszPath))) StrCatBuff(psfi->szDisplayName, PathFindExtension(pszPath), COUNTOF(psfi->szDisplayName)); return (dw); } } //============================================================================= // // FormatNumberStr() // int FormatNumberStr(LPWSTR lpNumberStr) { WCHAR *c; WCHAR szSep[8]; int i = 0; if (!lstrlen(lpNumberStr)) return (0); if (!GetLocaleInfo(LOCALE_USER_DEFAULT, LOCALE_STHOUSAND, szSep, COUNTOF(szSep))) szSep[0] = L'\''; c = StrEnd(lpNumberStr); while ((c = CharPrev(lpNumberStr, c)) != lpNumberStr) { if (++i == 3) { i = 0; MoveMemory(c + 1, c, sizeof(WCHAR) * (lstrlen(c) + 1)); *c = szSep[0]; } } return (lstrlen(lpNumberStr)); } //============================================================================= // // SetDlgItemIntEx() // BOOL SetDlgItemIntEx(HWND hwnd, int nIdItem, UINT uValue) { WCHAR szBuf[64]; wsprintf(szBuf, L"%u", uValue); FormatNumberStr(szBuf); return (SetDlgItemText(hwnd, nIdItem, szBuf)); } //============================================================================= // // A2W: Convert Dialog Item Text form Unicode to UTF-8 and vice versa // UINT GetDlgItemTextA2W(UINT uCP, HWND hDlg, int nIDDlgItem, LPSTR lpString, int nMaxCount) { WCHAR wsz[1024] = L""; UINT uRet = GetDlgItemTextW(hDlg, nIDDlgItem, wsz, COUNTOF(wsz)); ZeroMemory(lpString, nMaxCount); WCharToMBCS(uCP, wsz, lpString, nMaxCount - 2); return uRet; } UINT SetDlgItemTextA2W(UINT uCP, HWND hDlg, int nIDDlgItem, LPSTR lpString) { WCHAR wsz[1024] = L""; MBCSToWChar(uCP, lpString, wsz, COUNTOF(wsz)); return SetDlgItemTextW(hDlg, nIDDlgItem, wsz); } LRESULT ComboBox_AddStringA2W(UINT uCP, HWND hwnd, LPCSTR lpString) { WCHAR wsz[1024] = L""; MBCSToWChar(uCP, lpString, wsz, COUNTOF(wsz)); return SendMessageW(hwnd, CB_ADDSTRING, 0, (LPARAM)wsz); } //============================================================================= // // CodePageFromCharSet() // UINT CodePageFromCharSet(UINT uCharSet) { CHARSETINFO ci; if (TranslateCharsetInfo((DWORD *)(UINT_PTR)uCharSet, &ci, TCI_SRCCHARSET)) return (ci.ciACP); else return (GetACP()); } //============================================================================= // // MRU functions // LPMRULIST MRU_Create(LPCWSTR pszRegKey, int iFlags, int iSize) { LPMRULIST pmru = LocalAlloc(LPTR, sizeof(MRULIST)); ZeroMemory(pmru, sizeof(MRULIST)); lstrcpyn(pmru->szRegKey, pszRegKey, COUNTOF(pmru->szRegKey)); pmru->iFlags = iFlags; pmru->iSize = min(iSize, MRU_MAXITEMS); return (pmru); } BOOL MRU_Destroy(LPMRULIST pmru) { int i; for (i = 0; i < pmru->iSize; i++) { if (pmru->pszItems[i]) LocalFree(pmru->pszItems[i]); } ZeroMemory(pmru, sizeof(MRULIST)); LocalFree(pmru); return (1); } int MRU_Compare(LPMRULIST pmru, LPCWSTR psz1, LPCWSTR psz2) { if (pmru->iFlags & MRU_NOCASE) return (lstrcmpi(psz1, psz2)); else return (lstrcmp(psz1, psz2)); } BOOL MRU_Add(LPMRULIST pmru, LPCWSTR pszNew) { int i; for (i = 0; i < pmru->iSize; i++) { if (MRU_Compare(pmru, pmru->pszItems[i], pszNew) == 0) { LocalFree(pmru->pszItems[i]); break; } } i = min(i, pmru->iSize - 1); for (; i > 0; i--) pmru->pszItems[i] = pmru->pszItems[i - 1]; pmru->pszItems[0] = StrDup(pszNew); return (1); } BOOL MRU_AddFile(LPMRULIST pmru, LPCWSTR pszFile, BOOL bRelativePath, BOOL bUnexpandMyDocs) { int i; for (i = 0; i < pmru->iSize; i++) { // [2e]: access violation fix if (pmru->pszItems[i]) { if (lstrcmpi(pmru->pszItems[i], pszFile) == 0) { LocalFree(pmru->pszItems[i]); break; } else { WCHAR wchItem[MAX_PATH]; PathAbsoluteFromApp(pmru->pszItems[i], wchItem, COUNTOF(wchItem), TRUE); if (lstrcmpi(wchItem, pszFile) == 0) { LocalFree(pmru->pszItems[i]); break; } } } } i = min(i, pmru->iSize - 1); for (; i > 0; i--) pmru->pszItems[i] = pmru->pszItems[i - 1]; if (bRelativePath) { WCHAR wchFile[MAX_PATH]; PathRelativeToApp((LPWSTR)pszFile, wchFile, COUNTOF(wchFile), TRUE, TRUE, bUnexpandMyDocs); pmru->pszItems[0] = StrDup(wchFile); } else pmru->pszItems[0] = StrDup(pszFile); return (1); } BOOL MRU_Delete(LPMRULIST pmru, int iIndex) { int i; if (iIndex < 0 || iIndex > pmru->iSize - 1) return (0); if (pmru->pszItems[iIndex]) LocalFree(pmru->pszItems[iIndex]); for (i = iIndex; i < pmru->iSize - 1; i++) { pmru->pszItems[i] = pmru->pszItems[i + 1]; pmru->pszItems[i + 1] = NULL; } return (1); } BOOL MRU_DeleteFileFromStore(LPMRULIST pmru, LPCWSTR pszFile) { int i = 0; LPMRULIST pmruStore; WCHAR wchItem[256]; pmruStore = MRU_Create(pmru->szRegKey, pmru->iFlags, pmru->iSize); MRU_Load(pmruStore); while (MRU_Enum(pmruStore, i, wchItem, COUNTOF(wchItem)) != -1) { PathAbsoluteFromApp(wchItem, wchItem, COUNTOF(wchItem), TRUE); if (lstrcmpi(wchItem, pszFile) == 0) MRU_Delete(pmruStore, i); else i++; } MRU_Save(pmruStore); MRU_Destroy(pmruStore); return (1); } BOOL MRU_Empty(LPMRULIST pmru) { int i; for (i = 0; i < pmru->iSize; i++) { if (pmru->pszItems[i]) { LocalFree(pmru->pszItems[i]); pmru->pszItems[i] = NULL; } } return (1); } int MRU_Enum(LPMRULIST pmru, int iIndex, LPWSTR pszItem, int cchItem) { if (pszItem == NULL || cchItem == 0) { int i = 0; while (pmru->pszItems[i] && i < pmru->iSize) i++; return (i); } else { if (iIndex < 0 || iIndex > pmru->iSize - 1 || !pmru->pszItems[iIndex]) return (-1); else { lstrcpyn(pszItem, pmru->pszItems[iIndex], cchItem); return (lstrlen(pszItem)); } } } BOOL MRU_Load(LPMRULIST pmru) { int i, n = 0; WCHAR tchName[32]; WCHAR tchItem[1024]; WCHAR *pIniSection = LocalAlloc(LPTR, sizeof(WCHAR) * 32 * 1024); MRU_Empty(pmru); LoadIniSection(pmru->szRegKey, pIniSection, (int)LocalSize(pIniSection) / sizeof(WCHAR)); for (i = 0; i < pmru->iSize; i++) { wsprintf(tchName, L"%.2i", i + 1); if (IniSectionGetString(pIniSection, tchName, L"", tchItem, COUNTOF(tchItem))) pmru->pszItems[n++] = StrDup(tchItem); } LocalFree(pIniSection); return (1); } BOOL MRU_Save(LPMRULIST pmru) { int i; WCHAR tchName[32]; WCHAR *pIniSection = LocalAlloc(LPTR, sizeof(WCHAR) * 32 * 1024); for (i = 0; i < pmru->iSize; i++) { if (pmru->pszItems[i]) { wsprintf(tchName, L"%.2i", i + 1); IniSectionSetString(pIniSection, tchName, pmru->pszItems[i]); } } SaveIniSection(pmru->szRegKey, pIniSection); LocalFree(pIniSection); return (1); } BOOL MRU_MergeSave(LPMRULIST pmru, BOOL bAddFiles, BOOL bRelativePath, BOOL bUnexpandMyDocs) { int i; LPMRULIST pmruBase; pmruBase = MRU_Create(pmru->szRegKey, pmru->iFlags, pmru->iSize); MRU_Load(pmruBase); if (bAddFiles) { for (i = pmru->iSize - 1; i >= 0; i--) { if (pmru->pszItems[i]) { WCHAR wchItem[MAX_PATH]; PathAbsoluteFromApp(pmru->pszItems[i], wchItem, COUNTOF(wchItem), TRUE); MRU_AddFile(pmruBase, wchItem, bRelativePath, bUnexpandMyDocs); } } } else { for (i = pmru->iSize - 1; i >= 0; i--) { if (pmru->pszItems[i]) MRU_Add(pmruBase, pmru->pszItems[i]); } } MRU_Save(pmruBase); MRU_Destroy(pmruBase); return (1); } /* Themed Dialogs Modify dialog templates to use current theme font Based on code of MFC helper class CDialogTemplate */ BOOL GetThemedDialogFont(LPWSTR lpFaceName, WORD *wSize) { HDC hDC; int iLogPixelsY; HMODULE hModUxTheme; HTHEME hTheme; LOGFONT lf; BOOL bSucceed = FALSE; hDC = GetDC(NULL); iLogPixelsY = GetDeviceCaps(hDC, LOGPIXELSY); ReleaseDC(NULL, hDC); if (hModUxTheme = GetModuleHandle(L"uxtheme.dll")) { if ((BOOL)(GetProcAddress(hModUxTheme, "IsAppThemed")) ()) { hTheme = (HTHEME)(INT_PTR)(GetProcAddress(hModUxTheme, "OpenThemeData")) (NULL, L"WINDOWSTYLE;WINDOW"); if (hTheme) { if (S_OK == (HRESULT)(GetProcAddress(hModUxTheme, "GetThemeSysFont")) (hTheme,/*TMT_MSGBOXFONT*/805, &lf)) { if (lf.lfHeight < 0) lf.lfHeight = -lf.lfHeight; *wSize = (WORD)MulDiv(lf.lfHeight, 72, iLogPixelsY); if (*wSize == 0) *wSize = 8; StrCpyN(lpFaceName, lf.lfFaceName, LF_FACESIZE); bSucceed = TRUE; } (GetProcAddress(hModUxTheme, "CloseThemeData")) (hTheme); } } } return (bSucceed); } __inline BOOL DialogTemplate_IsDialogEx(const DLGTEMPLATE *pTemplate) { return ((DLGTEMPLATEEX *)pTemplate)->signature == 0xFFFF; } __inline BOOL DialogTemplate_HasFont(const DLGTEMPLATE *pTemplate) { return (DS_SETFONT & (DialogTemplate_IsDialogEx(pTemplate) ? ((DLGTEMPLATEEX *)pTemplate)->style : pTemplate->style)); } __inline int DialogTemplate_FontAttrSize(BOOL bDialogEx) { return (int) sizeof(WORD) * (bDialogEx ? 3 : 1); } __inline BYTE *DialogTemplate_GetFontSizeField(const DLGTEMPLATE *pTemplate) { BOOL bDialogEx = DialogTemplate_IsDialogEx(pTemplate); WORD *pw; if (bDialogEx) pw = (WORD *)((DLGTEMPLATEEX *)pTemplate + 1); else pw = (WORD *)(pTemplate + 1); if (*pw == (WORD)-1) pw += 2; else while (*pw++); if (*pw == (WORD)-1) pw += 2; else while (*pw++); while (*pw++); return (BYTE *)pw; } DLGTEMPLATE *LoadThemedDialogTemplate(LPCTSTR lpDialogTemplateID, HINSTANCE hInstance) { HRSRC hRsrc; HGLOBAL hRsrcMem; DLGTEMPLATE *pRsrcMem; DLGTEMPLATE *pTemplate; UINT dwTemplateSize = 0; WCHAR wchFaceName[LF_FACESIZE]; WORD wFontSize; BOOL bDialogEx; BOOL bHasFont; int cbFontAttr; int cbNew; int cbOld; BYTE *pbNew; BYTE *pb; BYTE *pOldControls; BYTE *pNewControls; WORD nCtrl; hRsrc = FindResource(hInstance, lpDialogTemplateID, RT_DIALOG); if (hRsrc == NULL) return (NULL); hRsrcMem = LoadResource(hInstance, hRsrc); pRsrcMem = (DLGTEMPLATE *)LockResource(hRsrcMem); dwTemplateSize = (UINT)SizeofResource(hInstance, hRsrc); if ((dwTemplateSize == 0) || (pTemplate = LocalAlloc(LPTR, dwTemplateSize + LF_FACESIZE * 2)) == NULL) { UnlockResource(hRsrcMem); FreeResource(hRsrcMem); return (NULL); } CopyMemory((BYTE *)pTemplate, pRsrcMem, (size_t)dwTemplateSize); UnlockResource(hRsrcMem); FreeResource(hRsrcMem); if (!GetThemedDialogFont(wchFaceName, &wFontSize)) return (pTemplate); bDialogEx = DialogTemplate_IsDialogEx(pTemplate); bHasFont = DialogTemplate_HasFont(pTemplate); cbFontAttr = DialogTemplate_FontAttrSize(bDialogEx); if (bDialogEx) ((DLGTEMPLATEEX *)pTemplate)->style |= DS_SHELLFONT; else pTemplate->style |= DS_SHELLFONT; cbNew = cbFontAttr + ((lstrlen(wchFaceName) + 1) * sizeof(WCHAR)); pbNew = (BYTE *)wchFaceName; pb = DialogTemplate_GetFontSizeField(pTemplate); cbOld = (int)(bHasFont ? cbFontAttr + 2 * (lstrlen((WCHAR *)(pb + cbFontAttr)) + 1) : 0); pOldControls = (BYTE *)(((DWORD_PTR)pb + cbOld + 3) & ~(DWORD_PTR)3); pNewControls = (BYTE *)(((DWORD_PTR)pb + cbNew + 3) & ~(DWORD_PTR)3); nCtrl = bDialogEx ? (WORD)((DLGTEMPLATEEX *)pTemplate)->cDlgItems : (WORD)pTemplate->cdit; if (cbNew != cbOld && nCtrl > 0) MoveMemory(pNewControls, pOldControls, (size_t)(dwTemplateSize - (pOldControls - (BYTE *)pTemplate))); *(WORD *)pb = wFontSize; MoveMemory(pb + cbFontAttr, pbNew, (size_t)(cbNew - cbFontAttr)); return (pTemplate); } INT_PTR ThemedDialogBoxParam( HINSTANCE hInstance, LPCTSTR lpTemplate, HWND hWndParent, DLGPROC lpDialogFunc, LPARAM dwInitParam) { INT_PTR ret; DLGTEMPLATE *pDlgTemplate; pDlgTemplate = LoadThemedDialogTemplate(lpTemplate, hInstance); ret = DialogBoxIndirectParam(hInstance, pDlgTemplate, hWndParent, lpDialogFunc, dwInitParam); if (pDlgTemplate) LocalFree(pDlgTemplate); return (ret); } HWND CreateThemedDialogParam( HINSTANCE hInstance, LPCTSTR lpTemplate, HWND hWndParent, DLGPROC lpDialogFunc, LPARAM dwInitParam) { HWND hwnd; DLGTEMPLATE *pDlgTemplate; pDlgTemplate = LoadThemedDialogTemplate(lpTemplate, hInstance); hwnd = CreateDialogIndirectParam(hInstance, pDlgTemplate, hWndParent, lpDialogFunc, dwInitParam); if (pDlgTemplate) LocalFree(pDlgTemplate); return (hwnd); } /****************************************************************************** * * UnSlash functions * Mostly taken from SciTE, (c) Neil Hodgson, http://www.scintilla.org * / /** * Is the character an octal digit? */ static BOOL IsOctalDigit(char ch) { return ch >= '0' && ch <= '7'; } /** * If the character is an hexa digit, get its value. */ static int GetHexDigit(char ch) { if (ch >= '0' && ch <= '9') { return ch - '0'; } if (ch >= 'A' && ch <= 'F') { return ch - 'A' + 10; } if (ch >= 'a' && ch <= 'f') { return ch - 'a' + 10; } return -1; } /** * Convert C style \a, \b, \f, \n, \r, \t, \v, \xhh and \uhhhh into their indicated characters. */ unsigned int UnSlash(char *s, UINT cpEdit) { char *sStart = s; char *o = s; while (*s) { if (*s == '\\') { s++; if (*s == 'a') *o = '\a'; else if (*s == 'b') *o = '\b'; else if (*s == 'f') *o = '\f'; else if (*s == 'n') *o = '\n'; else if (*s == 'r') *o = '\r'; else if (*s == 't') *o = '\t'; else if (*s == 'v') *o = '\v'; else if (*s == 'x' || *s == 'u') { BOOL bShort = (*s == 'x'); char ch[8]; char *pch = ch; WCHAR val[2] = L""; int hex; val[0] = 0; hex = GetHexDigit(*(s + 1)); if (hex >= 0) { s++; val[0] = hex; hex = GetHexDigit(*(s + 1)); if (hex >= 0) { s++; val[0] *= 16; val[0] += hex; if (!bShort) { hex = GetHexDigit(*(s + 1)); if (hex >= 0) { s++; val[0] *= 16; val[0] += hex; hex = GetHexDigit(*(s + 1)); if (hex >= 0) { s++; val[0] *= 16; val[0] += hex; } } } } if (val[0]) { val[1] = 0; WideCharToMultiByte(cpEdit, 0, val, -1, ch, COUNTOF(ch), NULL, NULL); *o = *pch++; while (*pch) *++o = *pch++; } else o--; } else o--; } else *o = *s; } else *o = *s; o++; if (*s) { s++; } } *o = '\0'; return (unsigned int)(o - sStart); } /** * Convert C style \0oo into their indicated characters. * This is used to get control characters into the regular expresion engine. */ unsigned int UnSlashLowOctal(char *s) { char *sStart = s; char *o = s; while (*s) { if ((s[0] == '\\') && (s[1] == '0') && IsOctalDigit(s[2]) && IsOctalDigit(s[3])) { *o = (char)(8 * (s[2] - '0') + (s[3] - '0')); s += 3; } else { *o = *s; } o++; if (*s) s++; } *o = '\0'; return (unsigned int)(o - sStart); } void TransformBackslashes(char *pszInput, BOOL bRegEx, UINT cpEdit) { if (bRegEx) UnSlashLowOctal(pszInput); else UnSlash(pszInput, cpEdit); } /* MinimizeToTray - Copyright 2000 Matthew Ellis <m.t.ellis@bigfoot.com> Changes made by flo: - Commented out: #include "stdafx.h" - Moved variable declaration: APPBARDATA appBarData; */ // MinimizeToTray // // A couple of routines to show how to make it produce a custom caption // animation to make it look like we are minimizing to and maximizing // from the system tray // // These routines are public domain, but it would be nice if you dropped // me a line if you use them! // // 1.0 29.06.2000 Initial version // 1.1 01.07.2000 The window retains it's place in the Z-order of windows // when minimized/hidden. This means that when restored/shown, it doen't // always appear as the foreground window unless we call SetForegroundWindow // // Copyright 2000 Matthew Ellis <m.t.ellis@bigfoot.com> /*#include "stdafx.h"*/ // Odd. VC++6 winuser.h has IDANI_CAPTION defined (as well as IDANI_OPEN and // IDANI_CLOSE), but the Platform SDK only has IDANI_OPEN... // I don't know what IDANI_OPEN or IDANI_CLOSE do. Trying them in this code // produces nothing. Perhaps they were intended for window opening and closing // like the MAC provides... #ifndef IDANI_OPEN #define IDANI_OPEN 1 #endif #ifndef IDANI_CLOSE #define IDANI_CLOSE 2 #endif #ifndef IDANI_CAPTION #define IDANI_CAPTION 3 #endif #define DEFAULT_RECT_WIDTH 150 #define DEFAULT_RECT_HEIGHT 30 // Returns the rect of where we think the system tray is. This will work for // all current versions of the shell. If explorer isn't running, we try our // best to work with a 3rd party shell. If we still can't find anything, we // return a rect in the lower right hand corner of the screen static VOID GetTrayWndRect(LPRECT lpTrayRect) { APPBARDATA appBarData; // First, we'll use a quick hack method. We know that the taskbar is a window // of class Shell_TrayWnd, and the status tray is a child of this of class // TrayNotifyWnd. This provides us a window rect to minimize to. Note, however, // that this is not guaranteed to work on future versions of the shell. If we // use this method, make sure we have a backup! HWND hShellTrayWnd = FindWindowEx(NULL, NULL, TEXT("Shell_TrayWnd"), NULL); if (hShellTrayWnd) { HWND hTrayNotifyWnd = FindWindowEx(hShellTrayWnd, NULL, TEXT("TrayNotifyWnd"), NULL); if (hTrayNotifyWnd) { GetWindowRect(hTrayNotifyWnd, lpTrayRect); return; } } // OK, we failed to get the rect from the quick hack. Either explorer isn't // running or it's a new version of the shell with the window class names // changed (how dare Microsoft change these undocumented class names!) So, we // try to find out what side of the screen the taskbar is connected to. We // know that the system tray is either on the right or the bottom of the // taskbar, so we can make a good guess at where to minimize to /*APPBARDATA appBarData;*/ appBarData.cbSize = sizeof(appBarData); if (SHAppBarMessage(ABM_GETTASKBARPOS, &appBarData)) { // We know the edge the taskbar is connected to, so guess the rect of the // system tray. Use various fudge factor to make it look good switch (appBarData.uEdge) { case ABE_LEFT: case ABE_RIGHT: // We want to minimize to the bottom of the taskbar lpTrayRect->top = appBarData.rc.bottom - 100; lpTrayRect->bottom = appBarData.rc.bottom - 16; lpTrayRect->left = appBarData.rc.left; lpTrayRect->right = appBarData.rc.right; break; case ABE_TOP: case ABE_BOTTOM: // We want to minimize to the right of the taskbar lpTrayRect->top = appBarData.rc.top; lpTrayRect->bottom = appBarData.rc.bottom; lpTrayRect->left = appBarData.rc.right - 100; lpTrayRect->right = appBarData.rc.right - 16; break; } return; } // Blimey, we really aren't in luck. It's possible that a third party shell // is running instead of explorer. This shell might provide support for the // system tray, by providing a Shell_TrayWnd window (which receives the // messages for the icons) So, look for a Shell_TrayWnd window and work out // the rect from that. Remember that explorer's taskbar is the Shell_TrayWnd, // and stretches either the width or the height of the screen. We can't rely // on the 3rd party shell's Shell_TrayWnd doing the same, in fact, we can't // rely on it being any size. The best we can do is just blindly use the // window rect, perhaps limiting the width and height to, say 150 square. // Note that if the 3rd party shell supports the same configuraion as // explorer (the icons hosted in NotifyTrayWnd, which is a child window of // Shell_TrayWnd), we would already have caught it above hShellTrayWnd = FindWindowEx(NULL, NULL, TEXT("Shell_TrayWnd"), NULL); if (hShellTrayWnd) { GetWindowRect(hShellTrayWnd, lpTrayRect); if (lpTrayRect->right - lpTrayRect->left > DEFAULT_RECT_WIDTH) lpTrayRect->left = lpTrayRect->right - DEFAULT_RECT_WIDTH; if (lpTrayRect->bottom - lpTrayRect->top > DEFAULT_RECT_HEIGHT) lpTrayRect->top = lpTrayRect->bottom - DEFAULT_RECT_HEIGHT; return; } // OK. Haven't found a thing. Provide a default rect based on the current work // area SystemParametersInfo(SPI_GETWORKAREA, 0, lpTrayRect, 0); lpTrayRect->left = lpTrayRect->right - DEFAULT_RECT_WIDTH; lpTrayRect->top = lpTrayRect->bottom - DEFAULT_RECT_HEIGHT; } // Check to see if the animation has been disabled BOOL GetDoAnimateMinimize(VOID) { ANIMATIONINFO ai; ai.cbSize = sizeof(ai); SystemParametersInfo(SPI_GETANIMATION, sizeof(ai), &ai, 0); return ai.iMinAnimate ? TRUE : FALSE; } VOID MinimizeWndToTray(HWND hWnd) { if (GetDoAnimateMinimize()) { RECT rcFrom, rcTo; // Get the rect of the window. It is safe to use the rect of the whole // window - DrawAnimatedRects will only draw the caption GetWindowRect(hWnd, &rcFrom); GetTrayWndRect(&rcTo); // Get the system to draw our animation for us DrawAnimatedRects(hWnd, IDANI_CAPTION, &rcFrom, &rcTo); } // Add the tray icon. If we add it before the call to DrawAnimatedRects, // the taskbar gets erased, but doesn't get redrawn until DAR finishes. // This looks untidy, so call the functions in this order // Hide the window ShowWindow(hWnd, SW_HIDE); } VOID RestoreWndFromTray(HWND hWnd) { if (GetDoAnimateMinimize()) { // Get the rect of the tray and the window. Note that the window rect // is still valid even though the window is hidden RECT rcFrom, rcTo; GetTrayWndRect(&rcFrom); GetWindowRect(hWnd, &rcTo); // Get the system to draw our animation for us DrawAnimatedRects(hWnd, IDANI_CAPTION, &rcFrom, &rcTo); } // Show the window, and make sure we're the foreground window ShowWindow(hWnd, SW_SHOW); SetActiveWindow(hWnd); SetForegroundWindow(hWnd); // Remove the tray icon. As described above, remove the icon after the // call to DrawAnimatedRects, or the taskbar will not refresh itself // properly until DAR finished }
// Copyright 1998-2017 Epic Games, Inc. All Rights Reserved. /** * LevelStreamingPersistent * * @documentation * */ #pragma once #include "CoreMinimal.h" #include "UObject/ObjectMacros.h" #include "Engine/LevelStreaming.h" #include "LevelStreamingPersistent.generated.h" UCLASS(transient) class ULevelStreamingPersistent : public ULevelStreaming { GENERATED_UCLASS_BODY() //~ Begin ULevelStreaming Interface virtual bool ShouldBeLoaded() const override { return true; } virtual bool ShouldBeVisible() const override { return true; } //~ End ULevelStreaming Interface };
#ifdef __OBJC__ #import <Cocoa/Cocoa.h> #else #ifndef FOUNDATION_EXPORT #if defined(__cplusplus) #define FOUNDATION_EXPORT extern "C" #else #define FOUNDATION_EXPORT extern #endif #endif #endif FOUNDATION_EXPORT double Pods_App_HeartVoice_macOS_VersionNumber; FOUNDATION_EXPORT const unsigned char Pods_App_HeartVoice_macOS_VersionString[];
/** @file */ /// Includes all the systemwide header files #include<iostream> #include<cstdlib> #include<string> #include<fstream> #include<sstream> #include<assert.h> #include<iomanip> #include<sys/stat.h> #include<cmath> #include<math.h> #include<time.h> #include<vector> #include <omp.h> //Default namespace is std for this program using namespace std; #ifndef CONSTANTS #define CONSTANTS const double PI = 3.14159265; const double GAMMA = 1.4; // specific heat ratio /// Tolerances const double EPS = 2.220446049250313e-16; //machine accuracy const double SMALL = pow(10,-3); const double MICRO = pow(10,-6); const double NANO = pow(10,-9); const double PICO = pow(10,-12); const double FEMTO = pow(10,-15); const double SMALL10 = pow(10,-10); const double LARGE= pow(10,3); const double MEGA = pow(10,6); const double GIGA = pow(10,9); const double TERA = pow(10,12); const double PETA = pow(10,15); const double LARGE10 = pow(10,10); #endif /// Define dTypes typedef unsigned int Index; typedef unsigned int unt; // Include all the other supporting files // 0. Functions which do not depend on anything #include "cellTypes.h" #include "faceTypes.h" #include "Eigen/Dense" //include Eigen library for matrix operations #include "intFlag.h" #include "Solvers.h" #include "Systems.h" // 1. Functions which do not depend on other MEANDG functions but may depend on sysInclude.h functions #include "displayFunctions.h" #include "otherFunctions.h" #include "randomGenerator.h" #include "Tensor.h"
/** * \file md5.h * * \brief MD5 message digest algorithm (hash function) * * Copyright (C) 2006-2013, Brainspark B.V. * * This file is part of PolarSSL (http://www.polarssl.org) * Lead Maintainer: Paul Bakker <polarssl_maintainer at polarssl.org> * * All rights reserved. * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License along * with this program; if not, write to the Free Software Foundation, Inc., * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. */ #ifndef POLARSSL_MD5_H #define POLARSSL_MD5_H #if !defined(POLARSSL_CONFIG_FILE) #include "config.h" #else #include POLARSSL_CONFIG_FILE #endif #if !defined(POLARSSL_LINUX_KERNEL) #include <string.h> #endif #if defined(_MSC_VER) && !defined(EFIX64) && !defined(EFI32) #include <basetsd.h> typedef UINT32 uint32_t; #elseif !defined(POLARSSL_LINUX_KERNEL) #include <inttypes.h> #endif #define POLARSSL_ERR_MD5_FILE_IO_ERROR -0x0074 /**< Read/write error in file. */ #if !defined(POLARSSL_MD5_ALT) // Regular implementation // #ifdef __cplusplus extern "C" { #endif /** * \brief MD5 context structure */ typedef struct { uint32_t total[2]; /*!< number of bytes processed */ uint32_t state[4]; /*!< intermediate digest state */ unsigned char buffer[64]; /*!< data block being processed */ unsigned char ipad[64]; /*!< HMAC: inner padding */ unsigned char opad[64]; /*!< HMAC: outer padding */ } md5_context; /** * \brief Initialize MD5 context * * \param ctx MD5 context to be initialized */ void md5_init( md5_context *ctx ); /** * \brief Clear MD5 context * * \param ctx MD5 context to be cleared */ void md5_free( md5_context *ctx ); /** * \brief MD5 context setup * * \param ctx context to be initialized */ void md5_starts( md5_context *ctx ); /** * \brief MD5 process buffer * * \param ctx MD5 context * \param input buffer holding the data * \param ilen length of the input data */ void md5_update( md5_context *ctx, const unsigned char *input, size_t ilen ); /** * \brief MD5 final digest * * \param ctx MD5 context * \param output MD5 checksum result */ void md5_finish( md5_context *ctx, unsigned char output[16] ); /* Internal use */ void md5_process( md5_context *ctx, const unsigned char data[64] ); #ifdef __cplusplus } #endif #else /* POLARSSL_MD5_ALT */ #include "md5_alt.h" #endif /* POLARSSL_MD5_ALT */ #ifdef __cplusplus extern "C" { #endif /** * \brief Output = MD5( input buffer ) * * \param input buffer holding the data * \param ilen length of the input data * \param output MD5 checksum result */ void md5( const unsigned char *input, size_t ilen, unsigned char output[16] ); /** * \brief Output = MD5( file contents ) * * \param path input file name * \param output MD5 checksum result * * \return 0 if successful, or POLARSSL_ERR_MD5_FILE_IO_ERROR */ int md5_file( const char *path, unsigned char output[16] ); /** * \brief MD5 HMAC context setup * * \param ctx HMAC context to be initialized * \param key HMAC secret key * \param keylen length of the HMAC key */ void md5_hmac_starts( md5_context *ctx, const unsigned char *key, size_t keylen ); /** * \brief MD5 HMAC process buffer * * \param ctx HMAC context * \param input buffer holding the data * \param ilen length of the input data */ void md5_hmac_update( md5_context *ctx, const unsigned char *input, size_t ilen ); /** * \brief MD5 HMAC final digest * * \param ctx HMAC context * \param output MD5 HMAC checksum result */ void md5_hmac_finish( md5_context *ctx, unsigned char output[16] ); /** * \brief MD5 HMAC context reset * * \param ctx HMAC context to be reset */ void md5_hmac_reset( md5_context *ctx ); /** * \brief Output = HMAC-MD5( hmac key, input buffer ) * * \param key HMAC secret key * \param keylen length of the HMAC key * \param input buffer holding the data * \param ilen length of the input data * \param output HMAC-MD5 result */ void md5_hmac( const unsigned char *key, size_t keylen, const unsigned char *input, size_t ilen, unsigned char output[16] ); /** * \brief Checkup routine * * \return 0 if successful, or 1 if the test failed */ int md5_self_test( int verbose ); #ifdef __cplusplus } #endif #endif /* md5.h */
//------------------------------------------------------------------------------ /* This file is part of rippled: https://github.com/ripple/rippled Copyright (c) 2012, 2013 Ripple Labs Inc. Permission to use, copy, modify, and/or distribute this software for any purpose with or without fee is hereby granted, provided that the above copyright notice and this permission notice appear in all copies. THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL , DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. */ //============================================================================== #ifndef RIPPLE_PROTOCOL_STOBJECT_H_INCLUDED #define RIPPLE_PROTOCOL_STOBJECT_H_INCLUDED #include <ripple/basics/CountedObject.h> #include <ripple/basics/FeeUnits.h> #include <ripple/basics/Slice.h> #include <ripple/basics/chrono.h> #include <ripple/basics/contract.h> #include <ripple/protocol/HashPrefix.h> #include <ripple/protocol/SOTemplate.h> #include <ripple/protocol/STAmount.h> #include <ripple/protocol/STPathSet.h> #include <ripple/protocol/STVector256.h> #include <ripple/protocol/impl/STVar.h> #include <boost/iterator/transform_iterator.hpp> #include <cassert> #include <optional> #include <stdexcept> #include <type_traits> #include <utility> namespace ripple { class STArray; inline void throwFieldNotFound(SField const& field) { Throw<std::runtime_error>("Field not found: " + field.getName()); } class STObject : public STBase, public CountedObject<STObject> { private: // Proxy value for a STBase derived class template <class T> class Proxy { protected: using value_type = typename T::value_type; STObject* st_; SOEStyle style_; TypedField<T> const* f_; Proxy(Proxy const&) = default; Proxy(STObject* st, TypedField<T> const* f); value_type value() const; T const* find() const; template <class U> void assign(U&& u); }; template <class T> class ValueProxy : private Proxy<T> { private: using value_type = typename T::value_type; public: ValueProxy(ValueProxy const&) = default; ValueProxy& operator=(ValueProxy const&) = delete; template <class U> std::enable_if_t<std::is_assignable_v<T, U>, ValueProxy&> operator=(U&& u); operator value_type() const; private: friend class STObject; ValueProxy(STObject* st, TypedField<T> const* f); }; template <class T> class OptionalProxy : private Proxy<T> { private: using value_type = typename T::value_type; using optional_type = std::optional<typename std::decay<value_type>::type>; public: OptionalProxy(OptionalProxy const&) = default; OptionalProxy& operator=(OptionalProxy const&) = delete; /** Returns `true` if the field is set. Fields with soeDEFAULT and set to the default value will return `true` */ explicit operator bool() const noexcept; /** Return the contained value Throws: STObject::FieldErr if !engaged() */ value_type operator*() const; operator optional_type() const; /** Explicit conversion to std::optional */ optional_type operator~() const; friend bool operator==(OptionalProxy const& lhs, std::nullopt_t) noexcept { return !lhs.engaged(); } friend bool operator==(std::nullopt_t, OptionalProxy const& rhs) noexcept { return rhs == std::nullopt; } friend bool operator==(OptionalProxy const& lhs, optional_type const& rhs) noexcept { if (!lhs.engaged()) return !rhs; if (!rhs) return false; return *lhs == *rhs; } friend bool operator==(optional_type const& lhs, OptionalProxy const& rhs) noexcept { return rhs == lhs; } friend bool operator==(OptionalProxy const& lhs, OptionalProxy const& rhs) noexcept { if (lhs.engaged() != rhs.engaged()) return false; return !lhs.engaged() || *lhs == *rhs; } friend bool operator!=(OptionalProxy const& lhs, std::nullopt_t) noexcept { return !(lhs == std::nullopt); } friend bool operator!=(std::nullopt_t, OptionalProxy const& rhs) noexcept { return !(rhs == std::nullopt); } friend bool operator!=(OptionalProxy const& lhs, optional_type const& rhs) noexcept { return !(lhs == rhs); } friend bool operator!=(optional_type const& lhs, OptionalProxy const& rhs) noexcept { return !(lhs == rhs); } friend bool operator!=(OptionalProxy const& lhs, OptionalProxy const& rhs) noexcept { return !(lhs == rhs); } // Emulate std::optional::value_or value_type value_or(value_type val) const { return engaged() ? this->value() : val; } OptionalProxy& operator=(std::nullopt_t const&); OptionalProxy& operator=(optional_type&& v); OptionalProxy& operator=(optional_type const& v); template <class U> std::enable_if_t<std::is_assignable_v<T, U>, OptionalProxy&> operator=(U&& u); private: friend class STObject; OptionalProxy(STObject* st, TypedField<T> const* f); bool engaged() const noexcept; void disengage(); optional_type optional_value() const; }; struct Transform { explicit Transform() = default; using argument_type = detail::STVar; using result_type = STBase; STBase const& operator()(detail::STVar const& e) const { return e.get(); } }; using list_type = std::vector<detail::STVar>; list_type v_; SOTemplate const* mType; public: using iterator = boost:: transform_iterator<Transform, STObject::list_type::const_iterator>; class FieldErr : public std::runtime_error { using std::runtime_error::runtime_error; }; STObject(STObject&&); STObject(STObject const&) = default; STObject(const SOTemplate& type, SField const& name); STObject( const SOTemplate& type, SerialIter& sit, SField const& name) noexcept(false); STObject(SerialIter& sit, SField const& name, int depth = 0) noexcept( false); STObject(SerialIter&& sit, SField const& name) noexcept(false) : STObject(sit, name) { } STObject& operator=(STObject const&) = default; STObject& operator=(STObject&& other); explicit STObject(SField const& name); virtual ~STObject() = default; STBase* copy(std::size_t n, void* buf) const override { return emplace(n, buf, *this); } STBase* move(std::size_t n, void* buf) override { return emplace(n, buf, std::move(*this)); } iterator begin() const { return iterator(v_.begin()); } iterator end() const { return iterator(v_.end()); } bool empty() const { return v_.empty(); } void reserve(std::size_t n) { v_.reserve(n); } void applyTemplate(const SOTemplate& type) noexcept(false); void applyTemplateFromSField(SField const&) noexcept(false); bool isFree() const { return mType == nullptr; } void set(const SOTemplate&); bool set(SerialIter& u, int depth = 0); virtual SerializedTypeID getSType() const override { return STI_OBJECT; } virtual bool isEquivalent(const STBase& t) const override; virtual bool isDefault() const override { return v_.empty(); } virtual void add(Serializer& s) const override { add(s, withAllFields); // just inner elements } void addWithoutSigningFields(Serializer& s) const { add(s, omitSigningFields); } // VFALCO NOTE does this return an expensive copy of an object with a // dynamic buffer? // VFALCO TODO Remove this function and fix the few callers. Serializer getSerializer() const { Serializer s; add(s, withAllFields); return s; } virtual std::string getFullText() const override; virtual std::string getText() const override; // TODO(tom): options should be an enum. virtual Json::Value getJson(JsonOptions options) const override; template <class... Args> std::size_t emplace_back(Args&&... args) { v_.emplace_back(std::forward<Args>(args)...); return v_.size() - 1; } int getCount() const { return v_.size(); } bool setFlag(std::uint32_t); bool clearFlag(std::uint32_t); bool isFlag(std::uint32_t) const; std::uint32_t getFlags() const; uint256 getHash(HashPrefix prefix) const; uint256 getSigningHash(HashPrefix prefix) const; const STBase& peekAtIndex(int offset) const { return v_[offset].get(); } STBase& getIndex(int offset) { return v_[offset].get(); } const STBase* peekAtPIndex(int offset) const { return &v_[offset].get(); } STBase* getPIndex(int offset) { return &v_[offset].get(); } int getFieldIndex(SField const& field) const; SField const& getFieldSType(int index) const; const STBase& peekAtField(SField const& field) const; STBase& getField(SField const& field); const STBase* peekAtPField(SField const& field) const; STBase* getPField(SField const& field, bool createOkay = false); // these throw if the field type doesn't match, or return default values // if the field is optional but not present unsigned char getFieldU8(SField const& field) const; std::uint16_t getFieldU16(SField const& field) const; std::uint32_t getFieldU32(SField const& field) const; std::uint64_t getFieldU64(SField const& field) const; uint128 getFieldH128(SField const& field) const; uint160 getFieldH160(SField const& field) const; uint256 getFieldH256(SField const& field) const; AccountID getAccountID(SField const& field) const; Blob getFieldVL(SField const& field) const; STAmount const& getFieldAmount(SField const& field) const; STPathSet const& getFieldPathSet(SField const& field) const; const STVector256& getFieldV256(SField const& field) const; const STArray& getFieldArray(SField const& field) const; /** Get the value of a field. @param A TypedField built from an SField value representing the desired object field. In typical use, the TypedField will be implicitly constructed. @return The value of the specified field. @throws STObject::FieldErr if the field is not present. */ template <class T> typename T::value_type operator[](TypedField<T> const& f) const; /** Get the value of a field as a std::optional @param An OptionaledField built from an SField value representing the desired object field. In typical use, the OptionaledField will be constructed by using the ~ operator on an SField. @return std::nullopt if the field is not present, else the value of the specified field. */ template <class T> std::optional<std::decay_t<typename T::value_type>> operator[](OptionaledField<T> const& of) const; /** Get a modifiable field value. @param A TypedField built from an SField value representing the desired object field. In typical use, the TypedField will be implicitly constructed. @return A modifiable reference to the value of the specified field. @throws STObject::FieldErr if the field is not present. */ template <class T> ValueProxy<T> operator[](TypedField<T> const& f); /** Return a modifiable field value as std::optional @param An OptionaledField built from an SField value representing the desired object field. In typical use, the OptionaledField will be constructed by using the ~ operator on an SField. @return Transparent proxy object to an `optional` holding a modifiable reference to the value of the specified field. Returns std::nullopt if the field is not present. */ template <class T> OptionalProxy<T> operator[](OptionaledField<T> const& of); /** Get the value of a field. @param A TypedField built from an SField value representing the desired object field. In typical use, the TypedField will be implicitly constructed. @return The value of the specified field. @throws STObject::FieldErr if the field is not present. */ template <class T> typename T::value_type at(TypedField<T> const& f) const; /** Get the value of a field as std::optional @param An OptionaledField built from an SField value representing the desired object field. In typical use, the OptionaledField will be constructed by using the ~ operator on an SField. @return std::nullopt if the field is not present, else the value of the specified field. */ template <class T> std::optional<std::decay_t<typename T::value_type>> at(OptionaledField<T> const& of) const; /** Get a modifiable field value. @param A TypedField built from an SField value representing the desired object field. In typical use, the TypedField will be implicitly constructed. @return A modifiable reference to the value of the specified field. @throws STObject::FieldErr if the field is not present. */ template <class T> ValueProxy<T> at(TypedField<T> const& f); /** Return a modifiable field value as std::optional @param An OptionaledField built from an SField value representing the desired object field. In typical use, the OptionaledField will be constructed by using the ~ operator on an SField. @return Transparent proxy object to an `optional` holding a modifiable reference to the value of the specified field. Returns std::nullopt if the field is not present. */ template <class T> OptionalProxy<T> at(OptionaledField<T> const& of); /** Set a field. if the field already exists, it is replaced. */ void set(std::unique_ptr<STBase> v); void set(STBase* v); void setFieldU8(SField const& field, unsigned char); void setFieldU16(SField const& field, std::uint16_t); void setFieldU32(SField const& field, std::uint32_t); void setFieldU64(SField const& field, std::uint64_t); void setFieldH128(SField const& field, uint128 const&); void setFieldH256(SField const& field, uint256 const&); void setFieldVL(SField const& field, Blob const&); void setFieldVL(SField const& field, Slice const&); void setAccountID(SField const& field, AccountID const&); void setFieldAmount(SField const& field, STAmount const&); void setFieldPathSet(SField const& field, STPathSet const&); void setFieldV256(SField const& field, STVector256 const& v); void setFieldArray(SField const& field, STArray const& v); template <class Tag> void setFieldH160(SField const& field, base_uint<160, Tag> const& v) { STBase* rf = getPField(field, true); if (!rf) throwFieldNotFound(field); if (rf->getSType() == STI_NOTPRESENT) rf = makeFieldPresent(field); using Bits = STBitString<160>; if (auto cf = dynamic_cast<Bits*>(rf)) cf->setValue(v); else Throw<std::runtime_error>("Wrong field type " + field.fieldName); } STObject& peekFieldObject(SField const& field); STArray& peekFieldArray(SField const& field); bool isFieldPresent(SField const& field) const; STBase* makeFieldPresent(SField const& field); void makeFieldAbsent(SField const& field); bool delField(SField const& field); void delField(int index); bool hasMatchingEntry(const STBase&); bool operator==(const STObject& o) const; bool operator!=(const STObject& o) const { return !(*this == o); } private: enum WhichFields : bool { // These values are carefully chosen to do the right thing if passed // to SField::shouldInclude (bool) omitSigningFields = false, withAllFields = true }; void add(Serializer& s, WhichFields whichFields) const; // Sort the entries in an STObject into the order that they will be // serialized. Note: they are not sorted into pointer value order, they // are sorted by SField::fieldCode. static std::vector<STBase const*> getSortedFields(STObject const& objToSort, WhichFields whichFields); // Implementation for getting (most) fields that return by value. // // The remove_cv and remove_reference are necessitated by the STBitString // types. Their value() returns by const ref. We return those types // by value. template < typename T, typename V = typename std::remove_cv<typename std::remove_reference< decltype(std::declval<T>().value())>::type>::type> V getFieldByValue(SField const& field) const { const STBase* rf = peekAtPField(field); if (!rf) throwFieldNotFound(field); SerializedTypeID id = rf->getSType(); if (id == STI_NOTPRESENT) return V(); // optional field not present const T* cf = dynamic_cast<const T*>(rf); if (!cf) Throw<std::runtime_error>("Wrong field type " + field.fieldName); return cf->value(); } // Implementations for getting (most) fields that return by const reference. // // If an absent optional field is deserialized we don't have anything // obvious to return. So we insist on having the call provide an // 'empty' value we return in that circumstance. template <typename T, typename V> V const& getFieldByConstRef(SField const& field, V const& empty) const { const STBase* rf = peekAtPField(field); if (!rf) throwFieldNotFound(field); SerializedTypeID id = rf->getSType(); if (id == STI_NOTPRESENT) return empty; // optional field not present const T* cf = dynamic_cast<const T*>(rf); if (!cf) Throw<std::runtime_error>("Wrong field type " + field.fieldName); return *cf; } // Implementation for setting most fields with a setValue() method. template <typename T, typename V> void setFieldUsingSetValue(SField const& field, V value) { static_assert(!std::is_lvalue_reference<V>::value, ""); STBase* rf = getPField(field, true); if (!rf) throwFieldNotFound(field); if (rf->getSType() == STI_NOTPRESENT) rf = makeFieldPresent(field); T* cf = dynamic_cast<T*>(rf); if (!cf) Throw<std::runtime_error>("Wrong field type " + field.fieldName); cf->setValue(std::move(value)); } // Implementation for setting fields using assignment template <typename T> void setFieldUsingAssignment(SField const& field, T const& value) { STBase* rf = getPField(field, true); if (!rf) throwFieldNotFound(field); if (rf->getSType() == STI_NOTPRESENT) rf = makeFieldPresent(field); T* cf = dynamic_cast<T*>(rf); if (!cf) Throw<std::runtime_error>("Wrong field type " + field.fieldName); (*cf) = value; } // Implementation for peeking STObjects and STArrays template <typename T> T& peekField(SField const& field) { STBase* rf = getPField(field, true); if (!rf) throwFieldNotFound(field); if (rf->getSType() == STI_NOTPRESENT) rf = makeFieldPresent(field); T* cf = dynamic_cast<T*>(rf); if (!cf) Throw<std::runtime_error>("Wrong field type " + field.fieldName); return *cf; } }; //------------------------------------------------------------------------------ template <class T> STObject::Proxy<T>::Proxy(STObject* st, TypedField<T> const* f) : st_(st), f_(f) { if (st_->mType) { // STObject has associated template if (!st_->peekAtPField(*f_)) Throw<STObject::FieldErr>( "Template field error '" + this->f_->getName() + "'"); style_ = st_->mType->style(*f_); } else { style_ = soeINVALID; } } template <class T> auto STObject::Proxy<T>::value() const -> value_type { auto const t = find(); if (t) return t->value(); if (style_ != soeDEFAULT) Throw<STObject::FieldErr>( "Missing field '" + this->f_->getName() + "'"); return value_type{}; } template <class T> inline T const* STObject::Proxy<T>::find() const { return dynamic_cast<T const*>(st_->peekAtPField(*f_)); } template <class T> template <class U> void STObject::Proxy<T>::assign(U&& u) { if (style_ == soeDEFAULT && u == value_type{}) { st_->makeFieldAbsent(*f_); return; } T* t; if (style_ == soeINVALID) t = dynamic_cast<T*>(st_->getPField(*f_, true)); else t = dynamic_cast<T*>(st_->makeFieldPresent(*f_)); assert(t); *t = std::forward<U>(u); } //------------------------------------------------------------------------------ template <class T> template <class U> std::enable_if_t<std::is_assignable_v<T, U>, STObject::ValueProxy<T>&> STObject::ValueProxy<T>::operator=(U&& u) { this->assign(std::forward<U>(u)); return *this; } template <class T> STObject::ValueProxy<T>::operator value_type() const { return this->value(); } template <class T> STObject::ValueProxy<T>::ValueProxy(STObject* st, TypedField<T> const* f) : Proxy<T>(st, f) { } //------------------------------------------------------------------------------ template <class T> STObject::OptionalProxy<T>::operator bool() const noexcept { return engaged(); } template <class T> auto STObject::OptionalProxy<T>::operator*() const -> value_type { return this->value(); } template <class T> STObject::OptionalProxy<T>::operator typename STObject::OptionalProxy< T>::optional_type() const { return optional_value(); } template <class T> typename STObject::OptionalProxy<T>::optional_type STObject::OptionalProxy<T>::operator~() const { return optional_value(); } template <class T> auto STObject::OptionalProxy<T>::operator=(std::nullopt_t const&) -> OptionalProxy& { disengage(); return *this; } template <class T> auto STObject::OptionalProxy<T>::operator=(optional_type&& v) -> OptionalProxy& { if (v) this->assign(std::move(*v)); else disengage(); return *this; } template <class T> auto STObject::OptionalProxy<T>::operator=(optional_type const& v) -> OptionalProxy& { if (v) this->assign(*v); else disengage(); return *this; } template <class T> template <class U> std::enable_if_t<std::is_assignable_v<T, U>, STObject::OptionalProxy<T>&> STObject::OptionalProxy<T>::operator=(U&& u) { this->assign(std::forward<U>(u)); return *this; } template <class T> STObject::OptionalProxy<T>::OptionalProxy(STObject* st, TypedField<T> const* f) : Proxy<T>(st, f) { } template <class T> bool STObject::OptionalProxy<T>::engaged() const noexcept { return this->style_ == soeDEFAULT || this->find() != nullptr; } template <class T> void STObject::OptionalProxy<T>::disengage() { if (this->style_ == soeREQUIRED || this->style_ == soeDEFAULT) Throw<STObject::FieldErr>( "Template field error '" + this->f_->getName() + "'"); if (this->style_ == soeINVALID) this->st_->delField(*this->f_); else this->st_->makeFieldAbsent(*this->f_); } template <class T> auto STObject::OptionalProxy<T>::optional_value() const -> optional_type { if (!engaged()) return std::nullopt; return this->value(); } //------------------------------------------------------------------------------ template <class T> typename T::value_type STObject::operator[](TypedField<T> const& f) const { return at(f); } template <class T> std::optional<std::decay_t<typename T::value_type>> STObject::operator[](OptionaledField<T> const& of) const { return at(of); } template <class T> inline auto STObject::operator[](TypedField<T> const& f) -> ValueProxy<T> { return at(f); } template <class T> inline auto STObject::operator[](OptionaledField<T> const& of) -> OptionalProxy<T> { return at(of); } template <class T> typename T::value_type STObject::at(TypedField<T> const& f) const { auto const b = peekAtPField(f); if (!b) // This is a free object (no constraints) // with no template Throw<STObject::FieldErr>("Missing field '" + f.getName() + "'"); auto const u = dynamic_cast<T const*>(b); if (!u) { assert(mType); assert(b->getSType() == STI_NOTPRESENT); if (mType->style(f) == soeOPTIONAL) Throw<STObject::FieldErr>("Missing field '" + f.getName() + "'"); assert(mType->style(f) == soeDEFAULT); // Handle the case where value_type is a // const reference, otherwise we return // the address of a temporary. static std::decay_t<typename T::value_type> const dv{}; return dv; } return u->value(); } template <class T> std::optional<std::decay_t<typename T::value_type>> STObject::at(OptionaledField<T> const& of) const { auto const b = peekAtPField(*of.f); if (!b) return std::nullopt; auto const u = dynamic_cast<T const*>(b); if (!u) { assert(mType); assert(b->getSType() == STI_NOTPRESENT); if (mType->style(*of.f) == soeOPTIONAL) return std::nullopt; assert(mType->style(*of.f) == soeDEFAULT); return typename T::value_type{}; } return u->value(); } template <class T> inline auto STObject::at(TypedField<T> const& f) -> ValueProxy<T> { return ValueProxy<T>(this, &f); } template <class T> inline auto STObject::at(OptionaledField<T> const& of) -> OptionalProxy<T> { return OptionalProxy<T>(this, of.f); } } // namespace ripple #endif
#pragma once #include <android/log.h> #define DEBUG 1 #define LOG_TAG "mpv" #define ALOGE(...) __android_log_print(ANDROID_LOG_ERROR, LOG_TAG, __VA_ARGS__) #if DEBUG #define ALOGV(...) __android_log_print(ANDROID_LOG_VERBOSE, LOG_TAG, __VA_ARGS__) #else #define ALOGV(...) #endif void die(const char *msg);
/** ****************************************************************************** * @file stm32f10x_fsmc.h * @author MCD Application Team * @version V3.5.0 * @date 11-March-2011 * @brief This file contains all the functions prototypes for the FSMC firmware * library. ****************************************************************************** * @attention * * THE PRESENT FIRMWARE WHICH IS FOR GUIDANCE ONLY AIMS AT PROVIDING CUSTOMERS * WITH CODING INFORMATION REGARDING THEIR PRODUCTS IN ORDER FOR THEM TO SAVE * TIME. AS A RESULT, STMICROELECTRONICS SHALL NOT BE HELD LIABLE FOR ANY * DIRECT, INDIRECT OR CONSEQUENTIAL DAMAGES WITH RESPECT TO ANY CLAIMS ARISING * FROM THE CONTENT OF SUCH FIRMWARE AND/OR THE USE MADE BY CUSTOMERS OF THE * CODING INFORMATION CONTAINED HEREIN IN CONNECTION WITH THEIR PRODUCTS. * * <h2><center>&copy; COPYRIGHT 2011 STMicroelectronics</center></h2> ****************************************************************************** */ /* Define to prevent recursive inclusion -------------------------------------*/ #ifndef __STM32F10x_FSMC_H #define __STM32F10x_FSMC_H #ifdef __cplusplus extern "C" { #endif /* Includes ------------------------------------------------------------------*/ #include "stm32f10x.h" /** @addtogroup STM32F10x_StdPeriph_Driver * @{ */ /** @addtogroup FSMC * @{ */ /** @defgroup FSMC_Exported_Types * @{ */ /** * @brief Timing parameters For NOR/SRAM Banks */ typedef struct { uint32_t FSMC_AddressSetupTime; /*!< Defines the number of HCLK cycles to configure the duration of the address setup time. This parameter can be a value between 0 and 0xF. @note: It is not used with synchronous NOR Flash memories. */ uint32_t FSMC_AddressHoldTime; /*!< Defines the number of HCLK cycles to configure the duration of the address hold time. This parameter can be a value between 0 and 0xF. @note: It is not used with synchronous NOR Flash memories.*/ uint32_t FSMC_DataSetupTime; /*!< Defines the number of HCLK cycles to configure the duration of the data setup time. This parameter can be a value between 0 and 0xFF. @note: It is used for SRAMs, ROMs and asynchronous multiplexed NOR Flash memories. */ uint32_t FSMC_BusTurnAroundDuration; /*!< Defines the number of HCLK cycles to configure the duration of the bus turnaround. This parameter can be a value between 0 and 0xF. @note: It is only used for multiplexed NOR Flash memories. */ uint32_t FSMC_CLKDivision; /*!< Defines the period of CLK clock output signal, expressed in number of HCLK cycles. This parameter can be a value between 1 and 0xF. @note: This parameter is not used for asynchronous NOR Flash, SRAM or ROM accesses. */ uint32_t FSMC_DataLatency; /*!< Defines the number of memory clock cycles to issue to the memory before getting the first data. The value of this parameter depends on the memory type as shown below: - It must be set to 0 in case of a CRAM - It is don't care in asynchronous NOR, SRAM or ROM accesses - It may assume a value between 0 and 0xF in NOR Flash memories with synchronous burst mode enable */ uint32_t FSMC_AccessMode; /*!< Specifies the asynchronous access mode. This parameter can be a value of @ref FSMC_Access_Mode */ }FSMC_NORSRAMTimingInitTypeDef; /** * @brief FSMC NOR/SRAM Init structure definition */ typedef struct { uint32_t FSMC_Bank; /*!< Specifies the NOR/SRAM memory bank that will be used. This parameter can be a value of @ref FSMC_NORSRAM_Bank */ uint32_t FSMC_DataAddressMux; /*!< Specifies whether the address and data values are multiplexed on the databus or not. This parameter can be a value of @ref FSMC_Data_Address_Bus_Multiplexing */ uint32_t FSMC_MemoryType; /*!< Specifies the type of external memory attached to the corresponding memory bank. This parameter can be a value of @ref FSMC_Memory_Type */ uint32_t FSMC_MemoryDataWidth; /*!< Specifies the external memory device width. This parameter can be a value of @ref FSMC_Data_Width */ uint32_t FSMC_BurstAccessMode; /*!< Enables or disables the burst access mode for Flash memory, valid only with synchronous burst Flash memories. This parameter can be a value of @ref FSMC_Burst_Access_Mode */ uint32_t FSMC_AsynchronousWait; /*!< Enables or disables wait signal during asynchronous transfers, valid only with asynchronous Flash memories. This parameter can be a value of @ref FSMC_AsynchronousWait */ uint32_t FSMC_WaitSignalPolarity; /*!< Specifies the wait signal polarity, valid only when accessing the Flash memory in burst mode. This parameter can be a value of @ref FSMC_Wait_Signal_Polarity */ uint32_t FSMC_WrapMode; /*!< Enables or disables the Wrapped burst access mode for Flash memory, valid only when accessing Flash memories in burst mode. This parameter can be a value of @ref FSMC_Wrap_Mode */ uint32_t FSMC_WaitSignalActive; /*!< Specifies if the wait signal is asserted by the memory one clock cycle before the wait state or during the wait state, valid only when accessing memories in burst mode. This parameter can be a value of @ref FSMC_Wait_Timing */ uint32_t FSMC_WriteOperation; /*!< Enables or disables the write operation in the selected bank by the FSMC. This parameter can be a value of @ref FSMC_Write_Operation */ uint32_t FSMC_WaitSignal; /*!< Enables or disables the wait-state insertion via wait signal, valid for Flash memory access in burst mode. This parameter can be a value of @ref FSMC_Wait_Signal */ uint32_t FSMC_ExtendedMode; /*!< Enables or disables the extended mode. This parameter can be a value of @ref FSMC_Extended_Mode */ uint32_t FSMC_WriteBurst; /*!< Enables or disables the write burst operation. This parameter can be a value of @ref FSMC_Write_Burst */ FSMC_NORSRAMTimingInitTypeDef* FSMC_ReadWriteTimingStruct; /*!< Timing Parameters for write and read access if the ExtendedMode is not used*/ FSMC_NORSRAMTimingInitTypeDef* FSMC_WriteTimingStruct; /*!< Timing Parameters for write access if the ExtendedMode is used*/ }FSMC_NORSRAMInitTypeDef; /** * @brief Timing parameters For FSMC NAND and PCCARD Banks */ typedef struct { uint32_t FSMC_SetupTime; /*!< Defines the number of HCLK cycles to setup address before the command assertion for NAND-Flash read or write access to common/Attribute or I/O memory space (depending on the memory space timing to be configured). This parameter can be a value between 0 and 0xFF.*/ uint32_t FSMC_WaitSetupTime; /*!< Defines the minimum number of HCLK cycles to assert the command for NAND-Flash read or write access to common/Attribute or I/O memory space (depending on the memory space timing to be configured). This parameter can be a number between 0x00 and 0xFF */ uint32_t FSMC_HoldSetupTime; /*!< Defines the number of HCLK clock cycles to hold address (and data for write access) after the command deassertion for NAND-Flash read or write access to common/Attribute or I/O memory space (depending on the memory space timing to be configured). This parameter can be a number between 0x00 and 0xFF */ uint32_t FSMC_HiZSetupTime; /*!< Defines the number of HCLK clock cycles during which the databus is kept in HiZ after the start of a NAND-Flash write access to common/Attribute or I/O memory space (depending on the memory space timing to be configured). This parameter can be a number between 0x00 and 0xFF */ }FSMC_NAND_PCCARDTimingInitTypeDef; /** * @brief FSMC NAND Init structure definition */ typedef struct { uint32_t FSMC_Bank; /*!< Specifies the NAND memory bank that will be used. This parameter can be a value of @ref FSMC_NAND_Bank */ uint32_t FSMC_Waitfeature; /*!< Enables or disables the Wait feature for the NAND Memory Bank. This parameter can be any value of @ref FSMC_Wait_feature */ uint32_t FSMC_MemoryDataWidth; /*!< Specifies the external memory device width. This parameter can be any value of @ref FSMC_Data_Width */ uint32_t FSMC_ECC; /*!< Enables or disables the ECC computation. This parameter can be any value of @ref FSMC_ECC */ uint32_t FSMC_ECCPageSize; /*!< Defines the page size for the extended ECC. This parameter can be any value of @ref FSMC_ECC_Page_Size */ uint32_t FSMC_TCLRSetupTime; /*!< Defines the number of HCLK cycles to configure the delay between CLE low and RE low. This parameter can be a value between 0 and 0xFF. */ uint32_t FSMC_TARSetupTime; /*!< Defines the number of HCLK cycles to configure the delay between ALE low and RE low. This parameter can be a number between 0x0 and 0xFF */ FSMC_NAND_PCCARDTimingInitTypeDef* FSMC_CommonSpaceTimingStruct; /*!< FSMC Common Space Timing */ FSMC_NAND_PCCARDTimingInitTypeDef* FSMC_AttributeSpaceTimingStruct; /*!< FSMC Attribute Space Timing */ }FSMC_NANDInitTypeDef; /** * @brief FSMC PCCARD Init structure definition */ typedef struct { uint32_t FSMC_Waitfeature; /*!< Enables or disables the Wait feature for the Memory Bank. This parameter can be any value of @ref FSMC_Wait_feature */ uint32_t FSMC_TCLRSetupTime; /*!< Defines the number of HCLK cycles to configure the delay between CLE low and RE low. This parameter can be a value between 0 and 0xFF. */ uint32_t FSMC_TARSetupTime; /*!< Defines the number of HCLK cycles to configure the delay between ALE low and RE low. This parameter can be a number between 0x0 and 0xFF */ FSMC_NAND_PCCARDTimingInitTypeDef* FSMC_CommonSpaceTimingStruct; /*!< FSMC Common Space Timing */ FSMC_NAND_PCCARDTimingInitTypeDef* FSMC_AttributeSpaceTimingStruct; /*!< FSMC Attribute Space Timing */ FSMC_NAND_PCCARDTimingInitTypeDef* FSMC_IOSpaceTimingStruct; /*!< FSMC IO Space Timing */ }FSMC_PCCARDInitTypeDef; /** * @} */ /** @defgroup FSMC_Exported_Constants * @{ */ /** @defgroup FSMC_NORSRAM_Bank * @{ */ #define FSMC_Bank1_NORSRAM1 ((uint32_t)0x00000000) #define FSMC_Bank1_NORSRAM2 ((uint32_t)0x00000002) #define FSMC_Bank1_NORSRAM3 ((uint32_t)0x00000004) #define FSMC_Bank1_NORSRAM4 ((uint32_t)0x00000006) /** * @} */ /** @defgroup FSMC_NAND_Bank * @{ */ #define FSMC_Bank2_NAND ((uint32_t)0x00000010) #define FSMC_Bank3_NAND ((uint32_t)0x00000100) /** * @} */ /** @defgroup FSMC_PCCARD_Bank * @{ */ #define FSMC_Bank4_PCCARD ((uint32_t)0x00001000) /** * @} */ #define IS_FSMC_NORSRAM_BANK(BANK) (((BANK) == FSMC_Bank1_NORSRAM1) || \ ((BANK) == FSMC_Bank1_NORSRAM2) || \ ((BANK) == FSMC_Bank1_NORSRAM3) || \ ((BANK) == FSMC_Bank1_NORSRAM4)) #define IS_FSMC_NAND_BANK(BANK) (((BANK) == FSMC_Bank2_NAND) || \ ((BANK) == FSMC_Bank3_NAND)) #define IS_FSMC_GETFLAG_BANK(BANK) (((BANK) == FSMC_Bank2_NAND) || \ ((BANK) == FSMC_Bank3_NAND) || \ ((BANK) == FSMC_Bank4_PCCARD)) #define IS_FSMC_IT_BANK(BANK) (((BANK) == FSMC_Bank2_NAND) || \ ((BANK) == FSMC_Bank3_NAND) || \ ((BANK) == FSMC_Bank4_PCCARD)) /** @defgroup NOR_SRAM_Controller * @{ */ /** @defgroup FSMC_Data_Address_Bus_Multiplexing * @{ */ #define FSMC_DataAddressMux_Disable ((uint32_t)0x00000000) #define FSMC_DataAddressMux_Enable ((uint32_t)0x00000002) #define IS_FSMC_MUX(MUX) (((MUX) == FSMC_DataAddressMux_Disable) || \ ((MUX) == FSMC_DataAddressMux_Enable)) /** * @} */ /** @defgroup FSMC_Memory_Type * @{ */ #define FSMC_MemoryType_SRAM ((uint32_t)0x00000000) #define FSMC_MemoryType_PSRAM ((uint32_t)0x00000004) #define FSMC_MemoryType_NOR ((uint32_t)0x00000008) #define IS_FSMC_MEMORY(MEMORY) (((MEMORY) == FSMC_MemoryType_SRAM) || \ ((MEMORY) == FSMC_MemoryType_PSRAM)|| \ ((MEMORY) == FSMC_MemoryType_NOR)) /** * @} */ /** @defgroup FSMC_Data_Width * @{ */ #define FSMC_MemoryDataWidth_8b ((uint32_t)0x00000000) #define FSMC_MemoryDataWidth_16b ((uint32_t)0x00000010) #define IS_FSMC_MEMORY_WIDTH(WIDTH) (((WIDTH) == FSMC_MemoryDataWidth_8b) || \ ((WIDTH) == FSMC_MemoryDataWidth_16b)) /** * @} */ /** @defgroup FSMC_Burst_Access_Mode * @{ */ #define FSMC_BurstAccessMode_Disable ((uint32_t)0x00000000) #define FSMC_BurstAccessMode_Enable ((uint32_t)0x00000100) #define IS_FSMC_BURSTMODE(STATE) (((STATE) == FSMC_BurstAccessMode_Disable) || \ ((STATE) == FSMC_BurstAccessMode_Enable)) /** * @} */ /** @defgroup FSMC_AsynchronousWait * @{ */ #define FSMC_AsynchronousWait_Disable ((uint32_t)0x00000000) #define FSMC_AsynchronousWait_Enable ((uint32_t)0x00008000) #define IS_FSMC_ASYNWAIT(STATE) (((STATE) == FSMC_AsynchronousWait_Disable) || \ ((STATE) == FSMC_AsynchronousWait_Enable)) /** * @} */ /** @defgroup FSMC_Wait_Signal_Polarity * @{ */ #define FSMC_WaitSignalPolarity_Low ((uint32_t)0x00000000) #define FSMC_WaitSignalPolarity_High ((uint32_t)0x00000200) #define IS_FSMC_WAIT_POLARITY(POLARITY) (((POLARITY) == FSMC_WaitSignalPolarity_Low) || \ ((POLARITY) == FSMC_WaitSignalPolarity_High)) /** * @} */ /** @defgroup FSMC_Wrap_Mode * @{ */ #define FSMC_WrapMode_Disable ((uint32_t)0x00000000) #define FSMC_WrapMode_Enable ((uint32_t)0x00000400) #define IS_FSMC_WRAP_MODE(MODE) (((MODE) == FSMC_WrapMode_Disable) || \ ((MODE) == FSMC_WrapMode_Enable)) /** * @} */ /** @defgroup FSMC_Wait_Timing * @{ */ #define FSMC_WaitSignalActive_BeforeWaitState ((uint32_t)0x00000000) #define FSMC_WaitSignalActive_DuringWaitState ((uint32_t)0x00000800) #define IS_FSMC_WAIT_SIGNAL_ACTIVE(ACTIVE) (((ACTIVE) == FSMC_WaitSignalActive_BeforeWaitState) || \ ((ACTIVE) == FSMC_WaitSignalActive_DuringWaitState)) /** * @} */ /** @defgroup FSMC_Write_Operation * @{ */ #define FSMC_WriteOperation_Disable ((uint32_t)0x00000000) #define FSMC_WriteOperation_Enable ((uint32_t)0x00001000) #define IS_FSMC_WRITE_OPERATION(OPERATION) (((OPERATION) == FSMC_WriteOperation_Disable) || \ ((OPERATION) == FSMC_WriteOperation_Enable)) /** * @} */ /** @defgroup FSMC_Wait_Signal * @{ */ #define FSMC_WaitSignal_Disable ((uint32_t)0x00000000) #define FSMC_WaitSignal_Enable ((uint32_t)0x00002000) #define IS_FSMC_WAITE_SIGNAL(SIGNAL) (((SIGNAL) == FSMC_WaitSignal_Disable) || \ ((SIGNAL) == FSMC_WaitSignal_Enable)) /** * @} */ /** @defgroup FSMC_Extended_Mode * @{ */ #define FSMC_ExtendedMode_Disable ((uint32_t)0x00000000) #define FSMC_ExtendedMode_Enable ((uint32_t)0x00004000) #define IS_FSMC_EXTENDED_MODE(MODE) (((MODE) == FSMC_ExtendedMode_Disable) || \ ((MODE) == FSMC_ExtendedMode_Enable)) /** * @} */ /** @defgroup FSMC_Write_Burst * @{ */ #define FSMC_WriteBurst_Disable ((uint32_t)0x00000000) #define FSMC_WriteBurst_Enable ((uint32_t)0x00080000) #define IS_FSMC_WRITE_BURST(BURST) (((BURST) == FSMC_WriteBurst_Disable) || \ ((BURST) == FSMC_WriteBurst_Enable)) /** * @} */ /** @defgroup FSMC_Address_Setup_Time * @{ */ #define IS_FSMC_ADDRESS_SETUP_TIME(TIME) ((TIME) <= 0xF) /** * @} */ /** @defgroup FSMC_Address_Hold_Time * @{ */ #define IS_FSMC_ADDRESS_HOLD_TIME(TIME) ((TIME) <= 0xF) /** * @} */ /** @defgroup FSMC_Data_Setup_Time * @{ */ #define IS_FSMC_DATASETUP_TIME(TIME) (((TIME) > 0) && ((TIME) <= 0xFF)) /** * @} */ /** @defgroup FSMC_Bus_Turn_around_Duration * @{ */ #define IS_FSMC_TURNAROUND_TIME(TIME) ((TIME) <= 0xF) /** * @} */ /** @defgroup FSMC_CLK_Division * @{ */ #define IS_FSMC_CLK_DIV(DIV) ((DIV) <= 0xF) /** * @} */ /** @defgroup FSMC_Data_Latency * @{ */ #define IS_FSMC_DATA_LATENCY(LATENCY) ((LATENCY) <= 0xF) /** * @} */ /** @defgroup FSMC_Access_Mode * @{ */ #define FSMC_AccessMode_A ((uint32_t)0x00000000) #define FSMC_AccessMode_B ((uint32_t)0x10000000) #define FSMC_AccessMode_C ((uint32_t)0x20000000) #define FSMC_AccessMode_D ((uint32_t)0x30000000) #define IS_FSMC_ACCESS_MODE(MODE) (((MODE) == FSMC_AccessMode_A) || \ ((MODE) == FSMC_AccessMode_B) || \ ((MODE) == FSMC_AccessMode_C) || \ ((MODE) == FSMC_AccessMode_D)) /** * @} */ /** * @} */ /** @defgroup NAND_PCCARD_Controller * @{ */ /** @defgroup FSMC_Wait_feature * @{ */ #define FSMC_Waitfeature_Disable ((uint32_t)0x00000000) #define FSMC_Waitfeature_Enable ((uint32_t)0x00000002) #define IS_FSMC_WAIT_FEATURE(FEATURE) (((FEATURE) == FSMC_Waitfeature_Disable) || \ ((FEATURE) == FSMC_Waitfeature_Enable)) /** * @} */ /** @defgroup FSMC_ECC * @{ */ #define FSMC_ECC_Disable ((uint32_t)0x00000000) #define FSMC_ECC_Enable ((uint32_t)0x00000040) #define IS_FSMC_ECC_STATE(STATE) (((STATE) == FSMC_ECC_Disable) || \ ((STATE) == FSMC_ECC_Enable)) /** * @} */ /** @defgroup FSMC_ECC_Page_Size * @{ */ #define FSMC_ECCPageSize_256Bytes ((uint32_t)0x00000000) #define FSMC_ECCPageSize_512Bytes ((uint32_t)0x00020000) #define FSMC_ECCPageSize_1024Bytes ((uint32_t)0x00040000) #define FSMC_ECCPageSize_2048Bytes ((uint32_t)0x00060000) #define FSMC_ECCPageSize_4096Bytes ((uint32_t)0x00080000) #define FSMC_ECCPageSize_8192Bytes ((uint32_t)0x000A0000) #define IS_FSMC_ECCPAGE_SIZE(SIZE) (((SIZE) == FSMC_ECCPageSize_256Bytes) || \ ((SIZE) == FSMC_ECCPageSize_512Bytes) || \ ((SIZE) == FSMC_ECCPageSize_1024Bytes) || \ ((SIZE) == FSMC_ECCPageSize_2048Bytes) || \ ((SIZE) == FSMC_ECCPageSize_4096Bytes) || \ ((SIZE) == FSMC_ECCPageSize_8192Bytes)) /** * @} */ /** @defgroup FSMC_TCLR_Setup_Time * @{ */ #define IS_FSMC_TCLR_TIME(TIME) ((TIME) <= 0xFF) /** * @} */ /** @defgroup FSMC_TAR_Setup_Time * @{ */ #define IS_FSMC_TAR_TIME(TIME) ((TIME) <= 0xFF) /** * @} */ /** @defgroup FSMC_Setup_Time * @{ */ #define IS_FSMC_SETUP_TIME(TIME) ((TIME) <= 0xFF) /** * @} */ /** @defgroup FSMC_Wait_Setup_Time * @{ */ #define IS_FSMC_WAIT_TIME(TIME) ((TIME) <= 0xFF) /** * @} */ /** @defgroup FSMC_Hold_Setup_Time * @{ */ #define IS_FSMC_HOLD_TIME(TIME) ((TIME) <= 0xFF) /** * @} */ /** @defgroup FSMC_HiZ_Setup_Time * @{ */ #define IS_FSMC_HIZ_TIME(TIME) ((TIME) <= 0xFF) /** * @} */ /** @defgroup FSMC_Interrupt_sources * @{ */ #define FSMC_IT_RisingEdge ((uint32_t)0x00000008) #define FSMC_IT_Level ((uint32_t)0x00000010) #define FSMC_IT_FallingEdge ((uint32_t)0x00000020) #define IS_FSMC_IT(IT) ((((IT) & (uint32_t)0xFFFFFFC7) == 0x00000000) && ((IT) != 0x00000000)) #define IS_FSMC_GET_IT(IT) (((IT) == FSMC_IT_RisingEdge) || \ ((IT) == FSMC_IT_Level) || \ ((IT) == FSMC_IT_FallingEdge)) /** * @} */ /** @defgroup FSMC_Flags * @{ */ #define FSMC_FLAG_RisingEdge ((uint32_t)0x00000001) #define FSMC_FLAG_Level ((uint32_t)0x00000002) #define FSMC_FLAG_FallingEdge ((uint32_t)0x00000004) #define FSMC_FLAG_FEMPT ((uint32_t)0x00000040) #define IS_FSMC_GET_FLAG(FLAG) (((FLAG) == FSMC_FLAG_RisingEdge) || \ ((FLAG) == FSMC_FLAG_Level) || \ ((FLAG) == FSMC_FLAG_FallingEdge) || \ ((FLAG) == FSMC_FLAG_FEMPT)) #define IS_FSMC_CLEAR_FLAG(FLAG) ((((FLAG) & (uint32_t)0xFFFFFFF8) == 0x00000000) && ((FLAG) != 0x00000000)) /** * @} */ /** * @} */ /** * @} */ /** @defgroup FSMC_Exported_Macros * @{ */ /** * @} */ /** @defgroup FSMC_Exported_Functions * @{ */ void FSMC_NORSRAMDeInit(uint32_t FSMC_Bank); void FSMC_NANDDeInit(uint32_t FSMC_Bank); void FSMC_PCCARDDeInit(void); void FSMC_NORSRAMInit(FSMC_NORSRAMInitTypeDef* FSMC_NORSRAMInitStruct); void FSMC_NANDInit(FSMC_NANDInitTypeDef* FSMC_NANDInitStruct); void FSMC_PCCARDInit(FSMC_PCCARDInitTypeDef* FSMC_PCCARDInitStruct); void FSMC_NORSRAMStructInit(FSMC_NORSRAMInitTypeDef* FSMC_NORSRAMInitStruct); void FSMC_NANDStructInit(FSMC_NANDInitTypeDef* FSMC_NANDInitStruct); void FSMC_PCCARDStructInit(FSMC_PCCARDInitTypeDef* FSMC_PCCARDInitStruct); void FSMC_NORSRAMCmd(uint32_t FSMC_Bank, FunctionalState NewState); void FSMC_NANDCmd(uint32_t FSMC_Bank, FunctionalState NewState); void FSMC_PCCARDCmd(FunctionalState NewState); void FSMC_NANDECCCmd(uint32_t FSMC_Bank, FunctionalState NewState); uint32_t FSMC_GetECC(uint32_t FSMC_Bank); void FSMC_ITConfig(uint32_t FSMC_Bank, uint32_t FSMC_IT, FunctionalState NewState); FlagStatus FSMC_GetFlagStatus(uint32_t FSMC_Bank, uint32_t FSMC_FLAG); void FSMC_ClearFlag(uint32_t FSMC_Bank, uint32_t FSMC_FLAG); ITStatus FSMC_GetITStatus(uint32_t FSMC_Bank, uint32_t FSMC_IT); void FSMC_ClearITPendingBit(uint32_t FSMC_Bank, uint32_t FSMC_IT); #ifdef __cplusplus } #endif #endif /*__STM32F10x_FSMC_H */ /** * @} */ /** * @} */ /** * @} */ /******************* (C) COPYRIGHT 2011 STMicroelectronics *****END OF FILE****/
/* URI Online Judge | 1050 DDD Adapted by Neilor Tonin, URI Brazil https://www.urionlinejudge.com.br/judge/en/problems/view/1050 Timelimit: 1 Read an integer number that is the code number for phone dialing. Then, print the destination according to the following table: 61 Brasilia 71 Salvador 11 Sao Paulo 21 Rio de Janeiro 32 Juiz de Fora 19 Campinas 27 Vitoria 31 Belo Horizonte If the input number isn’t found in the above table, the output must be: DDD nao cadastrado That means “DDD not found” in Portuguese language. Input The input consists in a unique integer number. Output Print the city name corresponding to the input DDD. Print DDD nao cadastrado if doesn't exist corresponding DDD to the typed number. @author Marcos Lima @profile https://www.urionlinejudge.com.br/judge/pt/profile/242402 @status Accepted @language C (gcc 4.8.5, -O2 -lm) [+0s] @time 0.000s @size 795 Bytes @submission 12/7/19, 1:07:34 PM */ #include <stdio.h> int main() { int n; scanf("%d", &n); switch (n) { case 11: printf("Sao Paulo\n"); break; case 19: printf("Campinas\n"); break; case 21: printf("Rio de Janeiro\n"); break; case 27: printf("Vitoria\n"); break; case 31: printf("Belo Horizonte\n"); break; case 32: printf("Juiz de Fora\n"); break; case 71: printf("Salvador\n"); break; case 61: printf("Brasilia\n"); break; default: printf("DDD nao cadastrado\n"); break; } return 0; }
/**************************************************************************** * drivers/wireless/nrf24l01.c * * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. The * ASF licenses this file to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance with the * License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations * under the License. * ****************************************************************************/ /* Features: * - Fixed length and dynamically sized payloads (1 - 32 bytes) * - Management of the 6 receiver pipes * - Configuration of each pipe: address, packet length, auto-acknowledge, * etc. * - Use a FIFO buffer to store the received packets * * Todo: * - Add support for payloads in ACK packets (?) * - Add compatibility with nRF24L01 (not +) hardware (?) */ /**************************************************************************** * Included Files ****************************************************************************/ #include <nuttx/config.h> #include <assert.h> #include <stdlib.h> #include <string.h> #include <errno.h> #include <stdio.h> #include <unistd.h> #include <poll.h> #include <debug.h> #include <fcntl.h> #include <nuttx/kmalloc.h> #include <nuttx/semaphore.h> #include <nuttx/signal.h> #ifdef CONFIG_WL_NRF24L01_RXSUPPORT # include <nuttx/wqueue.h> #endif #include <nuttx/wireless/nrf24l01.h> #include "nrf24l01.h" /**************************************************************************** * Pre-processor Definitions ****************************************************************************/ /* Configuration ************************************************************/ #ifndef CONFIG_WL_NRF24L01_DFLT_ADDR_WIDTH # define CONFIG_WL_NRF24L01_DFLT_ADDR_WIDTH 5 #endif #ifndef CONFIG_WL_NRF24L01_RXFIFO_LEN # define CONFIG_WL_NRF24L01_RXFIFO_LEN 128 #endif #if defined(CONFIG_WL_NRF24L01_RXSUPPORT) && !defined(CONFIG_SCHED_HPWORK) # error RX support requires CONFIG_SCHED_HPWORK #endif #ifdef CONFIG_WL_NRF24L01_CHECK_PARAMS # define CHECK_ARGS(cond) do { if (!(cond)) return -EINVAL; } while (0) #else # define CHECK_ARGS(cond) #endif /* NRF24L01 Definitions *****************************************************/ /* Default SPI bus frequency (in Hz). * Can go up to 10 Mbs according to datasheet. */ #define NRF24L01_SPIFREQ 9000000 /* power-down -> standby transition timing (in us). Note: this value is * probably larger than required. */ #define NRF24L01_TPD2STBY_DELAY 4500 /* Max time to wait for TX irq (in ms) */ #define NRF24L01_MAX_TX_IRQ_WAIT 2000 #define FIFO_PKTLEN_MASK 0x1F /* 5 ls bits used to store packet length */ #define FIFO_PKTLEN_SHIFT 0 #define FIFO_PIPENO_MASK 0xE0 /* 3 ms bits used to store pipe # */ #define FIFO_PIPENO_SHIFT 5 #define FIFO_PKTLEN(dev) \ (((dev->rx_fifo[dev->nxt_read] & FIFO_PKTLEN_MASK) >> FIFO_PKTLEN_SHIFT) + 1) #define FIFO_PIPENO(dev) \ (((dev->rx_fifo[dev->nxt_read] & FIFO_PIPENO_MASK) >> FIFO_PIPENO_SHIFT)) #define FIFO_HEADER(pktlen,pipeno) \ ((pktlen - 1) | (pipeno << FIFO_PIPENO_SHIFT)) #define DEV_NAME "/dev/nrf24l01" #define FL_AA_ENABLED (1 << 0) /**************************************************************************** * Private Data Types ****************************************************************************/ typedef enum { MODE_READ, MODE_WRITE } nrf24l01_access_mode_t; struct nrf24l01_dev_s { FAR struct spi_dev_s *spi; /* Reference to SPI bus device */ FAR struct nrf24l01_config_s *config; /* Board specific GPIO functions */ nrf24l01_state_t state; /* Current state of the nRF24L01 */ bool tx_payload_noack; /* TX without waiting for ACK */ uint8_t en_aa; /* Cache EN_AA register value */ uint8_t en_pipes; /* Cache EN_RXADDR register value */ bool ce_enabled; /* Cache the value of CE pin */ uint8_t lastxmitcount; /* Retransmit count of the last succeeded AA transmission */ uint8_t addrlen; /* Address width (3-5) */ uint8_t pipedatalen[NRF24L01_PIPE_COUNT]; uint8_t pipe0addr[NRF24L01_MAX_ADDR_LEN]; /* Configured address on pipe 0 */ uint8_t last_recvpipeno; sem_t sem_tx; bool tx_pending; /* Is userspace waiting for TX IRQ? - accessor * needs to hold lock on SPI bus */ #ifdef CONFIG_WL_NRF24L01_RXSUPPORT uint8_t *rx_fifo; /* Circular RX buffer. [pipe# / pkt_len] [packet data...] */ uint16_t fifo_len; /* Number of bytes stored in fifo */ uint16_t nxt_read; /* Next read index */ uint16_t nxt_write; /* Next write index */ sem_t sem_fifo; /* Protect access to rx fifo */ sem_t sem_rx; /* Wait for availability of received data */ struct work_s irq_work; /* Interrupt handling "bottom half" */ #endif uint8_t nopens; /* Number of times the device has been opened */ sem_t devsem; /* Ensures exclusive access to this structure */ FAR struct pollfd *pfd; /* Polled file descr (or NULL if any) */ }; /**************************************************************************** * Private Function Prototypes ****************************************************************************/ /* Low-level SPI helpers */ static inline void nrf24l01_configspi(FAR struct spi_dev_s *spi); static void nrf24l01_lock(FAR struct spi_dev_s *spi); static void nrf24l01_unlock(FAR struct spi_dev_s *spi); static uint8_t nrf24l01_access(FAR struct nrf24l01_dev_s *dev, nrf24l01_access_mode_t mode, uint8_t cmd, FAR uint8_t *buf, int length); static uint8_t nrf24l01_flush_rx(FAR struct nrf24l01_dev_s *dev); static uint8_t nrf24l01_flush_tx(FAR struct nrf24l01_dev_s *dev); /* Read register from nrf24 */ static uint8_t nrf24l01_readreg(FAR struct nrf24l01_dev_s *dev, uint8_t reg, FAR uint8_t *value, int len); /* Read single byte value from a register of nrf24 */ static uint8_t nrf24l01_readregbyte(FAR struct nrf24l01_dev_s *dev, uint8_t reg); static void nrf24l01_writeregbyte(FAR struct nrf24l01_dev_s *dev, uint8_t reg, uint8_t value); static uint8_t nrf24l01_setregbit(FAR struct nrf24l01_dev_s *dev, uint8_t reg, uint8_t value, bool set); static void nrf24l01_tostate(FAR struct nrf24l01_dev_s *dev, nrf24l01_state_t state); static int nrf24l01_irqhandler(FAR int irq, FAR void *context, FAR void *arg); static inline int nrf24l01_attachirq(FAR struct nrf24l01_dev_s *dev, xcpt_t isr, FAR void *arg); static int dosend(FAR struct nrf24l01_dev_s *dev, FAR const uint8_t *data, size_t datalen); static int nrf24l01_unregister(FAR struct nrf24l01_dev_s *dev); #ifdef CONFIG_WL_NRF24L01_RXSUPPORT static void fifoput(FAR struct nrf24l01_dev_s *dev, uint8_t pipeno, FAR uint8_t *buffer, uint8_t buflen); static uint8_t fifoget(FAR struct nrf24l01_dev_s *dev, FAR uint8_t *buffer, uint8_t buflen, FAR uint8_t *pipeno); static void nrf24l01_worker(FAR void *arg); #endif #ifdef CONFIG_DEBUG_WIRELESS static void binarycvt(FAR char *deststr, FAR const uint8_t *srcbin, size_t srclen); #endif /* POSIX API */ static int nrf24l01_open(FAR struct file *filep); static int nrf24l01_close(FAR struct file *filep); static ssize_t nrf24l01_read(FAR struct file *filep, FAR char *buffer, size_t buflen); static ssize_t nrf24l01_write(FAR struct file *filep, FAR const char *buffer, size_t buflen); static int nrf24l01_ioctl(FAR struct file *filep, int cmd, unsigned long arg); static int nrf24l01_poll(FAR struct file *filep, FAR struct pollfd *fds, bool setup); /**************************************************************************** * Private Data ****************************************************************************/ static const struct file_operations nrf24l01_fops = { nrf24l01_open, /* open */ nrf24l01_close, /* close */ nrf24l01_read, /* read */ nrf24l01_write, /* write */ NULL, /* seek */ nrf24l01_ioctl, /* ioctl */ nrf24l01_poll /* poll */ #ifndef CONFIG_DISABLE_PSEUDOFS_OPERATIONS , NULL /* unlink */ #endif }; /**************************************************************************** * Private Functions ****************************************************************************/ /**************************************************************************** * Name: nrf24l01_lock ****************************************************************************/ static void nrf24l01_lock(FAR struct spi_dev_s *spi) { /* Lock the SPI bus because there are multiple devices competing for the * SPI bus */ SPI_LOCK(spi, true); /* We have the lock. Now make sure that the SPI bus is configured for the * NRF24L01 (it might have gotten configured for a different device while * unlocked) */ SPI_SELECT(spi, SPIDEV_WIRELESS(0), true); SPI_SETMODE(spi, SPIDEV_MODE0); SPI_SETBITS(spi, 8); SPI_HWFEATURES(spi, 0); SPI_SETFREQUENCY(spi, NRF24L01_SPIFREQ); SPI_SELECT(spi, SPIDEV_WIRELESS(0), false); } /**************************************************************************** * Name: nrf24l01_unlock * * Description: * Un-lock the SPI bus after each transfer, possibly losing the current * configuration if we are sharing the SPI bus with other devices. * * Input Parameters: * spi - Reference to the SPI driver structure * * Returned Value: * None * * Assumptions: * ****************************************************************************/ static void nrf24l01_unlock(FAR struct spi_dev_s *spi) { /* Relinquish the SPI bus. */ SPI_LOCK(spi, false); } /**************************************************************************** * Name: nrf24l01_configspi * * Description: * Configure the SPI for use with the NRF24L01. * * Input Parameters: * spi - Reference to the SPI driver structure * * Returned Value: * None * * Assumptions: * ****************************************************************************/ static inline void nrf24l01_configspi(FAR struct spi_dev_s *spi) { /* Configure SPI for the NRF24L01 module. */ SPI_SELECT(spi, SPIDEV_WIRELESS(0), true); /* Useful ? */ SPI_SETMODE(spi, SPIDEV_MODE0); SPI_SETBITS(spi, 8); SPI_HWFEATURES(spi, 0); SPI_SETFREQUENCY(spi, NRF24L01_SPIFREQ); SPI_SELECT(spi, SPIDEV_WIRELESS(0), false); } /**************************************************************************** * Name: nrf24l01_select ****************************************************************************/ static inline void nrf24l01_select(struct nrf24l01_dev_s * dev) { SPI_SELECT(dev->spi, SPIDEV_WIRELESS(0), true); } /**************************************************************************** * Name: nrf24l01_deselect ****************************************************************************/ static inline void nrf24l01_deselect(struct nrf24l01_dev_s * dev) { SPI_SELECT(dev->spi, SPIDEV_WIRELESS(0), false); } /**************************************************************************** * Name: nrf24l01_access ****************************************************************************/ static uint8_t nrf24l01_access(FAR struct nrf24l01_dev_s *dev, nrf24l01_access_mode_t mode, uint8_t cmd, FAR uint8_t *buf, int length) { uint8_t status; /* Prepare SPI */ nrf24l01_select(dev); /* Transfer */ status = SPI_SEND(dev->spi, cmd); switch (mode) { case MODE_WRITE: if (length > 0) { SPI_SNDBLOCK(dev->spi, buf, length); } break; case MODE_READ: SPI_RECVBLOCK(dev->spi, buf, length); break; } nrf24l01_deselect(dev); return status; } /**************************************************************************** * Name: nrf24l01_flush_rx ****************************************************************************/ static inline uint8_t nrf24l01_flush_rx(FAR struct nrf24l01_dev_s *dev) { return nrf24l01_access(dev, MODE_WRITE, NRF24L01_FLUSH_RX, NULL, 0); } /**************************************************************************** * Name: nrf24l01_flush_tx ****************************************************************************/ static inline uint8_t nrf24l01_flush_tx(FAR struct nrf24l01_dev_s *dev) { return nrf24l01_access(dev, MODE_WRITE, NRF24L01_FLUSH_TX, NULL, 0); } /**************************************************************************** * Name: nrf24l01_readreg * * Description: * Read register from nrf24l01 * ****************************************************************************/ static inline uint8_t nrf24l01_readreg(FAR struct nrf24l01_dev_s *dev, uint8_t reg, FAR uint8_t *value, int len) { return nrf24l01_access(dev, MODE_READ, reg | NRF24L01_R_REGISTER, value, len); } /**************************************************************************** * Name: nrf24l01_readregbyte * * Description: * Read single byte value from a register of nrf24l01 * ****************************************************************************/ static inline uint8_t nrf24l01_readregbyte(FAR struct nrf24l01_dev_s *dev, uint8_t reg) { uint8_t val; nrf24l01_readreg(dev, reg, &val, 1); return val; } /**************************************************************************** * Name: nrf24l01_writereg * * Description: * Write value to a register of nrf24l01 * ****************************************************************************/ static inline int nrf24l01_writereg(FAR struct nrf24l01_dev_s *dev, uint8_t reg, FAR const uint8_t *value, int len) { return nrf24l01_access(dev, MODE_WRITE, reg | NRF24L01_W_REGISTER, (FAR uint8_t *)value, len); } /**************************************************************************** * Name: nrf24l01_writeregbyte * * Description: * Write single byte value to a register of nrf24l01 * ****************************************************************************/ static inline void nrf24l01_writeregbyte(FAR struct nrf24l01_dev_s *dev, uint8_t reg, uint8_t value) { nrf24l01_writereg(dev, reg, &value, 1); } /**************************************************************************** * Name: nrf24l01_setregbit ****************************************************************************/ static uint8_t nrf24l01_setregbit(FAR struct nrf24l01_dev_s *dev, uint8_t reg, uint8_t value, bool set) { uint8_t val; nrf24l01_readreg(dev, reg, &val, 1); if (set) { val |= value; } else { val &= ~value; } nrf24l01_writereg(dev, reg, &val, 1); return val; } /**************************************************************************** * Name: fifoput * * Description: * RX fifo mgt * ****************************************************************************/ #ifdef CONFIG_WL_NRF24L01_RXSUPPORT static void fifoput(FAR struct nrf24l01_dev_s *dev, uint8_t pipeno, FAR uint8_t *buffer, uint8_t buflen) { nxsem_wait(&dev->sem_fifo); while (dev->fifo_len + buflen + 1 > CONFIG_WL_NRF24L01_RXFIFO_LEN) { /* TODO: Set fifo overrun flag ! */ int skiplen = FIFO_PKTLEN(dev) + 1; dev->nxt_read = (dev->nxt_read + skiplen) % CONFIG_WL_NRF24L01_RXFIFO_LEN; dev->fifo_len -= skiplen; } dev->rx_fifo[dev->nxt_write] = FIFO_HEADER(buflen, pipeno); dev->nxt_write = (dev->nxt_write + 1) % CONFIG_WL_NRF24L01_RXFIFO_LEN; /* Adjust fifo bytes count */ dev->fifo_len += (buflen + 1); while (buflen--) { dev->rx_fifo[dev->nxt_write] = *(buffer++); dev->nxt_write = (dev->nxt_write + 1) % CONFIG_WL_NRF24L01_RXFIFO_LEN; } nxsem_post(&dev->sem_fifo); } /**************************************************************************** * Name: fifoget ****************************************************************************/ static uint8_t fifoget(FAR struct nrf24l01_dev_s *dev, FAR uint8_t *buffer, uint8_t buflen, FAR uint8_t *pipeno) { uint8_t pktlen; uint8_t i; nxsem_wait(&dev->sem_fifo); /* sem_rx contains count of inserted packets in FIFO, but FIFO can * overflow - fail smart. */ if (dev->fifo_len == 0) { pktlen = 0; goto no_data; } pktlen = FIFO_PKTLEN(dev); if (NULL != pipeno) { *pipeno = FIFO_PIPENO(dev); } dev->nxt_read = (dev->nxt_read + 1) % CONFIG_WL_NRF24L01_RXFIFO_LEN; for (i = 0; i < pktlen && i < buflen; i++) { *(buffer++) = dev->rx_fifo[dev->nxt_read]; dev->nxt_read = (dev->nxt_read + 1) % CONFIG_WL_NRF24L01_RXFIFO_LEN; } if (i < pktlen) { dev->nxt_read = (dev->nxt_read + pktlen - i) % CONFIG_WL_NRF24L01_RXFIFO_LEN; } /* Adjust fifo bytes count */ dev->fifo_len -= (pktlen + 1); no_data: nxsem_post(&dev->sem_fifo); return pktlen; } #endif /**************************************************************************** * Name: nrf24l01_irqhandler ****************************************************************************/ static int nrf24l01_irqhandler(int irq, FAR void *context, FAR void *arg) { FAR struct nrf24l01_dev_s *dev = (FAR struct nrf24l01_dev_s *)arg; wlinfo("*IRQ*\n"); #ifdef CONFIG_WL_NRF24L01_RXSUPPORT /* If RX is enabled we delegate the actual work to bottom-half handler */ work_queue(HPWORK, &dev->irq_work, nrf24l01_worker, dev, 0); #else /* Otherwise we simply wake up the send function */ nxsem_post(&dev->sem_tx); /* Wake up the send function */ #endif return OK; } /**************************************************************************** * Name: nrf24l01_attachirq * * Description: * Configure IRQ pin (falling edge) * ****************************************************************************/ static inline int nrf24l01_attachirq(FAR struct nrf24l01_dev_s *dev, xcpt_t isr, FAR void *arg) { return dev->config->irqattach(isr, arg); } /**************************************************************************** * Name: nrf24l01_chipenable ****************************************************************************/ static inline bool nrf24l01_chipenable(FAR struct nrf24l01_dev_s *dev, bool enable) { if (dev->ce_enabled != enable) { dev->config->chipenable(enable); dev->ce_enabled = enable; return !enable; } else { return enable; } } /**************************************************************************** * Name: nrf24l01_worker ****************************************************************************/ #ifdef CONFIG_WL_NRF24L01_RXSUPPORT static void nrf24l01_worker(FAR void *arg) { FAR struct nrf24l01_dev_s *dev = (FAR struct nrf24l01_dev_s *) arg; uint8_t status; uint8_t fifo_status; nrf24l01_lock(dev->spi); status = nrf24l01_readregbyte(dev, NRF24L01_STATUS); if (status & NRF24L01_RX_DR) { /* Put CE low */ bool ce = nrf24l01_chipenable(dev, false); bool has_data = false; wlinfo("RX_DR is set!\n"); /* Read and store all received payloads */ do { uint8_t pipeno; uint8_t pktlen; uint8_t buf[NRF24L01_MAX_PAYLOAD_LEN]; /* For each packet: * - Get pipe # * - Get payload length (either static or dynamic) * - Read payload content */ pipeno = (status & NRF24L01_RX_P_NO_MASK) >> NRF24L01_RX_P_NO_SHIFT; if (pipeno >= NRF24L01_PIPE_COUNT) /* 6=invalid 7=fifo empty */ { wlerr("invalid pipe rx: %d\n", (int)pipeno); nrf24l01_flush_rx(dev); break; } pktlen = dev->pipedatalen[pipeno]; if (NRF24L01_DYN_LENGTH == pktlen) { /* If dynamic length payload need to use R_RX_PL_WID command * to get actual length. */ nrf24l01_access(dev, MODE_READ, NRF24L01_R_RX_PL_WID, &pktlen, 1); } if (pktlen > NRF24L01_MAX_PAYLOAD_LEN) /* bad length */ { wlerr("invalid length in rx: %d\n", (int)pktlen); nrf24l01_flush_rx(dev); break; } /* Get payload content */ nrf24l01_access(dev, MODE_READ, NRF24L01_R_RX_PAYLOAD, buf, pktlen); fifoput(dev, pipeno, buf, pktlen); has_data = true; nxsem_post(&dev->sem_rx); /* Wake-up any thread waiting in recv */ status = nrf24l01_readreg(dev, NRF24L01_FIFO_STATUS, &fifo_status, 1); wlinfo("FIFO_STATUS=%02x\n", fifo_status); wlinfo("STATUS=%02x\n", status); } while ((fifo_status & NRF24L01_RX_EMPTY) == 0); if (dev->pfd && has_data) { dev->pfd->revents |= POLLIN; /* Data available for input */ wlinfo("Wake up polled fd\n"); nxsem_post(dev->pfd->sem); } /* Clear interrupt sources */ nrf24l01_writeregbyte(dev, NRF24L01_STATUS, NRF24L01_RX_DR); /* Restore CE */ nrf24l01_chipenable(dev, ce); } if (status & (NRF24L01_TX_DS | NRF24L01_MAX_RT)) { /* Confirm send */ nrf24l01_chipenable(dev, false); if (dev->tx_pending) { /* The actual work is done in the send function */ nxsem_post(&dev->sem_tx); } } if (dev->state == ST_RX) { /* Re-enable CE (to go back to RX mode state) */ nrf24l01_chipenable(dev, true); } nrf24l01_unlock(dev->spi); } #endif /**************************************************************************** * Name: nrf24l01_tostate ****************************************************************************/ static void nrf24l01_tostate(FAR struct nrf24l01_dev_s *dev, nrf24l01_state_t state) { nrf24l01_state_t oldstate = dev->state; if (oldstate == state) { return; } if (oldstate == ST_POWER_DOWN) { /* Leaving power down (note: new state cannot be power down here) */ nrf24l01_setregbit(dev, NRF24L01_CONFIG, NRF24L01_PWR_UP, true); nxsig_usleep(NRF24L01_TPD2STBY_DELAY); } /* Entering new state */ switch (state) { case ST_UNKNOWN: /* Power down the module here... */ case ST_POWER_DOWN: nrf24l01_chipenable(dev, false); nrf24l01_setregbit(dev, NRF24L01_CONFIG, NRF24L01_PWR_UP, false); break; case ST_STANDBY: nrf24l01_chipenable(dev, false); nrf24l01_setregbit(dev, NRF24L01_CONFIG, NRF24L01_PRIM_RX, false); break; #ifdef CONFIG_WL_NRF24L01_RXSUPPORT case ST_RX: nrf24l01_setregbit(dev, NRF24L01_CONFIG, NRF24L01_PRIM_RX, true); nrf24l01_chipenable(dev, true); break; #endif } dev->state = state; } /**************************************************************************** * Name: dosend ****************************************************************************/ static int dosend(FAR struct nrf24l01_dev_s *dev, FAR const uint8_t *data, size_t datalen) { uint8_t status; uint8_t obsvalue; uint8_t cmd; int ret; /* Store the current lifecycle state in order to restore it after transmit * done. */ nrf24l01_state_t prevstate = dev->state; nrf24l01_tostate(dev, ST_STANDBY); /* Flush old - can't harm */ nrf24l01_flush_tx(dev); /* Write payload - use different command depending on ACK setting */ cmd = dev->tx_payload_noack ? NRF24L01_W_TX_PAYLOAD_NOACK : NRF24L01_W_TX_PAYLOAD; nrf24l01_access(dev, MODE_WRITE, cmd, (FAR uint8_t *)data, datalen); dev->tx_pending = true; /* Free the SPI bus during the IRQ wait */ nrf24l01_unlock(dev->spi); /* Cause rising CE edge to start transmission */ nrf24l01_chipenable(dev, true); /* Wait for IRQ (TX_DS or MAX_RT) - but don't hang on lost IRQ */ ret = nxsem_tickwait(&dev->sem_tx, clock_systime_ticks(), MSEC2TICK(NRF24L01_MAX_TX_IRQ_WAIT)); /* Re-acquire the SPI bus */ nrf24l01_lock(dev->spi); dev->tx_pending = false; if (ret < 0) { wlerr("wait for irq failed\n"); nrf24l01_flush_tx(dev); goto out; } status = nrf24l01_readreg(dev, NRF24L01_OBSERVE_TX, &obsvalue, 1); if (status & NRF24L01_TX_DS) { /* Transmit OK */ ret = OK; dev->lastxmitcount = (obsvalue & NRF24L01_ARC_CNT_MASK) >> NRF24L01_ARC_CNT_SHIFT; wlinfo("Transmission OK (lastxmitcount=%d)\n", dev->lastxmitcount); } else if (status & NRF24L01_MAX_RT) { wlinfo("MAX_RT! (lastxmitcount=%d)\n", dev->lastxmitcount); ret = -ECOMM; dev->lastxmitcount = NRF24L01_XMIT_MAXRT; /* If no ACK packet is received the payload remains in TX fifo. We * need to flush it. */ nrf24l01_flush_tx(dev); } else { /* Unexpected... */ wlerr("ERROR: No TX_DS nor MAX_RT bit set in STATUS reg!\n"); ret = -EIO; } out: /* Clear interrupt sources */ nrf24l01_writeregbyte(dev, NRF24L01_STATUS, NRF24L01_TX_DS | NRF24L01_MAX_RT); /* Clear fifo */ nrf24l01_flush_tx(dev); /* Restore state */ nrf24l01_tostate(dev, prevstate); return ret; } /**************************************************************************** * Name: binarycvt ****************************************************************************/ #ifdef CONFIG_DEBUG_WIRELESS static void binarycvt(FAR char *deststr, FAR const uint8_t *srcbin, size_t srclen) { int i = 0; while (i < srclen) { sprintf(deststr + i * 2, "%02x", srcbin[i]); ++i; } *(deststr + i * 2) = '\0'; } #endif /**************************************************************************** * POSIX API ****************************************************************************/ /**************************************************************************** * Name: nrf24l01_open ****************************************************************************/ static int nrf24l01_open(FAR struct file *filep) { FAR struct inode *inode; FAR struct nrf24l01_dev_s *dev; int ret; wlinfo("Opening nRF24L01 dev\n"); DEBUGASSERT(filep); inode = filep->f_inode; DEBUGASSERT(inode && inode->i_private); dev = (FAR struct nrf24l01_dev_s *)inode->i_private; /* Get exclusive access to the driver data structure */ ret = nxsem_wait(&dev->devsem); if (ret < 0) { return ret; } /* Check if device is not already used */ if (dev->nopens > 0) { ret = -EBUSY; goto errout; } ret = nrf24l01_init(dev); if (!ret) { dev->nopens++; } errout: nxsem_post(&dev->devsem); return ret; } /**************************************************************************** * Name: nrf24l01_close ****************************************************************************/ static int nrf24l01_close(FAR struct file *filep) { FAR struct inode *inode; FAR struct nrf24l01_dev_s *dev; int ret; wlinfo("Closing nRF24L01 dev\n"); DEBUGASSERT(filep); inode = filep->f_inode; DEBUGASSERT(inode && inode->i_private); dev = (FAR struct nrf24l01_dev_s *)inode->i_private; /* Get exclusive access to the driver data structure */ ret = nxsem_wait(&dev->devsem); if (ret < 0) { return ret; } nrf24l01_changestate(dev, ST_POWER_DOWN); dev->nopens--; nxsem_post(&dev->devsem); return OK; } /**************************************************************************** * Name: nrf24l01_read ****************************************************************************/ static ssize_t nrf24l01_read(FAR struct file *filep, FAR char *buffer, size_t buflen) { #ifndef CONFIG_WL_NRF24L01_RXSUPPORT return -ENOSYS; #else FAR struct nrf24l01_dev_s *dev; FAR struct inode *inode; int ret; DEBUGASSERT(filep); inode = filep->f_inode; DEBUGASSERT(inode && inode->i_private); dev = (FAR struct nrf24l01_dev_s *)inode->i_private; ret = nxsem_wait(&dev->devsem); if (ret < 0) { return ret; } if (filep->f_oflags & O_NONBLOCK) { int packet_count; /* Test if data is ready */ ret = nxsem_get_value(&dev->sem_rx, &packet_count); if (ret) { goto errout; /* getvalue failed */ } if (!packet_count) { ret = -EWOULDBLOCK; /* don't wait for packets */ goto errout; } } ret = nrf24l01_recv(dev, (uint8_t *)buffer, buflen, &dev->last_recvpipeno); errout: nxsem_post(&dev->devsem); return ret; #endif } /**************************************************************************** * Name: nrf24l01_write ****************************************************************************/ static ssize_t nrf24l01_write(FAR struct file *filep, FAR const char *buffer, size_t buflen) { FAR struct nrf24l01_dev_s *dev; FAR struct inode *inode; int ret; DEBUGASSERT(filep); inode = filep->f_inode; DEBUGASSERT(inode && inode->i_private); dev = (FAR struct nrf24l01_dev_s *)inode->i_private; ret = nxsem_wait(&dev->devsem); if (ret < 0) { return ret; } ret = nrf24l01_send(dev, (const uint8_t *)buffer, buflen); nxsem_post(&dev->devsem); return ret; } /**************************************************************************** * Name: nrf24l01_ioctl ****************************************************************************/ static int nrf24l01_ioctl(FAR struct file *filep, int cmd, unsigned long arg) { FAR struct inode *inode; FAR struct nrf24l01_dev_s *dev; int ret; wlinfo("cmd: %d arg: %ld\n", cmd, arg); DEBUGASSERT(filep); inode = filep->f_inode; DEBUGASSERT(inode && inode->i_private); dev = (FAR struct nrf24l01_dev_s *)inode->i_private; /* Get exclusive access to the driver data structure */ ret = nxsem_wait(&dev->devsem); if (ret < 0) { return ret; } /* Process the IOCTL by command */ switch (cmd) { case WLIOC_SETRADIOFREQ: /* Set radio frequency. Arg: Pointer to * uint32_t frequency value */ { FAR uint32_t *ptr = (FAR uint32_t *)((uintptr_t)arg); DEBUGASSERT(ptr != NULL); nrf24l01_setradiofreq(dev, *ptr); } break; case WLIOC_GETRADIOFREQ: /* Get current radio frequency. arg: Pointer * to uint32_t frequency value */ { FAR uint32_t *ptr = (FAR uint32_t *)((uintptr_t)arg); DEBUGASSERT(ptr != NULL); *ptr = nrf24l01_getradiofreq(dev); } break; case NRF24L01IOC_SETTXADDR: /* Set current TX addr. arg: Pointer to * uint8_t array defining the address */ { FAR const uint8_t *addr = (FAR const uint8_t *)(arg); DEBUGASSERT(addr != NULL); nrf24l01_settxaddr(dev, addr); } break; case NRF24L01IOC_GETTXADDR: /* Get current TX addr. arg: Pointer to * uint8_t array defining the address */ { FAR uint8_t *addr = (FAR uint8_t *)(arg); DEBUGASSERT(addr != NULL); nrf24l01_gettxaddr(dev, addr); } break; case WLIOC_SETTXPOWER: /* Set current radio frequency. arg: Pointer * to int32_t, output power */ { FAR int32_t *ptr = (FAR int32_t *)(arg); DEBUGASSERT(ptr != NULL); nrf24l01_settxpower(dev, *ptr); } break; case WLIOC_GETTXPOWER: /* Get current radio frequency. arg: Pointer * to int32_t, output power */ { FAR int32_t *ptr = (FAR int32_t *)(arg); DEBUGASSERT(ptr != NULL); *ptr = nrf24l01_gettxpower(dev); } break; case NRF24L01IOC_SETRETRCFG: /* Set retransmit params. arg: Pointer * to nrf24l01_retrcfg_t */ { FAR nrf24l01_retrcfg_t *ptr = (FAR nrf24l01_retrcfg_t *)(arg); DEBUGASSERT(ptr != NULL); nrf24l01_setretransmit(dev, ptr->delay, ptr->count); } break; case NRF24L01IOC_GETRETRCFG: /* Get retransmit params. arg: Pointer * to nrf24l01_retrcfg_t */ ret = -ENOSYS; /* TODO */ break; case NRF24L01IOC_SETPIPESCFG: { int i; FAR nrf24l01_pipecfg_t **cfg_array = (FAR nrf24l01_pipecfg_t **)(arg); DEBUGASSERT(cfg_array != NULL); for (i = 0; i < NRF24L01_PIPE_COUNT; i++) { if (cfg_array[i]) { nrf24l01_setpipeconfig(dev, i, cfg_array[i]); } } } break; case NRF24L01IOC_GETPIPESCFG: { int i; FAR nrf24l01_pipecfg_t **cfg_array = (FAR nrf24l01_pipecfg_t **)(arg); DEBUGASSERT(cfg_array != NULL); for (i = 0; i < NRF24L01_PIPE_COUNT; i++) { if (cfg_array[i]) { nrf24l01_getpipeconfig(dev, i, cfg_array[i]); } } } break; case NRF24L01IOC_SETPIPESENABLED: { int i; uint8_t en_pipes; FAR uint8_t *en_pipesp = (FAR uint8_t *)(arg); DEBUGASSERT(en_pipesp != NULL); en_pipes = *en_pipesp; for (i = 0; i < NRF24L01_PIPE_COUNT; i++) { if ((dev->en_pipes & (1 << i)) != (en_pipes & (1 << i))) { nrf24l01_enablepipe(dev, i, en_pipes & (1 << i)); } } } break; case NRF24L01IOC_GETPIPESENABLED: { FAR uint8_t *en_pipesp = (FAR uint8_t *)(arg); DEBUGASSERT(en_pipesp != NULL); *en_pipesp = dev->en_pipes; break; } case NRF24L01IOC_SETDATARATE: { FAR nrf24l01_datarate_t *drp = (FAR nrf24l01_datarate_t *)(arg); DEBUGASSERT(drp != NULL); nrf24l01_setdatarate(dev, *drp); break; } case NRF24L01IOC_GETDATARATE: ret = -ENOSYS; /* TODO */ break; case NRF24L01IOC_SETADDRWIDTH: { FAR uint32_t *widthp = (FAR uint32_t *)(arg); DEBUGASSERT(widthp != NULL); nrf24l01_setaddrwidth(dev, *widthp); break; } case NRF24L01IOC_GETADDRWIDTH: { FAR int *widthp = (FAR int *)(arg); DEBUGASSERT(widthp != NULL); *widthp = (int)dev->addrlen; break; } case NRF24L01IOC_SETSTATE: { FAR nrf24l01_state_t *statep = (FAR nrf24l01_state_t *)(arg); DEBUGASSERT(statep != NULL); nrf24l01_changestate(dev, *statep); break; } case NRF24L01IOC_GETSTATE: { FAR nrf24l01_state_t *statep = (FAR nrf24l01_state_t *)(arg); DEBUGASSERT(statep != NULL); *statep = dev->state; break; } case NRF24L01IOC_GETLASTXMITCOUNT: { FAR uint32_t *xmitcntp = (FAR uint32_t *)(arg); DEBUGASSERT(xmitcntp != NULL); *xmitcntp = dev->lastxmitcount; break; } case NRF24L01IOC_GETLASTPIPENO: { FAR uint32_t *lastpipep = (FAR uint32_t *)(arg); DEBUGASSERT(lastpipep != NULL); *lastpipep = dev->last_recvpipeno; break; } case NRF24L01IOC_SETTXPAYLOADNOACK: { FAR uint32_t *tx_payload_noack = (FAR uint32_t *)(arg); DEBUGASSERT(tx_payload_noack != NULL); dev->tx_payload_noack = (*tx_payload_noack) > 0; break; } case NRF24L01IOC_GETTXPAYLOADNOACK: { FAR uint32_t *tx_payload_noack = (FAR uint32_t *)(arg); DEBUGASSERT(tx_payload_noack != NULL); *tx_payload_noack = dev->tx_payload_noack ? 1 : 0; break; } default: ret = -ENOTTY; break; } nxsem_post(&dev->devsem); return ret; } /**************************************************************************** * Name: nrf24l01_poll ****************************************************************************/ static int nrf24l01_poll(FAR struct file *filep, FAR struct pollfd *fds, bool setup) { #ifndef CONFIG_WL_NRF24L01_RXSUPPORT /* Polling is currently implemented for data input only */ return -ENOSYS; #else FAR struct inode *inode; FAR struct nrf24l01_dev_s *dev; int ret; wlinfo("setup: %d\n", (int)setup); DEBUGASSERT(filep && fds); inode = filep->f_inode; DEBUGASSERT(inode && inode->i_private); dev = (FAR struct nrf24l01_dev_s *)inode->i_private; /* Exclusive access */ ret = nxsem_wait(&dev->devsem); if (ret < 0) { return ret; } /* Are we setting up the poll? Or tearing it down? */ if (setup) { /* Ignore waits that do not include POLLIN */ if ((fds->events & POLLIN) == 0) { ret = -EDEADLK; goto errout; } /* Check if we can accept this poll. * For now, only one thread can poll the device at any time * (shorter / simpler code) */ if (dev->pfd) { ret = -EBUSY; goto errout; } dev->pfd = fds; /* Is there is already data in the fifo? then trigger POLLIN now - * don't wait for RX. */ nxsem_wait(&dev->sem_fifo); if (dev->fifo_len > 0) { dev->pfd->revents |= POLLIN; /* Data available for input */ nxsem_post(dev->pfd->sem); } nxsem_post(&dev->sem_fifo); } else /* Tear it down */ { dev->pfd = NULL; } errout: nxsem_post(&dev->devsem); return ret; #endif } /**************************************************************************** * Name: nrf24l01_unregister ****************************************************************************/ static int nrf24l01_unregister(FAR struct nrf24l01_dev_s *dev) { CHECK_ARGS(dev); /* Release IRQ */ nrf24l01_attachirq(dev, NULL, NULL); /* Free memory */ #ifdef CONFIG_WL_NRF24L01_RXSUPPORT kmm_free(dev->rx_fifo); #endif kmm_free(dev); return OK; } /**************************************************************************** * Public Functions ****************************************************************************/ /**************************************************************************** * Name: nrf24l01_register ****************************************************************************/ int nrf24l01_register(FAR struct spi_dev_s *spi, FAR struct nrf24l01_config_s *cfg) { FAR struct nrf24l01_dev_s *dev; int ret = OK; #ifdef CONFIG_WL_NRF24L01_RXSUPPORT FAR uint8_t *rx_fifo; #endif DEBUGASSERT((spi != NULL) & (cfg != NULL)); if ((dev = kmm_zalloc(sizeof(struct nrf24l01_dev_s))) == NULL) { return -ENOMEM; } dev->spi = spi; dev->config = cfg; dev->state = ST_UNKNOWN; dev->ce_enabled = false; nxsem_init(&(dev->devsem), 0, 1); nxsem_init(&dev->sem_tx, 0, 0); nxsem_set_protocol(&dev->sem_tx, SEM_PRIO_NONE); #ifdef CONFIG_WL_NRF24L01_RXSUPPORT if ((rx_fifo = kmm_malloc(CONFIG_WL_NRF24L01_RXFIFO_LEN)) == NULL) { kmm_free(dev); return -ENOMEM; } dev->rx_fifo = rx_fifo; nxsem_init(&(dev->sem_fifo), 0, 1); nxsem_init(&(dev->sem_rx), 0, 0); nxsem_set_protocol(&dev->sem_rx, SEM_PRIO_NONE); #endif /* Configure IRQ pin (falling edge) */ nrf24l01_attachirq(dev, nrf24l01_irqhandler, dev); /* Register the device as an input device */ wlinfo("Registering " DEV_NAME "\n"); ret = register_driver(DEV_NAME, &nrf24l01_fops, 0666, dev); if (ret < 0) { wlerr("ERROR: register_driver() failed: %d\n", ret); nrf24l01_unregister(dev); } return ret; } /**************************************************************************** * Name: nrf24l01_init * * Description: * (Re)set the device in a default initial state * ****************************************************************************/ int nrf24l01_init(FAR struct nrf24l01_dev_s *dev) { int ret = OK; uint8_t features; CHECK_ARGS(dev); nrf24l01_lock(dev->spi); /* Configure the SPI parameters before communicating */ nrf24l01_configspi(dev->spi); /* Enable features in hardware: dynamic payload length + sending without * expecting ACK */ nrf24l01_writeregbyte(dev, NRF24L01_FEATURE, NRF24L01_EN_DPL | NRF24L01_EN_DYN_ACK); features = nrf24l01_readregbyte(dev, NRF24L01_FEATURE); if (0 == features) { /* The ACTIVATE instruction is not documented in the nRF24L01+ docs. * However it is referenced / described by many sources on Internet, * * Is it for nRF24L01 (not +) hardware ? */ uint8_t v = 0x73; nrf24l01_access(dev, MODE_WRITE, NRF24L01_ACTIVATE, &v, 1); features = nrf24l01_readregbyte(dev, NRF24L01_FEATURE); if (0 == features) { /* If FEATURES reg is still unset here, consider there is no * actual hardware. */ ret = -ENODEV; goto out; } } /* Set initial state */ nrf24l01_tostate(dev, ST_POWER_DOWN); /* Disable all pipes */ dev->en_pipes = 0; nrf24l01_writeregbyte(dev, NRF24L01_EN_RXADDR, 0); /* Set addr width to default */ dev->addrlen = CONFIG_WL_NRF24L01_DFLT_ADDR_WIDTH; nrf24l01_writeregbyte(dev, NRF24L01_SETUP_AW, CONFIG_WL_NRF24L01_DFLT_ADDR_WIDTH - 2); /* Get pipe #0 addr */ nrf24l01_readreg(dev, NRF24L01_RX_ADDR_P0, dev->pipe0addr, dev->addrlen); dev->en_aa = nrf24l01_readregbyte(dev, NRF24L01_EN_AA); /* Flush HW fifo */ nrf24l01_flush_rx(dev); nrf24l01_flush_tx(dev); /* Clear interrupt sources (useful ?) */ nrf24l01_writeregbyte(dev, NRF24L01_STATUS, NRF24L01_RX_DR | NRF24L01_TX_DS | NRF24L01_MAX_RT); out: nrf24l01_unlock(dev->spi); return ret; } /**************************************************************************** * Name: nrf24l01_setpipeconfig ****************************************************************************/ int nrf24l01_setpipeconfig(FAR struct nrf24l01_dev_s *dev, unsigned int pipeno, FAR const nrf24l01_pipecfg_t *pipecfg) { bool dynlength; bool en_aa; int addrlen; CHECK_ARGS(dev && pipecfg && pipeno < NRF24L01_PIPE_COUNT); dynlength = (pipecfg->payload_length == NRF24L01_DYN_LENGTH); /* Need to enable AA to enable dynamic length payload */ en_aa = dynlength || pipecfg->en_aa; nrf24l01_lock(dev->spi); /* Set addr * Pipe 0 & 1 are the only ones to have a full length address. */ addrlen = (pipeno <= 1) ? dev->addrlen : 1; nrf24l01_writereg(dev, NRF24L01_RX_ADDR_P0 + pipeno, pipecfg->rx_addr, addrlen); /* Auto ack */ if (en_aa) { dev->en_aa |= 1 << pipeno; } else { dev->en_aa &= ~(1 << pipeno); } nrf24l01_setregbit(dev, NRF24L01_EN_AA, 1 << pipeno, en_aa); /* Payload config */ nrf24l01_setregbit(dev, NRF24L01_DYNPD, 1 << pipeno, dynlength); if (!dynlength) { nrf24l01_writeregbyte(dev, NRF24L01_RX_PW_P0 + pipeno, pipecfg->payload_length); } nrf24l01_unlock(dev->spi); dev->pipedatalen[pipeno] = pipecfg->payload_length; return OK; } /**************************************************************************** * Name: nrf24l01_getpipeconfig ****************************************************************************/ int nrf24l01_getpipeconfig(FAR struct nrf24l01_dev_s *dev, unsigned int pipeno, FAR nrf24l01_pipecfg_t *pipecfg) { bool dynlength; int addrlen; CHECK_ARGS(dev && pipecfg && pipeno < NRF24L01_PIPE_COUNT); nrf24l01_lock(dev->spi); /* Get pipe address. * Pipe 0 & 1 are the only ones to have a full length address. */ addrlen = (pipeno <= 1) ? dev->addrlen : 1; nrf24l01_readreg(dev, NRF24L01_RX_ADDR_P0 + pipeno, pipecfg->rx_addr, addrlen); /* Auto ack */ pipecfg->en_aa = ((nrf24l01_readregbyte(dev, NRF24L01_EN_AA) & (1 << pipeno)) != 0); /* Payload config */ dynlength = ((nrf24l01_readregbyte(dev, NRF24L01_DYNPD) & (1 << pipeno)) != 0); if (dynlength) { pipecfg->payload_length = NRF24L01_DYN_LENGTH; } else { pipecfg->payload_length = nrf24l01_readregbyte(dev, NRF24L01_RX_PW_P0 + pipeno); } nrf24l01_unlock(dev->spi); return OK; } /**************************************************************************** * Name: nrf24l01_enablepipe ****************************************************************************/ int nrf24l01_enablepipe(FAR struct nrf24l01_dev_s *dev, unsigned int pipeno, bool enable) { CHECK_ARGS(dev && pipeno < NRF24L01_PIPE_COUNT); uint8_t rxaddrval; uint8_t pipemask = 1 << pipeno; nrf24l01_lock(dev->spi); /* Enable pipe on nRF24L01 */ rxaddrval = nrf24l01_readregbyte(dev, NRF24L01_EN_RXADDR); if (enable) { rxaddrval |= pipemask; } else { rxaddrval &= ~pipemask; } nrf24l01_writeregbyte(dev, NRF24L01_EN_RXADDR, rxaddrval); nrf24l01_unlock(dev->spi); /* Update cached value */ dev->en_pipes = rxaddrval; return OK; } /**************************************************************************** * Name: nrf24l01_settxaddr ****************************************************************************/ int nrf24l01_settxaddr(FAR struct nrf24l01_dev_s *dev, FAR const uint8_t *txaddr) { CHECK_ARGS(dev && txaddr); nrf24l01_lock(dev->spi); nrf24l01_writereg(dev, NRF24L01_TX_ADDR, txaddr, dev->addrlen); nrf24l01_unlock(dev->spi); return OK; } /**************************************************************************** * Name: nrf24l01_gettxaddr ****************************************************************************/ int nrf24l01_gettxaddr(FAR struct nrf24l01_dev_s *dev, FAR uint8_t *txaddr) { CHECK_ARGS(dev && txaddr); nrf24l01_lock(dev->spi); nrf24l01_readreg(dev, NRF24L01_TX_ADDR, txaddr, dev->addrlen); nrf24l01_unlock(dev->spi); return OK; } /**************************************************************************** * Name: nrf24l01_setretransmit ****************************************************************************/ int nrf24l01_setretransmit(FAR struct nrf24l01_dev_s *dev, nrf24l01_retransmit_delay_t retrdelay, uint8_t retrcount) { uint8_t val; CHECK_ARGS(dev && retrcount <= NRF24L01_MAX_XMIT_RETR); val = (retrdelay << NRF24L01_ARD_SHIFT) | (retrcount << NRF24L01_ARC_SHIFT); nrf24l01_lock(dev->spi); nrf24l01_writeregbyte(dev, NRF24L01_SETUP_RETR, val); nrf24l01_unlock(dev->spi); return OK; } /**************************************************************************** * Name: nrf24l01_settxpower ****************************************************************************/ int nrf24l01_settxpower(FAR struct nrf24l01_dev_s *dev, int outpower) { uint8_t value; uint8_t hwpow; /* RF_PWR value <-> Output power in dBm * * '00' – -18dBm * '01' – -12dBm * '10' – -6dBm * '11' – 0dBm */ switch (outpower) { case 0: hwpow = 3 << NRF24L01_RF_PWR_SHIFT; break; case -6: hwpow = 2 << NRF24L01_RF_PWR_SHIFT; break; case -12: hwpow = 1 << NRF24L01_RF_PWR_SHIFT; break; case -18: hwpow = 0; break; default: return -EINVAL; } nrf24l01_lock(dev->spi); value = nrf24l01_readregbyte(dev, NRF24L01_RF_SETUP); value &= ~(NRF24L01_RF_PWR_MASK); value |= hwpow; nrf24l01_writeregbyte(dev, NRF24L01_RF_SETUP, value); nrf24l01_unlock(dev->spi); return OK; } /**************************************************************************** * Name: nrf24l01_gettxpower ****************************************************************************/ int nrf24l01_gettxpower(FAR struct nrf24l01_dev_s *dev) { uint8_t value; int powers[] = { -18, -12, -6, 0 }; nrf24l01_lock(dev->spi); value = nrf24l01_readregbyte(dev, NRF24L01_RF_SETUP); nrf24l01_unlock(dev->spi); value = (value & NRF24L01_RF_PWR_MASK) >> NRF24L01_RF_PWR_SHIFT; return powers[value]; } /**************************************************************************** * Name: nrf24l01_setdatarate ****************************************************************************/ int nrf24l01_setdatarate(FAR struct nrf24l01_dev_s *dev, nrf24l01_datarate_t datarate) { uint8_t value; nrf24l01_lock(dev->spi); value = nrf24l01_readregbyte(dev, NRF24L01_RF_SETUP); value &= ~(NRF24L01_RF_DR_HIGH | NRF24L01_RF_DR_LOW); switch (datarate) { case RATE_1Mbps: break; case RATE_2Mbps: value |= NRF24L01_RF_DR_HIGH; break; case RATE_250kbps: value |= NRF24L01_RF_DR_LOW; break; } nrf24l01_writeregbyte(dev, NRF24L01_RF_SETUP, value); nrf24l01_unlock(dev->spi); return OK; } /**************************************************************************** * Name: nrf24l01_setradiofreq ****************************************************************************/ int nrf24l01_setradiofreq(FAR struct nrf24l01_dev_s *dev, uint32_t freq) { uint8_t value; CHECK_ARGS(dev && freq >= NRF24L01_MIN_FREQ && freq <= NRF24L01_MAX_FREQ); value = freq - NRF24L01_MIN_FREQ; nrf24l01_lock(dev->spi); nrf24l01_writeregbyte(dev, NRF24L01_RF_CH, value); nrf24l01_unlock(dev->spi); return OK; } /**************************************************************************** * Name: nrf24l01_getradiofreq ****************************************************************************/ uint32_t nrf24l01_getradiofreq(FAR struct nrf24l01_dev_s *dev) { int rffreq; CHECK_ARGS(dev); nrf24l01_lock(dev->spi); rffreq = (int)nrf24l01_readregbyte(dev, NRF24L01_RF_CH); nrf24l01_unlock(dev->spi); return rffreq + NRF24L01_MIN_FREQ; } /**************************************************************************** * Name: nrf24l01_setaddrwidth ****************************************************************************/ int nrf24l01_setaddrwidth(FAR struct nrf24l01_dev_s *dev, uint32_t width) { CHECK_ARGS(dev && width <= NRF24L01_MAX_ADDR_LEN && width >= NRF24L01_MIN_ADDR_LEN); nrf24l01_lock(dev->spi); nrf24l01_writeregbyte(dev, NRF24L01_SETUP_AW, width - 2); nrf24l01_unlock(dev->spi); dev->addrlen = width; return OK; } /**************************************************************************** * Name: nrf24l01_changestate ****************************************************************************/ int nrf24l01_changestate(FAR struct nrf24l01_dev_s *dev, nrf24l01_state_t state) { nrf24l01_lock(dev->spi); nrf24l01_tostate(dev, state); nrf24l01_unlock(dev->spi); return OK; } /**************************************************************************** * Name: nrf24l01_send ****************************************************************************/ int nrf24l01_send(FAR struct nrf24l01_dev_s *dev, FAR const uint8_t *data, size_t datalen) { int ret; CHECK_ARGS(dev && data && datalen <= NRF24L01_MAX_PAYLOAD_LEN); nrf24l01_lock(dev->spi); ret = dosend(dev, data, datalen); nrf24l01_unlock(dev->spi); return ret; } /**************************************************************************** * Name: nrf24l01_sendto ****************************************************************************/ int nrf24l01_sendto(FAR struct nrf24l01_dev_s *dev, FAR const uint8_t *data, size_t datalen, FAR const uint8_t *destaddr) { bool pipeaddrchg = false; int ret; nrf24l01_lock(dev->spi); /* If AA is enabled (pipe 0 is active and its AA flag is set) and the dest * addr is not the current pipe 0 addr we need to change pipe 0 addr in * order to receive the ACK packet. */ if ((dev->en_aa & 1) && (memcmp(destaddr, dev->pipe0addr, dev->addrlen))) { wlinfo("Change pipe #0 addr to dest addr\n"); nrf24l01_writereg(dev, NRF24L01_RX_ADDR_P0, destaddr, NRF24L01_MAX_ADDR_LEN); pipeaddrchg = true; } ret = dosend(dev, data, datalen); if (pipeaddrchg) { /* Restore pipe #0 addr */ nrf24l01_writereg(dev, NRF24L01_RX_ADDR_P0, dev->pipe0addr, NRF24L01_MAX_ADDR_LEN); wlinfo("Pipe #0 default addr restored\n"); } nrf24l01_unlock(dev->spi); return ret; } /**************************************************************************** * Name: nrf24l01_lastxmitcount ****************************************************************************/ int nrf24l01_lastxmitcount(FAR struct nrf24l01_dev_s *dev) { return dev->lastxmitcount; } /**************************************************************************** * Name: nrf24l01_recv ****************************************************************************/ #ifdef CONFIG_WL_NRF24L01_RXSUPPORT ssize_t nrf24l01_recv(FAR struct nrf24l01_dev_s *dev, FAR uint8_t *buffer, size_t buflen, FAR uint8_t *recvpipe) { int ret = nxsem_wait(&dev->sem_rx); if (ret < 0) { return ret; } return fifoget(dev, buffer, buflen, recvpipe); } #endif /**************************************************************************** * Name: nrf24l01_dumpregs ****************************************************************************/ #ifdef CONFIG_DEBUG_WIRELESS void nrf24l01_dumpregs(FAR struct nrf24l01_dev_s *dev) { uint8_t addr[NRF24L01_MAX_ADDR_LEN]; char addrstr[NRF24L01_MAX_ADDR_LEN * 2 +1]; syslog(LOG_INFO, "CONFIG: %02x\n", nrf24l01_readregbyte(dev, NRF24L01_CONFIG)); syslog(LOG_INFO, "EN_AA: %02x\n", nrf24l01_readregbyte(dev, NRF24L01_EN_AA)); syslog(LOG_INFO, "EN_RXADDR: %02x\n", nrf24l01_readregbyte(dev, NRF24L01_EN_RXADDR)); syslog(LOG_INFO, "SETUP_AW: %02x\n", nrf24l01_readregbyte(dev, NRF24L01_SETUP_AW)); syslog(LOG_INFO, "SETUP_RETR:%02x\n", nrf24l01_readregbyte(dev, NRF24L01_SETUP_RETR)); syslog(LOG_INFO, "RF_CH: %02x\n", nrf24l01_readregbyte(dev, NRF24L01_RF_CH)); syslog(LOG_INFO, "RF_SETUP: %02x\n", nrf24l01_readregbyte(dev, NRF24L01_RF_SETUP)); syslog(LOG_INFO, "STATUS: %02x\n", nrf24l01_readregbyte(dev, NRF24L01_STATUS)); syslog(LOG_INFO, "OBS_TX: %02x\n", nrf24l01_readregbyte(dev, NRF24L01_OBSERVE_TX)); nrf24l01_readreg(dev, NRF24L01_TX_ADDR, addr, dev->addrlen); binarycvt(addrstr, addr, dev->addrlen); syslog(LOG_INFO, "TX_ADDR: %s\n", addrstr); syslog(LOG_INFO, "CD: %02x\n", nrf24l01_readregbyte(dev, NRF24L01_CD)); syslog(LOG_INFO, "RX_PW_P0: %02x\n", nrf24l01_readregbyte(dev, NRF24L01_RX_PW_P0)); syslog(LOG_INFO, "RX_PW_P1: %02x\n", nrf24l01_readregbyte(dev, NRF24L01_RX_PW_P1)); syslog(LOG_INFO, "RX_PW_P2: %02x\n", nrf24l01_readregbyte(dev, NRF24L01_RX_PW_P2)); syslog(LOG_INFO, "RX_PW_P3: %02x\n", nrf24l01_readregbyte(dev, NRF24L01_RX_PW_P3)); syslog(LOG_INFO, "RX_PW_P4: %02x\n", nrf24l01_readregbyte(dev, NRF24L01_RX_PW_P4)); syslog(LOG_INFO, "RX_PW_P5: %02x\n", nrf24l01_readregbyte(dev, NRF24L01_RX_PW_P5)); syslog(LOG_INFO, "FIFO_STAT: %02x\n", nrf24l01_readregbyte(dev, NRF24L01_FIFO_STATUS)); syslog(LOG_INFO, "DYNPD: %02x\n", nrf24l01_readregbyte(dev, NRF24L01_DYNPD)); syslog(LOG_INFO, "FEATURE: %02x\n", nrf24l01_readregbyte(dev, NRF24L01_FEATURE)); } #endif /* CONFIG_DEBUG_WIRELESS */ /**************************************************************************** * Name: nrf24l01_dumprxfifo ****************************************************************************/ #if defined(CONFIG_DEBUG_WIRELESS) && defined(CONFIG_WL_NRF24L01_RXSUPPORT) void nrf24l01_dumprxfifo(FAR struct nrf24l01_dev_s *dev) { syslog(LOG_INFO, "bytes count: %d\n", dev->fifo_len); syslog(LOG_INFO, "next read: %d, next write: %d\n", dev->nxt_read, dev-> nxt_write); } #endif /* CONFIG_DEBUG_WIRELESS && CONFIG_WL_NRF24L01_RXSUPPORT */
///////////////////////////////////////////////////////////////////////////////////////////// // Copyright 2017 Intel Corporation // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. ///////////////////////////////////////////////////////////////////////////////////////////// #ifndef __CPUT_DX11_H__ #define __CPUT_DX11_H__ #include <stdio.h> // include base headers we'll need #include "CPUTWindowWin.h" #include "CPUT.h" #include "CPUTMath.h" #include "CPUTEventHandler.h" #include "CPUTGuiControllerDX11.h" // CPUT objects #include "CPUTMeshDX11.h" #include "CPUTModelDX11.h" #include "CPUTAssetSetDX11.h" #include "CPUTAssetLibraryDX11.h" #include "CPUTCamera.h" #include "CPUTLight.h" #include "CPUTMaterialDX11.h" // include all DX11 headers needed #include <d3d11.h> #include <d3DX11.h> #include <D3DX11async.h> // for D3DX11CompileFromFile() #include <D3DCompiler.h> // for D3DReflect() / D3DX11Refection - IMPORTANT NOTE: include directories MUST list DX SDK include path BEFORE // Windows include paths or you'll get compile errors with D3DShader.h // context creation parameters struct CPUTContextCreation { int refreshRate; int swapChainBufferCount; DXGI_FORMAT swapChainFormat; DXGI_USAGE swapChainUsage; }; // window creation parameters struct CPUTWindowCreationParams { bool startFullscreen; int windowWidth; int windowHeight; int windowPositionX; int windowPositionY; CPUTContextCreation deviceParams; CPUTWindowCreationParams() : startFullscreen(false), windowWidth(1280), windowHeight(720), windowPositionX(0), windowPositionY(0) {} }; // Types of message boxes you can create enum CPUT_MESSAGE_BOX_TYPE { CPUT_MB_OK = MB_OK | MB_ICONINFORMATION, CPUT_MB_ERROR = MB_OK | MB_ICONEXCLAMATION, CPUT_MB_WARNING = MB_OK | MB_ICONWARNING }; //-------------------------------------------------------------------------------------- struct CPUTFrameConstantBuffer { XMMATRIX View; XMMATRIX Projection; XMVECTOR AmbientColor; XMVECTOR LightColor; XMVECTOR TotalSeconds; }; // DirectX 11 CPUT layer //----------------------------------------------------------------------------- class CPUT_DX11; extern CPUT_DX11 *gpSample; class CPUT_DX11:public CPUT { protected: static ID3D11Device *mpD3dDevice; public: static ID3D11Device *GetDevice(); protected: CPUTWindowWin *mpWindow; bool mbShutdown; cString mResourceDirectory; D3D_DRIVER_TYPE mdriverType; D3D_FEATURE_LEVEL mfeatureLevel; ID3D11DeviceContext *mpContext; IDXGISwapChain *mpSwapChain; UINT mSwapChainBufferCount; ID3D11RenderTargetView *mpBackBufferRTV; ID3D11ShaderResourceView *mpBackBufferSRV; ID3D11UnorderedAccessView *mpBackBufferUAV; DXGI_FORMAT mSwapChainFormat; ID3D11Texture2D *mpDepthStencilBuffer; ID3D11DepthStencilState *mpDepthStencilState; ID3D11DepthStencilView *mpDepthStencilView; // was in protected ID3D11ShaderResourceView *mpDepthStencilSRV; UINT mSyncInterval; // used for vsync CPUTBufferDX11 *mpPerFrameConstantBuffer; public: CPUT_DX11():mpWindow(NULL), mpContext(NULL), mpSwapChain(NULL), mSwapChainBufferCount(1), mpBackBufferRTV(NULL), mpBackBufferSRV(NULL), mpBackBufferUAV(NULL), mpDepthStencilBuffer(NULL), mpDepthStencilState(NULL), mpDepthStencilView(NULL), mpDepthStencilSRV(NULL), mSwapChainFormat(DXGI_FORMAT_UNKNOWN), mbShutdown(false), mSyncInterval(0), // start with vsync off mpPerFrameConstantBuffer(NULL) { mpTimer = (CPUTTimer*) new CPUTTimerWin(); gpSample = this; } virtual ~CPUT_DX11(); // context creation/destruction routines CPUTResult CPUTInitialize(const cString ResourceDirectory); CPUTResult SetCPUTResourceDirectory(const cString ResourceDirectory); cString GetCPUTResourceDirectory() { return mResourceDirectory; } CPUTResult CPUTParseCommandLine(cString commandLine, CPUTWindowCreationParams *pWindowParams, cString *pFilename); D3D_FEATURE_LEVEL GetFeatureLevel() { return mfeatureLevel; } int CPUTMessageLoop(); CPUTResult CPUTCreateWindowAndContext(const cString WindowTitle, CPUTWindowCreationParams windowParams); // CPUT interfaces virtual void ResizeWindow(UINT width, UINT height); virtual void ResizeWindowSoft(UINT width, UINT height); void DeviceShutdown(); void RestartCPUT(); void SetPerFrameConstantBuffer( double totalSeconds ); void InnerExecutionLoop(); // events virtual void Update(double deltaSeconds) {} virtual void Present() { mpSwapChain->Present( mSyncInterval, 0 ); } virtual void Render(double deltaSeconds) = 0; virtual void Create()=0; virtual void Shutdown(); virtual void FullscreenModeChange(bool bFullscreen) {UNREFERENCED_PARAMETER(bFullscreen);} // fires when CPUT changes to/from fullscreen mode virtual void ReleaseSwapChain() {} // virtual void ResizeWindow(UINT width, UINT height){UNREFERENCED_PARAMETER(width);UNREFERENCED_PARAMETER(height);} virtual CPUTResult CreateContext(); // GUI void CPUTDrawGUI(); // Event Handling CPUTEventHandledCode CPUTHandleKeyboardEvent(CPUTKey key); CPUTEventHandledCode CPUTHandleMouseEvent(int x, int y, int wheel, CPUTMouseState state); // Utility functions for the sample developer CPUTResult CPUTToggleFullScreenMode(); void CPUTSetFullscreenState(bool bIsFullscreen); bool CPUTGetFullscreenState(); CPUTGuiControllerDX11* CPUTGetGuiController(); // Message boxes void CPUTMessageBox(const cString DialogBoxTitle, const cString DialogMessage); protected: // private helper functions bool TestContextForRequiredFeatures(); void ShutdownAndDestroy(); virtual CPUTResult CreateDXContext(CPUTContextCreation ContextParams); // allow user to override DirectX context creation virtual CPUTResult DestroyDXContext(); // allow user to override DirectX context destruction CPUTResult MakeWindow(const cString WindowTitle, int windowWidth, int windowHeight, int windowX, int windowY); CPUTResult CreateAndBindDepthBuffer(int width, int height); void DrawLoadingFrame(); // TODO: Put this somewhere else bool FindMatchingInputSlot(const char *pInputSlotName, const ID3DBlob *pVertexShaderBlob); }; #endif //#ifndef __CPUT_DX11_H__
/* Copyright (c) 2005-2020 Intel Corporation Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ #include "tbb/compat/condition_variable" #include "tbb/mutex.h" #include "tbb/recursive_mutex.h" #include "tbb/tick_count.h" #include "tbb/atomic.h" #include <stdexcept> #include "harness.h" #if TBB_IMPLEMENT_CPP0X // This test deliberately avoids a "using tbb" statement, // so that the error of putting types in the wrong namespace will be caught. using namespace std; #else using namespace tbb::interface5; #endif #if __TBB_CPP11_RVALUE_REF_PRESENT template<typename M> void TestUniqueLockMoveConstructorAndAssignOp(){ typedef unique_lock<M> unique_lock_t; static const bool locked = true; static const bool unlocked = false; struct Locked{ bool value; Locked(bool a_value) : value(a_value) {} }; typedef Locked destination; typedef Locked source; struct MutexAndLockFixture{ M mutex; unique_lock_t lock; const bool was_locked; MutexAndLockFixture(source lckd_src) : lock(mutex), was_locked(lckd_src.value){ if (!lckd_src.value) lock.unlock(); ASSERT(was_locked == lock.owns_lock(), "unlock did not release the mutex while should?"); } }; struct TestCases{ const char* filename; int line; TestCases(const char* a_filename, int a_line) : filename(a_filename), line(a_line) {} void TestMoveConstructor(source locked_src){ MutexAndLockFixture src(locked_src); unique_lock_t dst_lock(std::move(src.lock)); AssertOwnershipWasTransfered(dst_lock, src.lock, src.was_locked, &src.mutex); } void TestMoveAssignment(source locked_src, destination locked_dest){ MutexAndLockFixture src(locked_src); MutexAndLockFixture dst(locked_dest); dst.lock = std::move(src.lock); ASSERT_CUSTOM(unique_lock_t(dst.mutex, try_to_lock).owns_lock(), "unique_lock should release owned mutex on assignment", filename, line); AssertOwnershipWasTransfered(dst.lock, src.lock, src.was_locked, &src.mutex); } void AssertOwnershipWasTransfered(unique_lock_t const& dest_lock, unique_lock_t const& src_lck, const bool was_locked, const M* mutex) { ASSERT_CUSTOM(dest_lock.owns_lock() == was_locked, "moved to lock object should have the same state as source before move", filename, line); ASSERT_CUSTOM(dest_lock.mutex() == mutex, "moved to lock object should have the same state as source before move", filename, line); ASSERT_CUSTOM(src_lck.owns_lock() == false, "moved from lock object must not left locked", filename, line); ASSERT_CUSTOM(src_lck.mutex() == NULL, "moved from lock object must not has mutex", filename, line); } }; //TODO: to rework this with an assertion binder #define AT_LOCATION() TestCases( __FILE__, __LINE__) \ AT_LOCATION().TestMoveConstructor(source(locked)); AT_LOCATION().TestMoveAssignment (source(locked), destination(locked)); AT_LOCATION().TestMoveAssignment (source(locked), destination(unlocked)); AT_LOCATION().TestMoveConstructor(source(unlocked)); AT_LOCATION().TestMoveAssignment (source(unlocked), destination(locked)); AT_LOCATION().TestMoveAssignment (source(unlocked), destination(unlocked)); #undef AT_LOCATION } #endif //__TBB_CPP11_RVALUE_REF_PRESENT template<typename M> struct Counter { typedef M mutex_type; M mutex; volatile long value; void flog_once_lock_guard( size_t mode ); void flog_once_unique_lock( size_t mode ); }; template<typename M> void Counter<M>::flog_once_lock_guard(size_t mode) /** Increments counter once for each iteration in the iteration space. */ { if( mode&1 ) { // Try acquire and release with implicit lock_guard // precondition: if mutex_type is not a recursive mutex, the calling thread does not own the mutex m. // if the precondition is not met, either dead-lock incorrect 'value' would result in. lock_guard<M> lg(mutex); value = value+1; } else { // Try acquire and release with adopt lock_quard // precodition: the calling thread owns the mutex m. // if the precondition is not met, incorrect 'value' would result in because the thread unlocks // mutex that it does not own. mutex.lock(); lock_guard<M> lg( mutex, adopt_lock ); value = value+1; } } template<typename M> void Counter<M>::flog_once_unique_lock(size_t mode) /** Increments counter once for each iteration in the iteration space. */ { switch( mode&7 ) { case 0: {// implicitly acquire and release mutex with unique_lock unique_lock<M> ul( mutex ); value = value+1; ASSERT( ul==true, NULL ); } break; case 1: {// unique_lock with defer_lock unique_lock<M> ul( mutex, defer_lock ); ASSERT( ul.owns_lock()==false, NULL ); ul.lock(); value = value+1; ASSERT( ul.owns_lock()==true, NULL ); } break; case 2: {// unique_lock::try_lock() with try_to_lock unique_lock<M> ul( mutex, try_to_lock ); if( !ul ) while( !ul.try_lock() ) __TBB_Yield(); value = value+1; } break; case 3: {// unique_lock::try_lock_for() with try_to_lock unique_lock<M> ul( mutex, defer_lock ); tbb::tick_count::interval_t i(1.0); while( !ul.try_lock_for( i ) ) ; value = value+1; ASSERT( ul.owns_lock()==true, NULL ); } break; case 4: { unique_lock<M> ul_o4; {// unique_lock with adopt_lock mutex.lock(); unique_lock<M> ul( mutex, adopt_lock ); value = value+1; ASSERT( ul.owns_lock()==true, NULL ); ASSERT( ul.mutex()==&mutex, NULL ); ASSERT( ul_o4.owns_lock()==false, NULL ); ASSERT( ul_o4.mutex()==NULL, NULL ); swap( ul, ul_o4 ); ASSERT( ul.owns_lock()==false, NULL ); ASSERT( ul.mutex()==NULL, NULL ); ASSERT( ul_o4.owns_lock()==true, NULL ); ASSERT( ul_o4.mutex()==&mutex, NULL ); ul_o4.unlock(); } ASSERT( ul_o4.owns_lock()==false, NULL ); } break; case 5: { unique_lock<M> ul_o5; {// unique_lock with adopt_lock mutex.lock(); unique_lock<M> ul( mutex, adopt_lock ); value = value+1; ASSERT( ul.owns_lock()==true, NULL ); ASSERT( ul.mutex()==&mutex, NULL ); ASSERT( ul_o5.owns_lock()==false, NULL ); ASSERT( ul_o5.mutex()==NULL, NULL ); ul_o5.swap( ul ); ASSERT( ul.owns_lock()==false, NULL ); ASSERT( ul.mutex()==NULL, NULL ); ASSERT( ul_o5.owns_lock()==true, NULL ); ASSERT( ul_o5.mutex()==&mutex, NULL ); ul_o5.unlock(); } ASSERT( ul_o5.owns_lock()==false, NULL ); } break; default: {// unique_lock with adopt_lock, and release() mutex.lock(); unique_lock<M> ul( mutex, adopt_lock ); ASSERT( ul==true, NULL ); value = value+1; M* old_m = ul.release(); old_m->unlock(); ASSERT( ul.owns_lock()==false, NULL ); } break; } } static tbb::atomic<size_t> Order; template<typename State, long TestSize> struct WorkForLocks: NoAssign { static const size_t chunk = 100; State& state; WorkForLocks( State& state_ ) : state(state_) {} void operator()( int ) const { size_t step; while( (step=Order.fetch_and_add<tbb::acquire>(chunk))<TestSize ) { for( size_t i=0; i<chunk && step<TestSize; ++i, ++step ) { state.flog_once_lock_guard(step); state.flog_once_unique_lock(step); } } } }; template<typename M> void TestLocks( const char* name, int nthread ) { REMARK("testing %s in TestLocks\n",name); Counter<M> counter; counter.value = 0; Order = 0; // use the macro because of a gcc 4.6 bug #define TEST_SIZE 100000 NativeParallelFor( nthread, WorkForLocks<Counter<M>, TEST_SIZE>(counter) ); if( counter.value!=2*TEST_SIZE ) REPORT("ERROR for %s in TestLocks: counter.value=%ld != 2 * %ld=test_size\n",name,counter.value,TEST_SIZE); #undef TEST_SIZE } static tbb::atomic<int> barrier; // Test if the constructor works and if native_handle() works template<typename M> struct WorkForCondVarCtor: NoAssign { condition_variable& my_cv; M& my_mtx; WorkForCondVarCtor( condition_variable& cv_, M& mtx_ ) : my_cv(cv_), my_mtx(mtx_) {} void operator()( int tid ) const { ASSERT( tid<=1, NULL ); // test with 2 threads. condition_variable::native_handle_type handle = my_cv.native_handle(); if( tid&1 ) { my_mtx.lock(); ++barrier; #if _WIN32||_WIN64 if( !tbb::interface5::internal::internal_condition_variable_wait( *handle, &my_mtx ) ) { int ec = GetLastError(); ASSERT( ec!=WAIT_TIMEOUT, NULL ); throw_exception( tbb::internal::eid_condvar_wait_failed ); } #else if( pthread_cond_wait( handle, my_mtx.native_handle() ) ) throw_exception( tbb::internal::eid_condvar_wait_failed ); #endif ++barrier; my_mtx.unlock(); } else { bool res; while( (res=my_mtx.try_lock())==true && barrier==0 ) { my_mtx.unlock(); __TBB_Yield(); } if( res ) my_mtx.unlock(); do { #if _WIN32||_WIN64 tbb::interface5::internal::internal_condition_variable_notify_one( *handle ); #else pthread_cond_signal( handle ); #endif __TBB_Yield(); } while ( barrier<2 ); } } }; static condition_variable* test_cv; static tbb::atomic<int> n_waiters; // Test if the destructor works template<typename M> struct WorkForCondVarDtor: NoAssign { int nthread; M& my_mtx; WorkForCondVarDtor( int n, M& mtx_ ) : nthread(n), my_mtx(mtx_) {} void operator()( int tid ) const { if( tid==0 ) { unique_lock<M> ul( my_mtx, defer_lock ); test_cv = new condition_variable; while( n_waiters<nthread-1 ) __TBB_Yield(); ul.lock(); test_cv->notify_all(); ul.unlock(); while( n_waiters>0 ) __TBB_Yield(); delete test_cv; } else { while( test_cv==NULL ) __TBB_Yield(); unique_lock<M> ul(my_mtx); ++n_waiters; test_cv->wait( ul ); --n_waiters; } } }; static const int max_ticket = 100; static const int short_delay = 10; static const int long_delay = 100; tbb::atomic<int> n_signaled; tbb::atomic<int> n_done, n_done_1, n_done_2; tbb::atomic<int> n_timed_out; static bool false_to_true; struct TestPredicateFalseToTrue { TestPredicateFalseToTrue() {} bool operator()() { return false_to_true; } }; struct TestPredicateFalse { TestPredicateFalse() {} bool operator()() { return false; } }; struct TestPredicateTrue { TestPredicateTrue() {} bool operator()() { return true; } }; // Test timed wait and timed wait with pred template<typename M> struct WorkForCondVarTimedWait: NoAssign { int nthread; condition_variable& test_cv; M& my_mtx; WorkForCondVarTimedWait( int n_, condition_variable& cv_, M& mtx_ ) : nthread(n_), test_cv(cv_), my_mtx(mtx_) {} void operator()( int tid ) const { tbb::tick_count t1, t2; unique_lock<M> ul( my_mtx, defer_lock ); ASSERT( n_timed_out==0, NULL ); ++barrier; while( barrier<nthread ) __TBB_Yield(); // test if a thread times out with wait_for() for( int i=1; i<10; ++i ) { tbb::tick_count::interval_t intv((double)i*0.0999 /*seconds*/); ul.lock(); cv_status st = no_timeout; __TBB_TRY { /** Some version of glibc return EINVAL instead 0 when spurious wakeup occurs on pthread_cond_timedwait() **/ st = test_cv.wait_for( ul, intv ); } __TBB_CATCH( std::runtime_error& ) {} ASSERT( ul, "mutex should have been reacquired" ); ul.unlock(); if( st==timeout ) ++n_timed_out; } ASSERT( n_timed_out>0, "should have been timed-out at least once\n" ); ++n_done_1; while( n_done_1<nthread ) __TBB_Yield(); for( int i=1; i<10; ++i ) { tbb::tick_count::interval_t intv((double)i*0.0001 /*seconds*/); ul.lock(); __TBB_TRY { /** Some version of glibc return EINVAL instead 0 when spurious wakeup occurs on pthread_cond_timedwait() **/ ASSERT( false==test_cv.wait_for( ul, intv, TestPredicateFalse()), "incorrect return value" ); } __TBB_CATCH( std::runtime_error& ) {} ASSERT( ul, "mutex should have been reacquired" ); ul.unlock(); } if( tid==0 ) n_waiters = 0; // barrier ++n_done_2; while( n_done_2<nthread ) __TBB_Yield(); // at this point, we know wait_for() successfully times out. // so test if a thread blocked on wait_for() could receive a signal before its waiting time elapses. if( tid==0 ) { // signaler n_signaled = 0; ASSERT( n_waiters==0, NULL ); ++n_done_2; // open gate 1 while( n_waiters<(nthread-1) ) __TBB_Yield(); // wait until all other threads block on cv. flag_1 ul.lock(); test_cv.notify_all(); n_waiters = 0; ul.unlock(); while( n_done_2<2*nthread ) __TBB_Yield(); ASSERT( n_signaled>0, "too small an interval?" ); n_signaled = 0; } else { while( n_done_2<nthread+1 ) __TBB_Yield(); // gate 1 // sleeper tbb::tick_count::interval_t intv((double)2.0 /*seconds*/); ul.lock(); ++n_waiters; // raise flag 1/(nthread-1) t1 = tbb::tick_count::now(); cv_status st = test_cv.wait_for( ul, intv ); // gate 2 t2 = tbb::tick_count::now(); ul.unlock(); if( st==no_timeout ) { ++n_signaled; ASSERT( (t2-t1).seconds()<intv.seconds(), "got a signal after timed-out?" ); } } ASSERT( n_done==0, NULL ); ++n_done_2; if( tid==0 ) { ASSERT( n_waiters==0, NULL ); ++n_done; // open gate 3 while( n_waiters<(nthread-1) ) __TBB_Yield(); // wait until all other threads block on cv. for( int i=0; i<2*short_delay; ++i ) __TBB_Yield(); // give some time to waiters so that all of them in the waitq ul.lock(); false_to_true = true; test_cv.notify_all(); // open gate 4 ul.unlock(); while( n_done<nthread ) __TBB_Yield(); // wait until all other threads wake up. ASSERT( n_signaled>0, "too small an interval?" ); } else { while( n_done<1 ) __TBB_Yield(); // gate 3 tbb::tick_count::interval_t intv((double)2.0 /*seconds*/); ul.lock(); ++n_waiters; // wait_for w/ predciate t1 = tbb::tick_count::now(); ASSERT( test_cv.wait_for( ul, intv, TestPredicateFalseToTrue())==true, NULL ); // gate 4 t2 = tbb::tick_count::now(); ul.unlock(); if( (t2-t1).seconds()<intv.seconds() ) ++n_signaled; ++n_done; } } }; tbb::atomic<int> ticket_for_sleep, ticket_for_wakeup, signaled_ticket, wokeup_ticket; tbb::atomic<unsigned> n_visit_to_waitq; unsigned max_waitq_length; template<typename M> struct WorkForCondVarWaitAndNotifyOne: NoAssign { int nthread; condition_variable& test_cv; M& my_mtx; WorkForCondVarWaitAndNotifyOne( int n_, condition_variable& cv_, M& mtx_ ) : nthread(n_), test_cv(cv_), my_mtx(mtx_) {} void operator()( int tid ) const { if( tid&1 ) { // exercise signal part while( ticket_for_wakeup<max_ticket ) { int my_ticket = ++ticket_for_wakeup; // atomically grab the next ticket if( my_ticket>max_ticket ) break; for( ;; ) { unique_lock<M> ul( my_mtx, defer_lock ); ul.lock(); if( n_waiters>0 && my_ticket<=ticket_for_sleep && my_ticket==(wokeup_ticket+1) ) { signaled_ticket = my_ticket; test_cv.notify_one(); ++n_signaled; ul.unlock(); break; } ul.unlock(); __TBB_Yield(); } // give waiters time to go to sleep. for( int m=0; m<short_delay; ++m ) __TBB_Yield(); } } else { while( ticket_for_sleep<max_ticket ) { unique_lock<M> ul( my_mtx, defer_lock ); ul.lock(); // exercise wait part int my_ticket = ++ticket_for_sleep; // grab my ticket if( my_ticket>max_ticket ) break; // each waiter should go to sleep at least once unsigned nw = ++n_waiters; for( ;; ) { // update to max_waitq_length if( nw>max_waitq_length ) max_waitq_length = nw; ++n_visit_to_waitq; test_cv.wait( ul ); // if( ret==false ) ++n_timedout; ASSERT( ul, "mutex should have been locked" ); --n_waiters; if( signaled_ticket==my_ticket ) { wokeup_ticket = my_ticket; break; } if( n_waiters>0 ) test_cv.notify_one(); nw = ++n_waiters; // update to max_waitq_length occurs above } ul.unlock(); __TBB_Yield(); // give other threads chance to run. } } ++n_done; spin_wait_until_eq( n_done, nthread ); ASSERT( n_signaled==max_ticket, "incorrect number of notifications sent" ); } }; struct TestPredicate1 { int target; TestPredicate1( int i_ ) : target(i_) {} bool operator()( ) { return signaled_ticket==target; } }; template<typename M> struct WorkForCondVarWaitPredAndNotifyAll: NoAssign { int nthread; condition_variable& test_cv; M& my_mtx; int multiple; WorkForCondVarWaitPredAndNotifyAll( int n_, condition_variable& cv_, M& mtx_, int m_ ) : nthread(n_), test_cv(cv_), my_mtx(mtx_), multiple(m_) {} void operator()( int tid ) const { if( tid&1 ) { while( ticket_for_sleep<max_ticket ) { unique_lock<M> ul( my_mtx, defer_lock ); // exercise wait part int my_ticket = ++ticket_for_sleep; // grab my ticket if( my_ticket>max_ticket ) break; ul.lock(); ++n_visit_to_waitq; unsigned nw = ++n_waiters; if( nw>max_waitq_length ) max_waitq_length = nw; test_cv.wait( ul, TestPredicate1( my_ticket ) ); wokeup_ticket = my_ticket; --n_waiters; ASSERT( ul, "mutex should have been locked" ); ul.unlock(); __TBB_Yield(); // give other threads chance to run. } } else { // exercise signal part while( ticket_for_wakeup<max_ticket ) { int my_ticket = ++ticket_for_wakeup; // atomically grab the next ticket if( my_ticket>max_ticket ) break; for( ;; ) { unique_lock<M> ul( my_mtx ); if( n_waiters>0 && my_ticket<=ticket_for_sleep && my_ticket==(wokeup_ticket+1) ) { signaled_ticket = my_ticket; test_cv.notify_all(); ++n_signaled; ul.unlock(); break; } ul.unlock(); __TBB_Yield(); } // give waiters time to go to sleep. for( int m=0; m<long_delay*multiple; ++m ) __TBB_Yield(); } } ++n_done; spin_wait_until_eq( n_done, nthread ); ASSERT( n_signaled==max_ticket, "incorrect number of notifications sent" ); } }; void InitGlobalCounters() { ticket_for_sleep = ticket_for_wakeup = signaled_ticket = wokeup_ticket = 0; n_waiters = 0; n_signaled = 0; n_done = n_done_1 = n_done_2 = 0; n_visit_to_waitq = 0; n_timed_out = 0; } template<typename M> void TestConditionVariable( const char* name, int nthread ) { REMARK("testing %s in TestConditionVariable\n",name); Counter<M> counter; M mtx; ASSERT( nthread>1, "at least two threads are needed for testing condition_variable" ); REMARK(" - constructor\n" ); // Test constructor. { condition_variable cv1; #if _WIN32||_WIN64 condition_variable::native_handle_type handle = cv1.native_handle(); ASSERT( uintptr_t(&handle->cv_event)==uintptr_t(&handle->cv_native), NULL ); #endif M mtx1; barrier = 0; NativeParallelFor( 2, WorkForCondVarCtor<M>( cv1, mtx1 ) ); } REMARK(" - destructor\n" ); // Test destructor. { M mtx2; test_cv = NULL; n_waiters = 0; NativeParallelFor( nthread, WorkForCondVarDtor<M>( nthread, mtx2 ) ); } REMARK(" - timed_wait (i.e., wait_for)\n"); // Test timed wait. { condition_variable cv_tw; M mtx_tw; barrier = 0; InitGlobalCounters(); int nthr = nthread>4?4:nthread; NativeParallelFor( nthr, WorkForCondVarTimedWait<M>( nthr, cv_tw, mtx_tw ) ); } REMARK(" - wait with notify_one\n"); // Test wait and notify_one do { condition_variable cv3; M mtx3; InitGlobalCounters(); NativeParallelFor( nthread, WorkForCondVarWaitAndNotifyOne<M>( nthread, cv3, mtx3 ) ); } while( n_visit_to_waitq==0 || max_waitq_length==0 ); REMARK(" - predicated wait with notify_all\n"); // Test wait_pred and notify_all int delay_multiple = 1; do { condition_variable cv4; M mtx4; InitGlobalCounters(); NativeParallelFor( nthread, WorkForCondVarWaitPredAndNotifyAll<M>( nthread, cv4, mtx4, delay_multiple ) ); if( max_waitq_length<unsigned(nthread/2) ) ++delay_multiple; } while( n_visit_to_waitq<=0 || max_waitq_length<unsigned(nthread/2) ); } #if TBB_USE_EXCEPTIONS && !__TBB_THROW_ACROSS_MODULE_BOUNDARY_BROKEN static tbb::atomic<int> err_count; #define TRY_AND_CATCH_RUNTIME_ERROR(op,msg) \ try { \ op; \ ++err_count; \ } catch( std::runtime_error& e ) {ASSERT( strstr(e.what(), msg) , NULL );} catch(...) {++err_count;} template<typename M> void TestUniqueLockException( const char * name ) { REMARK("testing %s TestUniqueLockException\n",name); M mtx; unique_lock<M> ul_0; err_count = 0; TRY_AND_CATCH_RUNTIME_ERROR( ul_0.lock(), "Operation not permitted" ); TRY_AND_CATCH_RUNTIME_ERROR( ul_0.try_lock(), "Operation not permitted" ); unique_lock<M> ul_1( mtx ); TRY_AND_CATCH_RUNTIME_ERROR( ul_1.lock(), "Resource deadlock" ); TRY_AND_CATCH_RUNTIME_ERROR( ul_1.try_lock(), "Resource deadlock" ); ul_1.unlock(); TRY_AND_CATCH_RUNTIME_ERROR( ul_1.unlock(), "Operation not permitted" ); ASSERT( !err_count, "Some exceptions are not thrown or incorrect ones are thrown" ); } template<typename M> void TestConditionVariableException( const char * name ) { REMARK("testing %s in TestConditionVariableException; yet to be implemented\n",name); } #endif /* TBB_USE_EXCEPTIONS */ template<typename Mutex, typename RecursiveMutex> void DoCondVarTest() { #if __TBB_CPP11_RVALUE_REF_PRESENT TestUniqueLockMoveConstructorAndAssignOp<Mutex>(); TestUniqueLockMoveConstructorAndAssignOp<RecursiveMutex>(); #endif for( int p=MinThread; p<=MaxThread; ++p ) { REMARK( "testing with %d threads\n", p ); TestLocks<Mutex>( "mutex", p ); TestLocks<RecursiveMutex>( "recursive_mutex", p ); if( p<=1 ) continue; // for testing condition_variable, at least one sleeper and one notifier are needed TestConditionVariable<Mutex>( "mutex", p ); } #if __TBB_THROW_ACROSS_MODULE_BOUNDARY_BROKEN REPORT("Known issue: exception handling tests are skipped.\n"); #elif TBB_USE_EXCEPTIONS TestUniqueLockException<Mutex>( "mutex" ); TestUniqueLockException<RecursiveMutex>( "recursive_mutex" ); TestConditionVariableException<Mutex>( "mutex" ); #endif /* TBB_USE_EXCEPTIONS */ }
#ifndef ION_DEVICE_BENCH_BOARD_H #define ION_DEVICE_BENCH_BOARD_H #include <shared/drivers/board_frequency.h> #include <shared/drivers/board_privileged.h> namespace Ion { namespace Device { namespace Board { void initFPU(); void initMPU(); void initCompensationCell(); void shutdownCompensationCell(); void initPeripherals(); void shutdownPeripherals(); void initSystemClocks(); // n0110/shared/drivers/board.cpp void initPeripheralsClocks(); void shutdownPeripheralsClocks(); void setDefaultGPIO(); void initInterruptions(); } } } #endif
/* * Copyright (C) 2011-2012 Regents of the University of Michigan, * Hyun Min Kang, Matthew Flickenger, Matthew Snyder, * and Goncalo Abecasis * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ #ifndef __VCF_RECORD_H__ #define __VCF_RECORD_H__ #include <vector> #include <stdlib.h> #include "VcfRecordFilter.h" #include "VcfRecordInfo.h" #include "VcfRecordGenotype.h" #include "StatGenStatus.h" #include "VcfRecordDiscardRules.h" /// This header file provides interface to read/write VCF files. class VcfRecord { public: /// Default Constructor, initializes the variables, but does not open /// any files. VcfRecord(); /// Destructor virtual ~VcfRecord(); /// Read the next Vcf data line from the file. /// \param filePtr IFILE to read from. /// \param siteOnly only store the first 8 columns /// \param sampleSubset pointer to sample subset information, /// but NULL if sample subsetting is not to be done. /// \param discardRules pointer to record discard information, /// but NULL if record discarding is not to be done. /// \return true if a line was successfully read from the specified filePtr, /// false if not. bool read(IFILE filePtr, bool siteOnly, VcfRecordDiscardRules& discardRules, VcfSubsetSamples* sampleSubset = NULL); /// Write this data line to the file (including the newline). /// \param filePtr IFILE to write to. /// \param siteOnly only write the first 8 columns /// \return true if a line was successfully written to the specified filePtr, /// false if not. bool write(IFILE filePtr, bool siteOnly); /// Reset this header, preparing for a new one. void reset(); /// Returns the status associated with the last method that sets the status. /// \return StatGenStatus of the last command that sets status. const StatGenStatus& getStatus(); // bool isValid(); /////////////////////// /// @name Get Vcf Fields /// Get methods for record fields (do not set status). //@{ const char* getChromStr() {return(myChrom.c_str());} int get1BasedPosition() {return(my1BasedPosNum);} const char* getIDStr() {return(myID.c_str());} const char* getRefStr() {return(myRef.c_str());} int getNumRefBases() {return(myRef.size());} const char* getAltStr() {return(myAlt.c_str());} /// Return a pointer to the alleles at the specified index with index 0 /// being the reference string for this position and index 1 starting /// the alternate alleles, throwing an exception if the index is out of /// range. /// \param index allele index (0 for reference, 1 for first alt, /// 2 for second, etc) /// \return string of the alleles at the specified index const char* getAlleles(unsigned int index); /// Return the int value of the first allele in the string at the /// specified index with index 0 being the reference string for /// this position and index 1 starting the alternate alleles, /// throwing an exception if the index is out of range. /// \param index allele index (0 for reference, 1 for first alt, /// 2 for second, etc) /// \return int allele at the specified index, 1=A, 2=C, 3=G, 4=T int getIntAllele(unsigned int index); /// Return the number of alternates listed in the Alts string. unsigned int getNumAlts(); float getQual() {return(myQualNum);} const char* getQualStr() {return(myQual.c_str());} /// Return a reference to the filter information. VcfRecordFilter& getFilter(){return(myFilter);} /// Return whether or not all filters were passed. int passedAllFilters() { return(myFilter.passedAllFilters()); } /// Get a reference to the information field. VcfRecordInfo& getInfo() {return myInfo;} /// Get a reference to the genotype fields. VcfRecordGenotype& getGenotypeInfo() {return myGenotype;} inline int getNumSamples() { return(myGenotype.getNumSamples()); } inline int getNumGTs(int index) { return(myGenotype.getNumGTs(index)); } inline int getGT(int sampleNum, unsigned int gtIndex) { return(myGenotype.getGT(sampleNum, gtIndex)); } /// Return true if all of the samples are phased and none are unphased, /// false if any are unphased or not phased. inline bool allPhased() { return(myGenotype.allPhased()); } /// Return true if all of the samples are unphased and none are phased, /// false if any are phased or not unphased. inline bool allUnphased() { return(myGenotype.allUnphased()); } /// Return true if all samples of all records have all the genotype alleles /// specified, false if not or if any GT field is missing. bool hasAllGenotypeAlleles() { return(myGenotype.hasAllGenotypeAlleles()); } /// Return the number of occurances of the specified allele index in the /// genotypes for this record. Index 0 for the reference. The alternate /// alleles start with index 1. An exception is thrown if the index is /// out of range. Optionally, the specified subset of samples can be /// skipped when determining allele counts. (If the record is read with /// just a subset of samples, those are automatically excluded here /// regardless of the passed in sampleSubset. /// \param index allele index (0 for reference, 1 for first alt, /// 2 for second, etc) /// \param sampleSubset pointer to sample subset information, /// but NULL if additional sample subsetting is not to be done. /// \return int allele count for the specified ref/alt. int getAlleleCount(unsigned int index, VcfSubsetSamples* sampleSubset = NULL); //@} /////////////////////// /// @name Set Vcf Fields /// Set methods for record fields (do not set status). //@{ void setChrom(const char* chrom) {myChrom = chrom;} void set1BasedPosition(int pos) {my1BasedPosNum = pos;} void setID(const char* id) {myID = id;} void setRef(const char* ref) {myRef = ref;} void setAlt(const char* alt) {myAlt = alt; myAltArray.clear();} // void setQual(float qual) {myQualNum = qual; } void setQual(const char* qual) { myQual = qual; if(myQual != ".") { myQualNum = atof(qual); } else { myQualNum = -1; } } protected: /// Read the specified file until a tab, '\n', or EOF is found /// and appending the read characters to stringRef (except for the /// stopping character). /// \param filePtr open file to be read. /// \param stringRef reference to a string that should be appended to /// with the characters read from the file until a '\t', '\n', or EOF /// is found. /// \return true if a '\t' stopped the reading, false if '\n' or /// EOF stopped the reading. bool readTilTab(IFILE filePtr, std::string& stringRef); private: VcfRecord(const VcfRecord& vcfRecord); VcfRecord& operator=(const VcfRecord& vcfRecord); static const char ALT_DELIM = ','; std::string myChrom; int my1BasedPosNum; std::string my1BasedPos; vcfIDtype myID; std::string myRef; std::string myAlt; float myQualNum; std::string myQual; VcfRecordFilter myFilter; VcfRecordInfo myInfo; VcfRecordGenotype myGenotype; ReusableVector<std::string> myAltArray; std::vector<int> myAlleleCount; // The status of the last failed command. StatGenStatus myStatus; std::string myDummyString; // Set Pointers to each piece. }; #endif
/**************************************************************************** ** ** Copyright (C) 2015 The Qt Company Ltd. ** Contact: http://www.qt.io/licensing/ ** ** This file is part of the plugins of the Qt Toolkit. ** ** $QT_BEGIN_LICENSE:LGPL21$ ** Commercial License Usage ** Licensees holding valid commercial Qt licenses may use this file in ** accordance with the commercial license agreement provided with the ** Software or, alternatively, in accordance with the terms contained in ** a written agreement between you and The Qt Company. For licensing terms ** and conditions see http://www.qt.io/terms-conditions. For further ** information use the contact form at http://www.qt.io/contact-us. ** ** GNU Lesser General Public License Usage ** Alternatively, this file may be used under the terms of the GNU Lesser ** General Public License version 2.1 or version 3 as published by the Free ** Software Foundation and appearing in the file LICENSE.LGPLv21 and ** LICENSE.LGPLv3 included in the packaging of this file. Please review the ** following information to ensure the GNU Lesser General Public License ** requirements will be met: https://www.gnu.org/licenses/lgpl.html and ** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html. ** ** As a special exception, The Qt Company gives you certain additional ** rights. These rights are described in The Qt Company LGPL Exception ** version 1.1, included in the file LGPL_EXCEPTION.txt in this package. ** ** $QT_END_LICENSE$ ** ****************************************************************************/ #ifndef QLINUXFBSCREEN_H #define QLINUXFBSCREEN_H #include <QtPlatformSupport/private/qfbscreen_p.h> QT_BEGIN_NAMESPACE class QPainter; class QFbCursor; class QLinuxFbScreen : public QFbScreen { Q_OBJECT public: QLinuxFbScreen(const QStringList &args); ~QLinuxFbScreen(); bool initialize(); QPixmap grabWindow(WId wid, int x, int y, int width, int height) const Q_DECL_OVERRIDE; QRegion doRedraw() Q_DECL_OVERRIDE; private: QStringList mArgs; int mFbFd; int mTtyFd; QImage mFbScreenImage; int mBytesPerLine; int mOldTtyMode; int mRotation; struct { uchar *data; int offset, size; } mMmap; QPainter *mBlitter; }; QT_END_NAMESPACE #endif // QLINUXFBSCREEN_H
/* * Copyright 2010-2017 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ #pragma once #include <aws/iam/IAM_EXPORTS.h> #include <aws/iam/IAMRequest.h> #include <aws/core/utils/memory/stl/AWSString.h> #include <utility> namespace Aws { namespace IAM { namespace Model { /** */ class AWS_IAM_API ListAttachedRolePoliciesRequest : public IAMRequest { public: ListAttachedRolePoliciesRequest(); Aws::String SerializePayload() const override; protected: void DumpBodyToUrl(Aws::Http::URI& uri ) const override; public: /** * <p>The name (friendly name, not ARN) of the role to list attached policies * for.</p> <p>This parameter allows (per its <a * href="http://wikipedia.org/wiki/regex">regex pattern</a>) a string of characters * consisting of upper and lowercase alphanumeric characters with no spaces. You * can also include any of the following characters: _+=,.@-</p> */ inline const Aws::String& GetRoleName() const{ return m_roleName; } /** * <p>The name (friendly name, not ARN) of the role to list attached policies * for.</p> <p>This parameter allows (per its <a * href="http://wikipedia.org/wiki/regex">regex pattern</a>) a string of characters * consisting of upper and lowercase alphanumeric characters with no spaces. You * can also include any of the following characters: _+=,.@-</p> */ inline void SetRoleName(const Aws::String& value) { m_roleNameHasBeenSet = true; m_roleName = value; } /** * <p>The name (friendly name, not ARN) of the role to list attached policies * for.</p> <p>This parameter allows (per its <a * href="http://wikipedia.org/wiki/regex">regex pattern</a>) a string of characters * consisting of upper and lowercase alphanumeric characters with no spaces. You * can also include any of the following characters: _+=,.@-</p> */ inline void SetRoleName(Aws::String&& value) { m_roleNameHasBeenSet = true; m_roleName = std::move(value); } /** * <p>The name (friendly name, not ARN) of the role to list attached policies * for.</p> <p>This parameter allows (per its <a * href="http://wikipedia.org/wiki/regex">regex pattern</a>) a string of characters * consisting of upper and lowercase alphanumeric characters with no spaces. You * can also include any of the following characters: _+=,.@-</p> */ inline void SetRoleName(const char* value) { m_roleNameHasBeenSet = true; m_roleName.assign(value); } /** * <p>The name (friendly name, not ARN) of the role to list attached policies * for.</p> <p>This parameter allows (per its <a * href="http://wikipedia.org/wiki/regex">regex pattern</a>) a string of characters * consisting of upper and lowercase alphanumeric characters with no spaces. You * can also include any of the following characters: _+=,.@-</p> */ inline ListAttachedRolePoliciesRequest& WithRoleName(const Aws::String& value) { SetRoleName(value); return *this;} /** * <p>The name (friendly name, not ARN) of the role to list attached policies * for.</p> <p>This parameter allows (per its <a * href="http://wikipedia.org/wiki/regex">regex pattern</a>) a string of characters * consisting of upper and lowercase alphanumeric characters with no spaces. You * can also include any of the following characters: _+=,.@-</p> */ inline ListAttachedRolePoliciesRequest& WithRoleName(Aws::String&& value) { SetRoleName(std::move(value)); return *this;} /** * <p>The name (friendly name, not ARN) of the role to list attached policies * for.</p> <p>This parameter allows (per its <a * href="http://wikipedia.org/wiki/regex">regex pattern</a>) a string of characters * consisting of upper and lowercase alphanumeric characters with no spaces. You * can also include any of the following characters: _+=,.@-</p> */ inline ListAttachedRolePoliciesRequest& WithRoleName(const char* value) { SetRoleName(value); return *this;} /** * <p>The path prefix for filtering the results. This parameter is optional. If it * is not included, it defaults to a slash (/), listing all policies.</p> <p>This * paramater allows (per its <a href="http://wikipedia.org/wiki/regex">regex * pattern</a>) a string of characters consisting of either a forward slash (/) by * itself or a string that must begin and end with forward slashes, containing any * ASCII character from the ! (\u0021) thru the DEL character (\u007F), including * most punctuation characters, digits, and upper and lowercased letters.</p> */ inline const Aws::String& GetPathPrefix() const{ return m_pathPrefix; } /** * <p>The path prefix for filtering the results. This parameter is optional. If it * is not included, it defaults to a slash (/), listing all policies.</p> <p>This * paramater allows (per its <a href="http://wikipedia.org/wiki/regex">regex * pattern</a>) a string of characters consisting of either a forward slash (/) by * itself or a string that must begin and end with forward slashes, containing any * ASCII character from the ! (\u0021) thru the DEL character (\u007F), including * most punctuation characters, digits, and upper and lowercased letters.</p> */ inline void SetPathPrefix(const Aws::String& value) { m_pathPrefixHasBeenSet = true; m_pathPrefix = value; } /** * <p>The path prefix for filtering the results. This parameter is optional. If it * is not included, it defaults to a slash (/), listing all policies.</p> <p>This * paramater allows (per its <a href="http://wikipedia.org/wiki/regex">regex * pattern</a>) a string of characters consisting of either a forward slash (/) by * itself or a string that must begin and end with forward slashes, containing any * ASCII character from the ! (\u0021) thru the DEL character (\u007F), including * most punctuation characters, digits, and upper and lowercased letters.</p> */ inline void SetPathPrefix(Aws::String&& value) { m_pathPrefixHasBeenSet = true; m_pathPrefix = std::move(value); } /** * <p>The path prefix for filtering the results. This parameter is optional. If it * is not included, it defaults to a slash (/), listing all policies.</p> <p>This * paramater allows (per its <a href="http://wikipedia.org/wiki/regex">regex * pattern</a>) a string of characters consisting of either a forward slash (/) by * itself or a string that must begin and end with forward slashes, containing any * ASCII character from the ! (\u0021) thru the DEL character (\u007F), including * most punctuation characters, digits, and upper and lowercased letters.</p> */ inline void SetPathPrefix(const char* value) { m_pathPrefixHasBeenSet = true; m_pathPrefix.assign(value); } /** * <p>The path prefix for filtering the results. This parameter is optional. If it * is not included, it defaults to a slash (/), listing all policies.</p> <p>This * paramater allows (per its <a href="http://wikipedia.org/wiki/regex">regex * pattern</a>) a string of characters consisting of either a forward slash (/) by * itself or a string that must begin and end with forward slashes, containing any * ASCII character from the ! (\u0021) thru the DEL character (\u007F), including * most punctuation characters, digits, and upper and lowercased letters.</p> */ inline ListAttachedRolePoliciesRequest& WithPathPrefix(const Aws::String& value) { SetPathPrefix(value); return *this;} /** * <p>The path prefix for filtering the results. This parameter is optional. If it * is not included, it defaults to a slash (/), listing all policies.</p> <p>This * paramater allows (per its <a href="http://wikipedia.org/wiki/regex">regex * pattern</a>) a string of characters consisting of either a forward slash (/) by * itself or a string that must begin and end with forward slashes, containing any * ASCII character from the ! (\u0021) thru the DEL character (\u007F), including * most punctuation characters, digits, and upper and lowercased letters.</p> */ inline ListAttachedRolePoliciesRequest& WithPathPrefix(Aws::String&& value) { SetPathPrefix(std::move(value)); return *this;} /** * <p>The path prefix for filtering the results. This parameter is optional. If it * is not included, it defaults to a slash (/), listing all policies.</p> <p>This * paramater allows (per its <a href="http://wikipedia.org/wiki/regex">regex * pattern</a>) a string of characters consisting of either a forward slash (/) by * itself or a string that must begin and end with forward slashes, containing any * ASCII character from the ! (\u0021) thru the DEL character (\u007F), including * most punctuation characters, digits, and upper and lowercased letters.</p> */ inline ListAttachedRolePoliciesRequest& WithPathPrefix(const char* value) { SetPathPrefix(value); return *this;} /** * <p>Use this parameter only when paginating results and only after you receive a * response indicating that the results are truncated. Set it to the value of the * <code>Marker</code> element in the response that you received to indicate where * the next call should start.</p> */ inline const Aws::String& GetMarker() const{ return m_marker; } /** * <p>Use this parameter only when paginating results and only after you receive a * response indicating that the results are truncated. Set it to the value of the * <code>Marker</code> element in the response that you received to indicate where * the next call should start.</p> */ inline void SetMarker(const Aws::String& value) { m_markerHasBeenSet = true; m_marker = value; } /** * <p>Use this parameter only when paginating results and only after you receive a * response indicating that the results are truncated. Set it to the value of the * <code>Marker</code> element in the response that you received to indicate where * the next call should start.</p> */ inline void SetMarker(Aws::String&& value) { m_markerHasBeenSet = true; m_marker = std::move(value); } /** * <p>Use this parameter only when paginating results and only after you receive a * response indicating that the results are truncated. Set it to the value of the * <code>Marker</code> element in the response that you received to indicate where * the next call should start.</p> */ inline void SetMarker(const char* value) { m_markerHasBeenSet = true; m_marker.assign(value); } /** * <p>Use this parameter only when paginating results and only after you receive a * response indicating that the results are truncated. Set it to the value of the * <code>Marker</code> element in the response that you received to indicate where * the next call should start.</p> */ inline ListAttachedRolePoliciesRequest& WithMarker(const Aws::String& value) { SetMarker(value); return *this;} /** * <p>Use this parameter only when paginating results and only after you receive a * response indicating that the results are truncated. Set it to the value of the * <code>Marker</code> element in the response that you received to indicate where * the next call should start.</p> */ inline ListAttachedRolePoliciesRequest& WithMarker(Aws::String&& value) { SetMarker(std::move(value)); return *this;} /** * <p>Use this parameter only when paginating results and only after you receive a * response indicating that the results are truncated. Set it to the value of the * <code>Marker</code> element in the response that you received to indicate where * the next call should start.</p> */ inline ListAttachedRolePoliciesRequest& WithMarker(const char* value) { SetMarker(value); return *this;} /** * <p>(Optional) Use this only when paginating results to indicate the maximum * number of items you want in the response. If additional items exist beyond the * maximum you specify, the <code>IsTruncated</code> response element is * <code>true</code>.</p> <p>If you do not include this parameter, it defaults to * 100. Note that IAM might return fewer results, even when there are more results * available. In that case, the <code>IsTruncated</code> response element returns * <code>true</code> and <code>Marker</code> contains a value to include in the * subsequent call that tells the service where to continue from.</p> */ inline int GetMaxItems() const{ return m_maxItems; } /** * <p>(Optional) Use this only when paginating results to indicate the maximum * number of items you want in the response. If additional items exist beyond the * maximum you specify, the <code>IsTruncated</code> response element is * <code>true</code>.</p> <p>If you do not include this parameter, it defaults to * 100. Note that IAM might return fewer results, even when there are more results * available. In that case, the <code>IsTruncated</code> response element returns * <code>true</code> and <code>Marker</code> contains a value to include in the * subsequent call that tells the service where to continue from.</p> */ inline void SetMaxItems(int value) { m_maxItemsHasBeenSet = true; m_maxItems = value; } /** * <p>(Optional) Use this only when paginating results to indicate the maximum * number of items you want in the response. If additional items exist beyond the * maximum you specify, the <code>IsTruncated</code> response element is * <code>true</code>.</p> <p>If you do not include this parameter, it defaults to * 100. Note that IAM might return fewer results, even when there are more results * available. In that case, the <code>IsTruncated</code> response element returns * <code>true</code> and <code>Marker</code> contains a value to include in the * subsequent call that tells the service where to continue from.</p> */ inline ListAttachedRolePoliciesRequest& WithMaxItems(int value) { SetMaxItems(value); return *this;} private: Aws::String m_roleName; bool m_roleNameHasBeenSet; Aws::String m_pathPrefix; bool m_pathPrefixHasBeenSet; Aws::String m_marker; bool m_markerHasBeenSet; int m_maxItems; bool m_maxItemsHasBeenSet; }; } // namespace Model } // namespace IAM } // namespace Aws
#ifndef TOKENIZER_H #define TOKENIZER_H /************************************************************** Name: Tokenizer.h Author: KJQ Desc: Static class to provide tokenizer services for simple parsers. Edits: Bugs: *************************************************************/ #include <StringVector.h> #include <vector> #include <string> using std::string; class Tokenizer { public: // split separates the line into multiple pieces, discarding delimiters // if quotechar is specified it's used to identify quoted strings. static int split(const string& input, const string& delimiters, StringVector&, char quoteChar = 0); private: Tokenizer(); // prevent anybody from making one ~Tokenizer(); }; #endif //TOKENIZER_H
/* * $Id$ * Copyright (C) 2000 ZetaBITS, Inc. * Copyright (C) 2000 Information-technology Promotion Agency, Japan * Copyright (C) 2001-2003 Shugo Maeda <shugo@modruby.net> * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF * SUCH DAMAGE. */ #include <sys/types.h> #include <sys/stat.h> /* for core_module */ #define CORE_PRIVATE #include "mod_ruby.h" #include "apachelib.h" #ifdef RUBY_VM #include "ruby/st.h" #else #include "st.h" #endif static VALUE rb_eApachePrematureChunkEndError; VALUE rb_cApacheRequest; /* Parse options */ static ID id_post_max, id_disable_uploads, id_temp_dir, id_hook_data, id_upload_hook; typedef struct request_data { request_rec *request; VALUE outbuf; VALUE connection; VALUE server; VALUE headers_in; VALUE headers_out; VALUE err_headers_out; VALUE subprocess_env; VALUE notes; VALUE finfo; VALUE parsed_uri; VALUE attributes; VALUE error_message; VALUE exception; ApacheRequest *apreq; VALUE upload_hook; VALUE upload_hook_arg; VALUE upload_table; VALUE cookies; VALUE param_table; VALUE options; } request_data; #define REQ_SYNC_HEADER FL_USER1 #define REQ_SYNC_OUTPUT FL_USER2 #define REQ_HEADER_PENDING FL_USER3 #define REQ_SENT_HEADER FL_USER4 #define REQUEST_STRING_ATTR_READER(fname, member) \ DEFINE_STRING_ATTR_READER(fname, request_data, request->member) #define REQUEST_STRING_ATTR_WRITER(fname, member) \ static VALUE fname(VALUE self, VALUE val) \ { \ request_data *data; \ Check_Type(val, T_STRING); \ data = get_request_data(self); \ data->request->member = \ apr_pstrndup(data->request->pool, \ RSTRING_PTR(val), RSTRING_LEN(val)); \ return val; \ } #define REQUEST_INT_ATTR_READER(fname, member) \ DEFINE_INT_ATTR_READER(fname, request_data, request->member) #define REQUEST_INT_ATTR_WRITER(fname, member) \ DEFINE_INT_ATTR_WRITER(fname, request_data, request->member) #define REQUEST_BOOL_ATTR_READER(fname, member) \ DEFINE_BOOL_ATTR_READER(fname, request_data, request->member) #define REQUEST_BOOL_ATTR_WRITER(fname, member) \ DEFINE_BOOL_ATTR_WRITER(fname, request_data, request->member) static void request_mark(request_data *data) { if (data == NULL) return; rb_gc_mark(data->outbuf); rb_gc_mark(data->connection); rb_gc_mark(data->server); rb_gc_mark(data->headers_in); rb_gc_mark(data->headers_out); rb_gc_mark(data->err_headers_out); rb_gc_mark(data->subprocess_env); rb_gc_mark(data->notes); rb_gc_mark(data->finfo); rb_gc_mark(data->parsed_uri); rb_gc_mark(data->attributes); rb_gc_mark(data->error_message); rb_gc_mark(data->exception); rb_gc_mark(data->upload_hook); rb_gc_mark(data->upload_hook_arg); rb_gc_mark(data->upload_table); rb_gc_mark(data->cookies); rb_gc_mark(data->param_table); rb_gc_mark(data->options); } static APR_CLEANUP_RETURN_TYPE cleanup_request_object(void *data) { request_rec *r = (request_rec *) data; ruby_request_config *rconf; VALUE reqobj; if (r->request_config == NULL) APR_CLEANUP_RETURN_SUCCESS(); rconf = get_request_config(r); if (rconf == NULL) APR_CLEANUP_RETURN_SUCCESS(); reqobj = rconf->request_object; if (TYPE(reqobj) == T_DATA) { free(RDATA(reqobj)->data); RDATA(reqobj)->data = NULL; } ap_set_module_config(r->request_config, &ruby_module, NULL); #if APR_HAS_THREADS if (ruby_is_threaded_mpm) { ruby_call_interpreter(r->pool, (ruby_interp_func_t) rb_apache_unregister_object, (void *) reqobj, NULL, 0); } else { #endif rb_apache_unregister_object(reqobj); #if APR_HAS_THREADS } #endif APR_CLEANUP_RETURN_SUCCESS(); } static VALUE apache_request_new(request_rec *r) { ruby_dir_config *dconf = get_dir_config(r); request_data *data; VALUE obj; const array_header *opts_arr; table_entry *opts; int i; obj = Data_Make_Struct(rb_cApacheRequest, request_data, request_mark, free, data); data->request = r; data->outbuf = rb_tainted_str_new("", 0); data->connection = Qnil; data->server = Qnil; data->headers_in = Qnil; data->headers_out = Qnil; data->err_headers_out = Qnil; data->subprocess_env = Qnil; data->notes = Qnil; data->finfo = Qnil; data->parsed_uri = Qnil; data->attributes = Qnil; data->error_message = Qnil; data->exception = Qnil; data->apreq = ApacheRequest_new( r ); data->upload_hook = Qnil; data->upload_hook_arg = Qnil; data->upload_table = rb_hash_new(); data->cookies = rb_hash_new(); data->param_table = Qnil; data->options = rb_hash_new(); if (dconf) { opts_arr = apr_table_elts(dconf->options); opts = (table_entry *) opts_arr->elts; for (i = 0; i < opts_arr->nelts; i++) { if (opts[i].key == NULL) continue; rb_hash_aset(data->options, rb_tainted_str_new2(opts[i].key), rb_tainted_str_new2(opts[i].val)); } } rb_apache_register_object(obj); if (r->request_config) { ruby_request_config *rconf = get_request_config(r); if (rconf) rconf->request_object = obj; } apr_pool_cleanup_register(r->pool, (void *) r, cleanup_request_object, apr_pool_cleanup_null); if (dconf) { switch (dconf->output_mode) { case MR_OUTPUT_SYNC_HEADER: FL_SET(obj, REQ_SYNC_HEADER); break; case MR_OUTPUT_SYNC: FL_SET(obj, REQ_SYNC_HEADER); FL_SET(obj, REQ_SYNC_OUTPUT); break; case MR_OUTPUT_NOSYNC: default: break; } } return obj; } VALUE rb_get_request_object(request_rec *r) { if (r == NULL) return Qnil; if (r->request_config) { ruby_request_config *rconf = get_request_config(r); if (rconf && !NIL_P(rconf->request_object)) return rconf->request_object; } return apache_request_new(r); } static request_data *get_request_data(VALUE obj) { request_data *data; Check_Type(obj, T_DATA); data = (request_data *) RDATA(obj)->data; if (data == NULL) rb_raise(rb_eArgError, "destroyed request"); return data; } request_rec *rb_get_request_rec(VALUE obj) { return get_request_data(obj)->request; } long rb_apache_request_length(VALUE self) { request_data *data; data = get_request_data(self); return RSTRING_LEN(data->outbuf); } static VALUE request_output_buffer(VALUE self) { request_data *data; data = get_request_data(self); return data->outbuf; } static VALUE request_replace(int argc, VALUE *argv, VALUE self) { request_data *data; data = get_request_data(self); return rb_funcall2(data->outbuf, rb_intern("replace"), argc, argv); } /* * Clear the output buffer. * @example Purge anything written to the output buffer if an exception is encountered. * * def handler( req ) * ... * rescue => err * req.cancel * req.content_type = 'text/plain' unless req.sent_http_header? * req.puts "Oops! Something went wrong:" * return Apache::OK * end */ static VALUE request_cancel(VALUE self) { request_data *data; data = get_request_data(self); rb_str_resize(data->outbuf, 0); return Qnil; } static VALUE request_get_sync_header(VALUE self) { return FL_TEST(self, REQ_SYNC_HEADER) ? Qtrue : Qfalse; } static VALUE request_set_sync_header(VALUE self, VALUE val) { if (RTEST(val)) { FL_SET(self, REQ_SYNC_HEADER); } else { FL_UNSET(self, REQ_SYNC_HEADER); } return val; } static VALUE request_get_sync_output(VALUE self) { return FL_TEST(self, REQ_SYNC_OUTPUT) ? Qtrue : Qfalse; } static VALUE request_set_sync_output(VALUE self, VALUE val) { if (RTEST(val)) { FL_SET(self, REQ_SYNC_OUTPUT); } else { FL_UNSET(self, REQ_SYNC_OUTPUT); } return val; } static VALUE request_set_sync(VALUE self, VALUE val) { if (RTEST(val)) { FL_SET(self, REQ_SYNC_HEADER); FL_SET(self, REQ_SYNC_OUTPUT); } else { FL_UNSET(self, REQ_SYNC_HEADER); FL_UNSET(self, REQ_SYNC_OUTPUT); } return val; } static VALUE request_write(VALUE self, VALUE str) { request_data *data; int len; data = get_request_data(self); str = rb_obj_as_string(str); if (FL_TEST(self, REQ_SYNC_OUTPUT)) { if (data->request->header_only && FL_TEST(self, REQ_SENT_HEADER)) return INT2NUM(0); len = ap_rwrite(RSTRING_PTR(str), RSTRING_LEN(str), data->request); ap_rflush(data->request); } else { rb_str_cat(data->outbuf, RSTRING_PTR(str), RSTRING_LEN(str)); len = RSTRING_LEN(str); } return INT2NUM(len); } static VALUE request_putc(VALUE self, VALUE c) { char ch = NUM2CHR(c); request_data *data; data = get_request_data(self); if (FL_TEST(self, REQ_SYNC_OUTPUT)) { int ret; if (data->request->header_only && FL_TEST(self, REQ_SENT_HEADER)) return INT2NUM(EOF); ret = ap_rputc(NUM2INT(c), data->request); return INT2NUM(ret); } else { rb_str_cat(data->outbuf, &ch, 1); return c; } } static VALUE request_print(int argc, VALUE *argv, VALUE out) { int i; VALUE line; /* if no argument given, print `$_' */ if (argc == 0) { argc = 1; line = rb_lastline_get(); argv = &line; } for (i=0; i<argc; i++) { if (!NIL_P(rb_output_fs) && i>0) { request_write(out, rb_output_fs); } switch (TYPE(argv[i])) { case T_NIL: request_write(out, STRING_LITERAL("nil")); break; default: request_write(out, argv[i]); break; } } if (!NIL_P(rb_output_rs)) { request_write(out, rb_output_rs); } return Qnil; } static VALUE request_printf(int argc, VALUE *argv, VALUE out) { request_write(out, rb_f_sprintf(argc, argv)); return Qnil; } static VALUE request_puts _((int, VALUE*, VALUE)); #ifdef RUBY_VM static VALUE request_puts_ary(VALUE ary, VALUE out, int recur) #else static VALUE request_puts_ary(VALUE ary, VALUE out) #endif { VALUE tmp; int i; for (i=0; i<RARRAY_LEN(ary); i++) { tmp = RARRAY_PTR(ary)[i]; #ifdef RUBY_VM if (recur) { #else if (rb_inspecting_p(tmp)) { #endif tmp = STRING_LITERAL("[...]"); } request_puts(1, &tmp, out); } return Qnil; } static VALUE request_puts(int argc, VALUE *argv, VALUE out) { int i; VALUE line; /* if no argument given, print newline. */ if (argc == 0) { request_write(out, rb_default_rs); return Qnil; } for (i=0; i<argc; i++) { switch (TYPE(argv[i])) { case T_NIL: line = STRING_LITERAL("nil"); break; case T_ARRAY: #ifdef RUBY_VM rb_exec_recursive(request_puts_ary, argv[i], out); #else rb_protect_inspect(request_puts_ary, argv[i], out); #endif continue; default: line = argv[i]; break; } line = rb_obj_as_string(line); request_write(out, line); if (RSTRING_PTR(line)[RSTRING_LEN(line)-1] != '\n') { request_write(out, rb_default_rs); } } return Qnil; } /* * Does the same thing as Apache::Request#write, but returns the request * object. * * @return [Apache::Request] the receiver */ static VALUE request_addstr(VALUE out, VALUE str) { request_write(out, str); return out; } VALUE rb_apache_request_send_http_header(VALUE self) { request_data *data; if (FL_TEST(self, REQ_SYNC_HEADER)) { data = get_request_data(self); ap_send_http_header(data->request); FL_SET(self, REQ_SENT_HEADER); FL_UNSET(self, REQ_HEADER_PENDING); } else { FL_SET(self, REQ_HEADER_PENDING); } return Qnil; } static VALUE request_sent_http_header(VALUE self) { if (FL_TEST(self, REQ_SENT_HEADER) || FL_TEST(self, REQ_HEADER_PENDING)) { return Qtrue; } else { return Qfalse; } } void rb_apache_request_flush(VALUE self) { request_data *data; data = get_request_data(self); if (FL_TEST(self, REQ_HEADER_PENDING)) { ap_send_http_header(data->request); FL_SET(self, REQ_SENT_HEADER); FL_UNSET(self, REQ_HEADER_PENDING); } if (data->request->header_only && FL_TEST(self, REQ_SENT_HEADER)) { rb_str_resize(data->outbuf, 0); return; } if (RSTRING_LEN(data->outbuf) > 0) { ap_rwrite(RSTRING_PTR(data->outbuf), RSTRING_LEN(data->outbuf), data->request); ap_rflush(data->request); rb_str_resize(data->outbuf, 0); } } /* * Return the connection object associated with the request. * @return [Apache::Connection] the connection object * @example Checking the client's IP address * request.connection.remote_ip # => "127.0.0.1" */ static VALUE request_connection(VALUE self) { request_data *data; data = get_request_data(self); if (NIL_P(data->connection)) { data->connection = rb_apache_connection_new(data->request->connection); } return data->connection; } static VALUE request_server(VALUE self) { request_data *data; data = get_request_data(self); if (NIL_P(data->server)) { data->server = rb_apache_server_new(data->request->server); } return data->server; } static VALUE request_next(VALUE self) { request_data *data; data = get_request_data(self); return rb_get_request_object(data->request->next); } static VALUE request_prev(VALUE self) { request_data *data; data = get_request_data(self); return rb_get_request_object(data->request->prev); } static VALUE request_last(VALUE self) { request_data *data; request_rec *last; data = get_request_data(self); for (last = data->request; last->next; last = last->next) continue; return rb_get_request_object(last); } static VALUE request_main(VALUE self) { request_data *data; data = get_request_data(self); return rb_get_request_object(data->request->main); } /* :TODO: These aren't going to work until I can figure out how to * make YARD see the ATTR_{READER,WRITER} macros. */ /* * Document-methods: * req.args -> string * req.args = string * * Get/set the query arguments part of the request URI. * @param * @return [String] the query arguments * */ /* * call-seq: * req.assbackwards? -> true or false * req.assbackwards = true or false * * Indicates an HTTP/0.9 ``simple'' request. This means that the response will contain * no headers, only the body. Although this exists for backwards compatibility with * obsolete browsers, some people have figured out that setting assbackwards * can be a useful technique when including part of the response from an internal * redirect to avoid headers being sent. * * example code */ REQUEST_STRING_ATTR_READER(request_protocol, protocol); REQUEST_STRING_ATTR_READER(request_hostname, hostname); REQUEST_STRING_ATTR_READER(request_unparsed_uri, unparsed_uri); REQUEST_STRING_ATTR_READER(request_get_uri, uri); REQUEST_STRING_ATTR_WRITER(request_set_uri, uri); REQUEST_STRING_ATTR_READER(request_get_filename, filename); REQUEST_STRING_ATTR_WRITER(request_set_filename, filename); REQUEST_STRING_ATTR_READER(request_get_path_info, path_info); REQUEST_STRING_ATTR_WRITER(request_set_path_info, path_info); REQUEST_INT_ATTR_READER(request_get_status, status); REQUEST_INT_ATTR_WRITER(request_set_status, status); REQUEST_STRING_ATTR_READER(request_get_status_line, status_line); REQUEST_STRING_ATTR_WRITER(request_set_status_line, status_line); REQUEST_STRING_ATTR_READER(request_the_request, the_request); REQUEST_BOOL_ATTR_READER(request_get_assbackwards, assbackwards); REQUEST_BOOL_ATTR_WRITER(request_set_assbackwards, assbackwards); REQUEST_STRING_ATTR_READER(request_request_method, method); REQUEST_INT_ATTR_READER(request_method_number, method_number); REQUEST_INT_ATTR_READER(request_get_allowed, allowed); REQUEST_INT_ATTR_WRITER(request_set_allowed, allowed); #ifdef FOR_RDOC /* * call-seq: * req.allowed = int * * A bitvector of the allowed methods. * * A handler must ensure that the request method is one that it is * capable of handling. Generally your handler should DECLINE any request * methods it does not handle, and set +r.allowed+ to the list of methods * that it is willing to handle. This bitvector is used to construct the * "Allow:" header required for OPTIONS requests, and * {Apache::HTTP_METHOD_NOT_ALLOWED} and {Apache::HTTP_NOT_IMPLEMENTED} status codes. * * Since the +default_handler+ deals with OPTIONS, all modules can usually * decline to deal with OPTIONS. TRACE is always allowed, modules don't * need to set it explicitly. * * Since the default_handler will always handle a GET, a module which * does *not* implement GET should probably return {Apache::HTTP_METHOD_NOT_ALLOWED}. * Unfortunately this means that a Script GET handler can't be installed * by mod_actions. * */ static VALUE request_set_allowed( VALUE self, VALUE val ) { request_data *data = get_request_data(self); data->request->allowed = NUM2INT(val); return val; } #endif REQUEST_STRING_ATTR_READER(request_get_args, args); REQUEST_STRING_ATTR_WRITER(request_set_args, args); REQUEST_STRING_ATTR_READER(request_get_content_type, content_type); /* * call-seq: * req.dispatch_handler -> string * * Get the name of the dispatch handler for the current request. For mod_ruby * handlers, for example, this will be 'ruby-object'. * */ REQUEST_STRING_ATTR_READER(request_get_dispatch_handler, handler); /* * call-seq: * req.dispatch_handler = handler * * Set a handler for the request. The +handler+ is the name of a handler * like the ones used in the SetHandler directive (e.g., 'None', * 'imap-file', 'cgi-script', etc.) * */ REQUEST_STRING_ATTR_WRITER(request_set_dispatch_handler, handler); /* * call-seq: * req.content_encoding -> string * * Return any additional content codings that have been applied to the * entity-body, and thus what decoding mechanisms must be applied in order * to obtain the media-type referenced by the Content-Type header field. * The encoding is primarily used to allow a document to be compressed * without losing the identity of its underlying media type. * * if req.content_encoding == 'gzip' * # decompress the entity body * end */ REQUEST_STRING_ATTR_READER(request_get_content_encoding, content_encoding); static VALUE request_request_time(VALUE self) { request_data *data; data = get_request_data(self); return rb_time_new(apr_time_sec(data->request->request_time), 0); } static VALUE request_header_only(VALUE self) { request_data *data; data = get_request_data(self); return data->request->header_only ? Qtrue : Qfalse; } static VALUE request_content_length(VALUE self) { request_data *data; const char *s; rb_warn("content_length is obsolete; use headers_in[\"Content-Length\"] instead"); data = get_request_data(self); s = apr_table_get(data->request->headers_in, "Content-Length"); return s ? rb_cstr2inum(s, 10) : Qnil; } /* * call-seq: * request.content_type = mimetype -> nil * * Set the MIME content type of the response. * @param [String] mimetype Set the mimetype associated with the response. */ static VALUE request_set_content_type(VALUE self, VALUE str) { request_data *data; data = get_request_data(self); if (NIL_P(str)) { data->request->content_type = NULL; } else { Check_Type(str, T_STRING); data->request->content_type = apr_pstrndup(data->request->pool, RSTRING_PTR(str), RSTRING_LEN(str)); } return Qnil; } /* * call-seq: * request.content_encoding = encoding * * Set the content-encoding of the response body. Note that this is * *not* the same as the character set of the response -- that should * be set as part of the Content-Type header ({#content_type}). * * @param [String] encoding the content-encoding of the response body * @example Indicate that the response body is compressed. * req.content_encoding = 'gzip' */ static VALUE request_set_content_encoding(VALUE self, VALUE str) { request_data *data; data = get_request_data(self); if (NIL_P(str)) { data->request->content_encoding = NULL; } else { Check_Type(str, T_STRING); data->request->content_encoding = apr_pstrndup(data->request->pool, RSTRING_PTR(str), RSTRING_LEN(str)); } return str; } static VALUE request_get_content_languages(VALUE self) { request_data *data; data = get_request_data(self); if (data->request->content_languages) { return rb_apache_array_new(data->request->content_languages); } else { return Qnil; } } static VALUE request_set_content_languages(VALUE self, VALUE ary) { request_data *data; int i; data = get_request_data(self); if (NIL_P(ary)) { data->request->content_languages = NULL; } else { Check_Type(ary, T_ARRAY); for (i = 0; i < RARRAY_LEN(ary); i++) { Check_Type(RARRAY_PTR(ary)[i], T_STRING); } data->request->content_languages = apr_array_make(data->request->pool, RARRAY_LEN(ary), sizeof(char *)); for (i = 0; i < RARRAY_LEN(ary); i++) { VALUE str = RARRAY_PTR(ary)[i]; *(char **) apr_array_push(data->request->content_languages) = apr_pstrndup(data->request->pool, RSTRING_PTR(str), RSTRING_LEN(str)); } } return ary; } static VALUE request_headers_in(VALUE self) { request_data *data; data = get_request_data(self); if (NIL_P(data->headers_in)) { data->headers_in = rb_apache_table_new(data->request->headers_in); } return data->headers_in; } static VALUE request_headers_out(VALUE self) { request_data *data; data = get_request_data(self); if (NIL_P(data->headers_out)) { data->headers_out = rb_apache_table_new(data->request->headers_out); } return data->headers_out; } static VALUE request_err_headers_out(VALUE self) { request_data *data; data = get_request_data(self); if (NIL_P(data->err_headers_out)) { data->err_headers_out = rb_apache_table_new(data->request->err_headers_out); } return data->err_headers_out; } static VALUE request_subprocess_env(VALUE self) { request_data *data; data = get_request_data(self); if (NIL_P(data->subprocess_env)) { data->subprocess_env = rb_apache_table_new(data->request->subprocess_env); } return data->subprocess_env; } static VALUE request_notes(VALUE self) { request_data *data; data = get_request_data(self); if (NIL_P(data->notes)) { data->notes = rb_apache_table_new(data->request->notes); } return data->notes; } #ifndef RUBY_VM #ifdef WIN32 typedef int mode_t; #endif static mode_t get_mode(apr_finfo_t *finfo) { mode_t mode = 0; if (finfo->protection & APR_UREAD) mode |= S_IRUSR; if (finfo->protection & APR_UWRITE) mode |= S_IWUSR; if (finfo->protection & APR_UEXECUTE) mode |= S_IXUSR; if (finfo->protection & APR_GREAD) mode |= S_IRGRP; if (finfo->protection & APR_GWRITE) mode |= S_IWGRP; if (finfo->protection & APR_GEXECUTE) mode |= S_IXGRP; if (finfo->protection & APR_WREAD) mode |= S_IROTH; if (finfo->protection & APR_WWRITE) mode |= S_IWOTH; if (finfo->protection & APR_WEXECUTE) mode |= S_IXOTH; switch (finfo->filetype) { case APR_REG: mode |= S_IFREG; break; case APR_DIR: mode |= S_IFDIR; break; case APR_CHR: mode |= S_IFCHR; break; case APR_BLK: #ifndef WIN32 mode |= S_IFBLK; #endif break; case APR_PIPE: #ifndef WIN32 mode |= S_IFIFO; #endif break; case APR_LNK: #ifndef WIN32 mode |= S_IFLNK; #endif break; case APR_SOCK: #if !defined(BEOS) && defined(S_ISSOCK) mode |= S_IFSOCK; #endif break; default: break; } return mode; } #endif /* RUBY_VM */ static VALUE request_finfo(VALUE self) { request_data *data; data = get_request_data(self); if (NIL_P(data->finfo)) { #ifdef RUBY_VM data->finfo = rb_protect_funcall(rb_cFile, rb_intern("stat"), NULL, 1, rb_str_new2(data->request->filename)); #else VALUE cStat; struct stat *st; cStat = rb_const_get(rb_cFile, rb_intern("Stat")); data->finfo = Data_Make_Struct(cStat, struct stat, NULL, free, st); memset(st, 0, sizeof(struct stat)); if (data->request->finfo.filetype != 0) { st->st_dev = data->request->finfo.device; st->st_ino = data->request->finfo.inode; st->st_nlink = data->request->finfo.nlink; st->st_mode = get_mode(&data->request->finfo); st->st_uid = data->request->finfo.user; st->st_gid = data->request->finfo.group; st->st_size = data->request->finfo.size; st->st_atime = apr_time_sec(data->request->finfo.atime); st->st_mtime = apr_time_sec(data->request->finfo.mtime); st->st_ctime = apr_time_sec(data->request->finfo.ctime); } #endif } return data->finfo; } static VALUE request_parsed_uri(VALUE self) { request_data *data; data = get_request_data(self); if (NIL_P(data->parsed_uri)) { data->parsed_uri = rb_apache_uri_new(&data->request->parsed_uri); } return data->parsed_uri; } /* * Arbitrary Hash of values that will be passed between handlers, and garbage-collected * when the request is done. * * @return [Hash] the Hash of request attributes * @example Pass a user object from a RubyAuthenHandler to later handlers to avoid having to look it up again. * * def authenticate( req ) * username = req.user * password = req.get_basic_auth_pw * if user = User.find( username ) && user.auth( password ) * req.attributes[:user] = user * return Apache::OK * else * ... * end * end * */ static VALUE request_attributes(VALUE self) { request_data *data; data = get_request_data(self); if (NIL_P(data->attributes)) data->attributes = rb_hash_new(); return data->attributes; } static VALUE request_setup_client_block(int argc, VALUE *argv, VALUE self) { request_data *data; VALUE policy; int read_policy = REQUEST_CHUNKED_ERROR; data = get_request_data(self); if (rb_scan_args(argc, argv, "01", &policy) == 1) { read_policy = NUM2INT(policy); } return INT2NUM(ap_setup_client_block(data->request, read_policy)); } static VALUE request_should_client_block(VALUE self) { request_data *data; data = get_request_data(self); return INT2BOOL(ap_should_client_block(data->request)); } static VALUE request_get_client_block(VALUE self, VALUE length) { request_data *data; int len; VALUE result; data = get_request_data(self); len = NUM2INT(length); #if RUBY_VERSION_CODE < 180 { char *buf = (char *) ap_palloc(data->request->pool, len); len = ap_get_client_block(data->request, buf, len); result = rb_tainted_str_new(buf, len); return result; } #else result = rb_str_buf_new(len); len = ap_get_client_block(data->request, RSTRING_PTR(result), len); switch (len) { case -1: rb_raise(rb_eApachePrematureChunkEndError, "premature chunk end"); break; case 0: return Qnil; default: rb_str_resize(result, len); OBJ_TAINT(result); return result; } #endif } static VALUE read_client_block(request_rec *r, int len) { char *buf; int rc; int nrd = 0; int old_read_length; VALUE result; if (r->read_length == 0) { if ((rc = ap_setup_client_block(r, REQUEST_CHUNKED_ERROR)) != OK) { rb_apache_exit(rc); } } old_read_length = r->read_length; r->read_length = 0; if (ap_should_client_block(r)) { if (len < 0) len = r->remaining; buf = (char *) apr_palloc(r->pool, len); result = rb_tainted_str_new("", 0); while (len > 0) { nrd = ap_get_client_block(r, buf, len); if (nrd == 0) { break; } if (nrd == -1) { r->read_length += old_read_length; rb_raise(rb_eApachePrematureChunkEndError, "premature chunk end"); } rb_str_cat(result, buf, nrd); len -= nrd; } } else { result = Qnil; } r->read_length += old_read_length; return result; } static VALUE request_read(int argc, VALUE *argv, VALUE self) { request_data *data; VALUE length; int len; data = get_request_data(self); rb_scan_args(argc, argv, "01", &length); if (NIL_P(length)) { return read_client_block(data->request, -1); } len = NUM2INT(length); if (len < 0) { rb_raise(rb_eArgError, "negative length %d given", len); } return read_client_block(data->request, len); } static VALUE request_getc(VALUE self) { request_data *data; VALUE str; data = get_request_data(self); str = read_client_block(data->request, 1); if (NIL_P(str) || RSTRING_LEN(str) == 0) return Qnil; return INT2FIX(RSTRING_PTR(str)[0]); } static VALUE request_eof(VALUE self) { request_data *data; data = get_request_data(self); return INT2BOOL(data->request->remaining == 0); } /* * @deprecated This no longer does anything at all. It used to put the input data stream * into binary mode on Win32. */ static VALUE request_binmode(VALUE self) { return Qnil; } /* * Returns a bitmask that specifies what options are enabled for the directory to which the * request has been mapped. You can use the Apache module's options bitmask constants * (+Apache::OPT_*+) to test for desired values. * * @return [Integer] the options bitmask * @example * include Apache * * # Make sure that ExecCGI and Indexes are turned on for the Location * # being served: * unless ( req.allow_options & OPT_EXECCGI|OPT_INDEXES ) * req.log_reason( "ExecCGI and/or Indexes are off in this directory", * req.filename ) * return FORBIDDEN * end * */ static VALUE request_allow_options(VALUE self) { request_data *data; data = get_request_data(self); return INT2NUM(ap_allow_options(data->request)); } /* * Returns a bitmask that specifies what options are allowed to be overridden according to the * value of the AllowOverride directives that apply to this request. Like {#allow_options}, the * value can be tested with the +Apache::OPT_+ constants. * * @return [Integer] the overrides bitmask */ static VALUE request_allow_overrides(VALUE self) { request_data *data; data = get_request_data(self); return INT2NUM(ap_allow_overrides(data->request)); } static VALUE request_default_type(VALUE self) { request_data *data; const char *type; data = get_request_data(self); type = ap_default_type(data->request); return type ? rb_tainted_str_new2(type) : Qnil; } static VALUE request_default_port(VALUE self) { request_data *data; data = get_request_data(self); return INT2NUM(ap_default_port(data->request)); } static VALUE request_remote_host(int argc, VALUE *argv, VALUE self) { request_data *data; const char *host; VALUE lookup_type; int lookup_val = REMOTE_HOST; if (argc == 1) { rb_scan_args(argc, argv, "01", &lookup_type); switch (NUM2INT(lookup_type)) { case REMOTE_HOST: lookup_val = REMOTE_HOST; break; case REMOTE_NAME: lookup_val = REMOTE_NAME; break; case REMOTE_NOLOOKUP: lookup_val = REMOTE_NOLOOKUP; break; case REMOTE_DOUBLE_REV: lookup_val = REMOTE_DOUBLE_REV; break; default: lookup_val = REMOTE_HOST; } } data = get_request_data(self); host = ap_get_remote_host(data->request->connection, data->request->per_dir_config, lookup_val, NULL); return host ? rb_tainted_str_new2(host) : Qnil; } static VALUE request_remote_logname(VALUE self) { request_data *data; const char *logname; data = get_request_data(self); logname = ap_get_remote_logname(data->request); return logname ? rb_tainted_str_new2(logname) : Qnil; } /* * call-seq: * construct_url( path ) -> uristring * * Make a fully-qualified URI String from the specified +path+, using the * request object's server name and port. * @param [String, #to_str] path the path to include in the URL * @return [String] the new URL string * @example Redirect to an advisory page on the same server if the database is down. * def handler( req ) * unless @db_conn.connected? * req.server.log_error "Database down. Redirecting to the placeholder page." * req.err_headers_out['Location'] = req.construct_url('/database-down.html') * return Apache::HTTP_TEMPORARY_REDIRECT * end * ... * end */ static VALUE request_construct_url(VALUE self, VALUE path) { request_data *data; char *url; data = get_request_data(self); url = ap_construct_url(data->request->pool, StringValuePtr(path), data->request); return rb_tainted_str_new2(url); } static VALUE request_server_name(VALUE self) { request_data *data; data = get_request_data(self); return rb_tainted_str_new2(ap_get_server_name(data->request)); } static VALUE request_server_port(VALUE self) { request_data *data; data = get_request_data(self); return INT2NUM(ap_get_server_port(data->request)); } static VALUE request_satisfies(VALUE self) { request_data *data; data = get_request_data(self); return INT2NUM(ap_satisfies(data->request)); } static VALUE request_requires(VALUE self) { VALUE result, req; request_data *data; const array_header *reqs_arr; require_line *reqs; int i; data = get_request_data(self); reqs_arr = ap_requires(data->request); if (reqs_arr == NULL) return Qnil; reqs = (require_line *) reqs_arr->elts; result = rb_ary_new2(reqs_arr->nelts); for (i = 0; i < reqs_arr->nelts; i++) { req = rb_assoc_new(INT2NUM(reqs[i].method_mask), rb_tainted_str_new2(reqs[i].requirement)); rb_ary_push(result, req); } return result; } static VALUE request_escape_html(VALUE self, VALUE str) { request_data *data; char *tmp; VALUE result; data = get_request_data(self); tmp = ap_escape_html(data->request->pool, StringValuePtr(str)); result = rb_str_new2(tmp); OBJ_INFECT(result, str); return result; } static VALUE request_signature(VALUE self) { request_data *data; data = get_request_data(self); return rb_tainted_str_new2(ap_psignature("", data->request)); } static VALUE request_reset_timeout(VALUE self) { rb_notimplement(); return Qnil; } static VALUE request_hard_timeout(VALUE self, VALUE name) { rb_notimplement(); return Qnil; } static VALUE request_soft_timeout(VALUE self, VALUE name) { request_data *data; char *s; Check_Type(name, T_STRING); data = get_request_data(self); s = apr_pstrndup(data->request->pool, RSTRING_PTR(name), RSTRING_LEN(name)); ap_soft_timeout(s, data->request); return Qnil; } static VALUE request_kill_timeout(VALUE self) { request_data *data; data = get_request_data(self); ap_kill_timeout(data->request); return Qnil; } static VALUE request_note_auth_failure(VALUE self) { request_data *data; data = get_request_data(self); ap_note_auth_failure(data->request); return Qnil; } static VALUE request_note_basic_auth_failure(VALUE self) { request_data *data; data = get_request_data(self); ap_note_basic_auth_failure(data->request); return Qnil; } static VALUE request_note_digest_auth_failure(VALUE self) { request_data *data; data = get_request_data(self); ap_note_digest_auth_failure(data->request); return Qnil; } static VALUE request_get_basic_auth_pw(VALUE self) { request_data *data; const char *pw; int res; data = get_request_data(self); if ((res = ap_get_basic_auth_pw(data->request, &pw)) != OK) { rb_apache_exit(res); } return rb_tainted_str_new2(pw); } /* * Add other Apache CGI variables to the {#subprocess_env} table, in * addition to those added by {#add_cgi_vars}. * * @return [nil] * @example * DOCUMENT_ROOT = "/tmp" * HTTP_ACCEPT = "text/plain" * HTTP_HOST = "localhost:63093" * PATH = "/bin:/usr/bin" * REMOTE_ADDR = "127.0.0.1" * REMOTE_PORT = "56835" * SCRIPT_FILENAME = "/tmp/" * SERVER_ADDR = "127.0.0.1" * SERVER_ADMIN = "[no address given]" * SERVER_NAME = "localhost" * SERVER_PORT = "63093" * SERVER_SIGNATURE = "" * SERVER_SOFTWARE = "Apache/2.2.15 (Unix) mod_ruby/1.3.0" */ static VALUE request_add_common_vars(VALUE self) { request_data *data; data = get_request_data(self); ap_add_common_vars(data->request); return Qnil; } /* * Add the variables required by the CGI/1.1 protocol to the {#subprocess_env} table. * * @return [nil] * @example * GATEWAY_INTERFACE = 'CGI/1.1' * QUERY_STRING = '' * REQUEST_METHOD = 'GET' * REQUEST_URI = '/' * SCRIPT_NAME = '' * SERVER_PROTOCOL = 'HTTP/1.1' */ static VALUE request_add_cgi_vars(VALUE self) { request_data *data; data = get_request_data(self); ap_add_cgi_vars(data->request); return Qnil; } static VALUE request_setup_cgi_env(VALUE self) { request_data *data; data = get_request_data(self); rb_setup_cgi_env(data->request); return Qnil; } static VALUE request_log_reason(VALUE self, VALUE msg, VALUE file) { request_data *data; const char *host; Check_Type(msg, T_STRING); Check_Type(file, T_STRING); data = get_request_data(self); host = ap_get_remote_host(data->request->connection, data->request->per_dir_config, REMOTE_HOST, NULL); ap_log_error(APLOG_MARK, APLOG_ERR | APLOG_NOERRNO, 0, data->request->server, "access to %s failed for %s, reason: %s", StringValuePtr(file), host, StringValuePtr(msg)); return Qnil; } void rb_apache_request_set_error(VALUE request, VALUE errmsg, VALUE exception) { request_data *data; Data_Get_Struct(request, request_data, data); data->error_message = errmsg; data->exception = exception; } static VALUE request_error_message(VALUE self) { request_data *data; data = get_request_data(self); return data->error_message; } static VALUE request_exception(VALUE self) { request_data *data; data = get_request_data(self); return data->exception; } REQUEST_STRING_ATTR_READER(request_user, user); static VALUE request_set_user(VALUE self, VALUE val) { request_data *data; Check_Type(val, T_STRING); data = get_request_data(self); data->request->user = apr_pstrndup(data->request->pool, RSTRING_PTR(val), RSTRING_LEN(val)); return val; } /* Should only be called from inside of response handlers */ static VALUE request_internal_redirect(VALUE self, VALUE uri) { request_data *data; Check_Type(uri, T_STRING); data = get_request_data(self); ap_internal_redirect(StringValuePtr(uri), data->request); return Qnil; } static VALUE request_custom_response(VALUE self, VALUE status, VALUE string) { request_data *data; Check_Type(status, T_FIXNUM); Check_Type(string, T_STRING); data = get_request_data(self); ap_custom_response(data->request, NUM2INT(status), StringValuePtr(string)); return Qnil; } static VALUE request_is_initial(VALUE self) { request_data *data; data = get_request_data(self); if (ap_is_initial_req(data->request)) { return Qtrue; } else { return Qfalse; } } static VALUE request_is_main(VALUE self) { request_data *data; data = get_request_data(self); if (data->request->main) { return Qfalse; } else { return Qtrue; } } /* * Get the authentication type for the receiving request. * @return [String] the authentication type; usually one of "Basic" * or "Digest". */ static VALUE request_auth_type(VALUE self) { request_data *data; core_dir_config *conf; data = get_request_data(self); conf = (core_dir_config *) ap_get_module_config(data->request->per_dir_config, &core_module); if (conf->ap_auth_type) { return rb_tainted_str_new2(conf->ap_auth_type); } else { return Qnil; } } /* * call-seq: * auth_type=( authtype ) * * Set the authentication type for the receiving request. * @param [String] authtype the authentication type * @example Changing the authtype of a request based on where it's coming from (e.g., * from an RubyAuthHandler) * * def */ static VALUE request_set_auth_type(VALUE self, VALUE val) { request_data *data; core_dir_config *conf; Check_Type(val, T_STRING); data = get_request_data(self); conf = (core_dir_config *) ap_get_module_config(data->request->per_dir_config, &core_module); conf->ap_auth_type = apr_pstrndup(data->request->pool, RSTRING_PTR(val), RSTRING_LEN(val)); ap_set_module_config(data->request->per_dir_config, &core_module, conf); return val; } /* * The name of the realm in which the client must be authenticated * and authorized for the request to be successfully served. This is set * with the AuthName directive in the Apache config. * * @return [String] the AuthName or +nil+ if there is no applicable realm. * */ static VALUE request_auth_name(VALUE self) { request_data *data; core_dir_config *conf; data = get_request_data(self); conf = (core_dir_config *) ap_get_module_config(data->request->per_dir_config, &core_module); if (conf->ap_auth_name) { return rb_tainted_str_new2(conf->ap_auth_name); } else { return Qnil; } } /* * call-seq: * req.auth_name=( name ) * * Set the authentication realm for the request. * @param [String] name the name of the authentication realm */ static VALUE request_set_auth_name(VALUE self, VALUE val) { request_data *data; core_dir_config *conf; Check_Type(val, T_STRING); data = get_request_data(self); conf = (core_dir_config *) ap_get_module_config(data->request->per_dir_config, &core_module); conf->ap_auth_name = apr_pstrndup(data->request->pool, RSTRING_PTR(val), RSTRING_LEN(val)); ap_set_module_config(data->request->per_dir_config, &core_module, conf); return val; } static VALUE request_default_charset(VALUE self) { request_data *data = get_request_data(self); core_dir_config *conf = ap_get_module_config(data->request->per_dir_config, &core_module); const char *charset_name = conf->add_default_charset_name; return charset_name ? rb_tainted_str_new2(charset_name) : Qnil; } /* * call-seq: * request.bytes_sent -> int * * Returns the number of bytes sent by the server to the client, excluding the * HTTP headers. It is only useful after {#send_http_header} has been called. * */ static VALUE request_bytes_sent(VALUE self) { request_data *data; request_rec *last; data = get_request_data(self); for (last = data->request; last->next; last = data->request->next) continue; return INT2NUM(last->bytes_sent); } static VALUE request_send_fd(VALUE self, VALUE io) { rb_io_t *fptr; request_data *data; apr_size_t bytes_sent; apr_file_t *file; int fd; struct stat st; request_set_sync(self, Qtrue); rb_apache_request_flush(self); data = get_request_data(self); Check_Type(io, T_FILE); GetOpenFile(io, fptr); #ifdef RUBY_VM fd = fptr->fd; #else fd = fileno(fptr->f); #endif if (apr_os_file_put(&file, &fd, 0, data->request->pool) != APR_SUCCESS) { rb_raise(rb_eIOError, "apr_os_file_put() failed"); } if (fstat(fd, &st) == -1) { rb_sys_fail(IO_PATH(fptr)); } ap_send_fd(file, data->request, 0, st.st_size, &bytes_sent); return INT2NUM(bytes_sent); } static VALUE request_proxy_q(VALUE self) { request_data *data = get_request_data(self); switch (data->request->proxyreq) { case PROXYREQ_NONE: return Qfalse; case PROXYREQ_PROXY: case PROXYREQ_REVERSE: return Qtrue; default: rb_raise(rb_eArgError, "Unknown Proxy Type"); } } static VALUE request_proxy_pass_q(VALUE self) { request_data *data = get_request_data(self); if (data->request->proxyreq == PROXYREQ_REVERSE) return Qtrue; else return Qfalse; } /* * Returns +true+ if either of the 'Pragma' or 'Cache-control' headers * have already been added to the response headers, regardless of their * values. * * @return [boolean] true if either of the headers are present in the response. */ static VALUE request_get_cache_resp(VALUE self) { request_data *data; table *tbl; table_entry *hdrs; const array_header *hdrs_arr; int i; data = get_request_data(self); if (NIL_P(data->headers_out)) data->headers_out = rb_apache_table_new(data->request->headers_out); Data_Get_Struct(data->headers_out, table, tbl); hdrs_arr = apr_table_elts(tbl); hdrs = (table_entry *) hdrs_arr->elts; for (i = 0; i < hdrs_arr->nelts; i++) { if (hdrs[i].key == NULL) continue; if (strcasecmp(hdrs[i].key, "Pragma") || strcasecmp(hdrs[i].key, "Cache-control")) { return Qtrue; } } return Qfalse; } /* * call-seq: * req.cache_resp=( flag ) * * Enable/disable cache-control headers in the response. * * @param [boolean] flag If +true+, the response will have 'Pragma' and 'Cache-control' * headers added to the response with the values set to 'no-cache'. If +false+, either of * the same headers will be removed from the response, regardless of their value. */ static VALUE request_set_cache_resp(VALUE self, VALUE arg) { request_data *data; table *tbl; data = get_request_data(self); if (NIL_P(data->headers_out)) data->headers_out = rb_apache_table_new(data->request->headers_out); Data_Get_Struct(data->headers_out, table, tbl); if (arg == Qtrue) { apr_table_setn(tbl, "Pragma", "no-cache"); apr_table_setn(tbl, "Cache-control", "no-cache"); return Qtrue; } else { apr_table_unset(tbl, "Pragma"); apr_table_unset(tbl, "Cache-control"); return Qfalse; } } static VALUE request_lookup_uri(VALUE self, VALUE uri) { request_data *data; request_rec *new_rec; Check_Type(uri, T_STRING); data = get_request_data(self); new_rec = ap_sub_req_lookup_uri(StringValuePtr(uri), data->request, NULL); return apache_request_new(new_rec); } static VALUE request_lookup_file(VALUE self, VALUE file) { request_data *data; request_rec *new_rec; Check_Type(file, T_STRING); data = get_request_data(self); new_rec = ap_sub_req_lookup_file(StringValuePtr(file), data->request, NULL); return apache_request_new(new_rec); } typedef struct request_cleanup { pool *pool; VALUE plain_cleanup; VALUE child_cleanup; } request_cleanup_t; static VALUE call_proc_0(VALUE proc) { return rb_funcall(proc, rb_intern("call"), 0); } static void call_proc(pool *p, VALUE proc) { #if APR_HAS_THREADS if (ruby_is_threaded_mpm) { ruby_call_interpreter(p, (ruby_interp_func_t) call_proc_0, (void *) proc, NULL, 0); } else { #endif call_proc_0(proc); #if APR_HAS_THREADS } #endif } static APR_CLEANUP_RETURN_TYPE call_plain_cleanup(void *data) { request_cleanup_t *cleanup = (request_cleanup_t *) data; call_proc(cleanup->pool, cleanup->plain_cleanup); APR_CLEANUP_RETURN_SUCCESS(); } static APR_CLEANUP_RETURN_TYPE call_child_cleanup(void *data) { request_cleanup_t *cleanup = (request_cleanup_t *) data; call_proc(cleanup->pool, cleanup->child_cleanup); APR_CLEANUP_RETURN_SUCCESS(); } static VALUE request_register_cleanup(int argc, VALUE *argv, VALUE self) { request_data *data; VALUE plain_cleanup, child_cleanup; request_cleanup_t *cleanup; APR_CLEANUP_RETURN_TYPE (*plain_cleanup_func) (void *); APR_CLEANUP_RETURN_TYPE (*child_cleanup_func) (void *); data = get_request_data(self); rb_scan_args(argc, argv, "02", &plain_cleanup, &child_cleanup); if (argc == 0) plain_cleanup = rb_f_lambda(); if (NIL_P(plain_cleanup)) plain_cleanup_func = apr_pool_cleanup_null; else plain_cleanup_func = call_plain_cleanup; if (NIL_P(child_cleanup)) child_cleanup_func = apr_pool_cleanup_null; else child_cleanup_func = call_child_cleanup; cleanup = apr_palloc(data->request->pool, sizeof(request_cleanup_t)); cleanup->pool = data->request->pool; cleanup->plain_cleanup = plain_cleanup; cleanup->child_cleanup = child_cleanup; apr_pool_cleanup_register(data->request->pool, (void *) cleanup, plain_cleanup_func, child_cleanup_func); return Qnil; } static VALUE request_options(VALUE self) { request_data *data; data = get_request_data(self); return data->options; } /* * call-seq: * Apache::Request.libapreq? -> boolean * * Returns +true+ if mod_ruby has been compiled with the Apache Request library. * @deprecated This is no longer necessary, as libapreq support is built into mod_ruby itself. */ static VALUE request_libapreq_p( VALUE klass ) { return Qtrue; } static VALUE request_uploads( VALUE self ) { request_data *data = get_request_data( self ); ApacheUpload *upload; VALUE upobj; if ( !data->apreq->parsed ) rb_funcall( self, rb_intern("parse"), 0 ); #if RUBY_VM if (!RHASH(data->upload_table)->ntbl->num_entries) { #else if (!RHASH(data->upload_table)->tbl->num_entries) { #endif for ( upload = ApacheRequest_upload(data->apreq); upload; upload = upload->next ) { upobj = rb_apache_upload_new(upload); rb_hash_aset( data->upload_table, rb_tainted_str_new2(upload->name), upobj ); } } return data->upload_table; } static VALUE request_post_max_eq( VALUE self, VALUE setting ) { request_data *data = get_request_data( self ); data->apreq->post_max = NUM2INT( setting ); return INT2FIX( data->apreq->post_max ); } static VALUE request_post_max( VALUE self ) { request_data *data = get_request_data( self ); return INT2FIX( data->apreq->post_max ); } static VALUE request_disable_uploads_eq( VALUE self, VALUE setting ) { request_data *data = get_request_data( self ); data->apreq->disable_uploads = RTEST( setting ) ? 1 : 0; return data->apreq->disable_uploads ? Qtrue : Qfalse; } static VALUE request_disable_uploads_p( VALUE self ) { request_data *data = get_request_data( self ); return data->apreq->disable_uploads ? Qtrue : Qfalse; } static VALUE request_temp_dir_eq( VALUE self, VALUE setting ) { request_data *data = get_request_data( self ); SafeStringValue( setting ); data->apreq->temp_dir = StringValuePtr( setting ); return setting; } static VALUE request_temp_dir( VALUE self ) { request_data *data = get_request_data( self ); return rb_str_new2( data->apreq->temp_dir ); } static int request_call_upload_hook( VALUE self, char *buffer, int bufsize, ApacheUpload *upload ) { request_data *data = get_request_data(self); VALUE rbuf, name, upobj, rval; rbuf = rb_tainted_str_new(buffer, (long) bufsize); name = rb_tainted_str_new2(upload->name); upobj = rb_hash_aref( data->upload_table, name ); if (NIL_P(upobj)) { upobj = rb_apache_upload_new(upload); rb_hash_aset(data->upload_table, name, upobj); } rval = rb_funcall(data->upload_hook, rb_intern("call"), 3, rbuf, upobj, data->upload_hook_arg); return bufsize; } static VALUE request_upload_hook_eq( VALUE self, VALUE setting ) { request_data *data = get_request_data( self ); VALUE func = rb_check_convert_type( setting, T_DATA, "Proc", "to_proc" ); if ( !rb_obj_is_instance_of(func, rb_cProc) ) { rb_raise( rb_eTypeError, "wrong argument type %s (expected Proc)", rb_class2name(CLASS_OF(func)) ); } data->upload_hook = func; data->apreq->upload_hook = (int(*)(void*,char*,int,ApacheUpload*)) request_call_upload_hook; data->apreq->hook_data = (void *) self; return func; } static VALUE request_upload_hook( VALUE self ) { request_data *data = get_request_data( self ); return data->upload_hook; } static VALUE request_upload_hook_data_eq( VALUE self, VALUE setting ) { request_data *data = get_request_data( self ); data->upload_hook_arg = setting; return setting; } static VALUE request_upload_hook_data( VALUE self ) { request_data *data = get_request_data( self ); return data->upload_hook_arg; } static VALUE request_set_parse_option( VALUE pair, VALUE self ) { ID opt; VALUE optval; Check_Type( pair, T_ARRAY ); if ( !RARRAY_LEN(pair) == 2 ) rb_raise( rb_eArgError, "Expected an array of 2 elements, not %d", (int) RARRAY_LEN(pair) ); opt = rb_to_id( *(RARRAY_PTR(pair)) ); optval = *(RARRAY_PTR(pair) + 1); if ( opt == id_post_max ) { request_post_max_eq( self, optval ); } else if ( opt == id_disable_uploads ) { request_post_max_eq( self, optval ); } else if ( opt == id_temp_dir ) { request_temp_dir_eq( self, optval ); } else if ( opt == id_hook_data ) { request_upload_hook_data_eq( self, optval ); } else if ( opt == id_upload_hook ) { request_upload_hook_eq( self, optval ); } else { VALUE s = rb_inspect(*( RARRAY_PTR(pair) )); rb_raise( rb_eArgError, "Unknown option %s", StringValuePtr(s) ); } return optval; } static VALUE request_parse( int argc, VALUE *argv, VALUE self ) { request_data *data = get_request_data( self ); int status; VALUE options; if ( data->apreq->parsed ) return Qfalse; if( rb_scan_args(argc, argv, "01", &options) ) { Check_Type( options, T_HASH ); rb_iterate( rb_each, options, request_set_parse_option, self ); } if ( (status = ApacheRequest_parse( data->apreq )) != OK ) rb_raise( rb_eApacheRequestError, "Failed to parse request params (%d)", status ); return Qtrue; } static VALUE request_script_name(VALUE self) { request_data *data = get_request_data( self ); const char *val; val = ApacheRequest_script_name(data->apreq); return val ? rb_tainted_str_new2(val) : Qnil; } static VALUE request_script_path(VALUE self) { request_data *data = get_request_data( self ); const char *val; val = ApacheRequest_script_path(data->apreq); return val ? rb_tainted_str_new2(val) : Qnil; } static VALUE request_param(VALUE self, VALUE key) { request_data *data = get_request_data(self); const char *val; if (!data->apreq->parsed) rb_funcall(self, rb_intern("parse"), 0); val = ApacheRequest_param(data->apreq, StringValuePtr(key)); return val ? rb_tainted_str_new2(val) : Qnil; } static VALUE request_params(VALUE self, VALUE key) { request_data *data = get_request_data(self); array_header *val; if (!data->apreq->parsed) rb_funcall(self, rb_intern("parse"), 0); val = ApacheRequest_params(data->apreq, StringValuePtr(key)); return val ? rb_apache_array_new(val) : Qnil; } /* * Iterator function: makes the Hash for #all_params */ static int make_all_params(void *data, const char *key, const char *val) { VALUE hash = (VALUE) data; VALUE vkey, ary; vkey = rb_tainted_str_new2(key); ary = rb_hash_aref(hash, vkey); if (NIL_P(ary)) { ary = rb_ary_new(); rb_hash_aset(hash, vkey, ary); } rb_ary_push(ary, rb_tainted_str_new2(val)); return 1; } /* * Fetch all request parameters as a Hash of Arrays keyed by parameter name. * * @return [Hash<String => Array>] the request parameters */ static VALUE request_all_params(VALUE self, VALUE key) { request_data *data = get_request_data(self); VALUE result; if (!data->apreq->parsed) rb_funcall(self, rb_intern("parse"), 0); result = rb_hash_new(); apr_table_do(make_all_params, (void *) result, data->apreq->parms, NULL); return result; } static VALUE request_paramtable( VALUE self ) { request_data *data = get_request_data( self ); if ( !data->apreq->parsed ) rb_funcall( self, rb_intern("parse"), 0 ); if ( !RTEST(data->param_table) ) { data->param_table = rb_apache_paramtable_new(data->apreq->parms); } return data->param_table; } static VALUE request_params_as_string(VALUE self, VALUE key) { request_data *data = get_request_data( self ); const char *val; if ( !data->apreq->parsed ) rb_funcall( self, rb_intern("parse"), 0 ); val = ApacheRequest_params_as_string(data->apreq, StringValuePtr(key)); return val ? rb_tainted_str_new2(val) : Qnil; } static VALUE request_cookies( VALUE self ) { request_data *data = get_request_data( self ); if ( !data->apreq->parsed ) rb_funcall( self, rb_intern("parse"), 0 ); if ( ! RHASH_SIZE(data->cookies) ) { ApacheCookieJar *jar = ApacheCookie_parse( data->request, NULL ); int i; for ( i = 0; i < ApacheCookieJarItems(jar); i++ ) { ApacheCookie *c = ApacheCookieJarFetch( jar, i ); VALUE cookie = rb_apache_cookie_new(c); rb_hash_aset( data->cookies, rb_tainted_str_new2(c->name), cookie ); } } return data->cookies; } static VALUE request_cookies_eq( VALUE self, VALUE newhash ) { request_data *data = get_request_data( self ); Check_Type( newhash, T_HASH ); data->cookies = newhash; return newhash; } void rb_init_apache_request() { rb_eApachePrematureChunkEndError = rb_define_class_under(rb_mApache, "PrematureChunkEndError", rb_eStandardError); rb_cApacheRequest = rb_define_class_under(rb_mApache, "Request", rb_cObject); rb_include_module(rb_cApacheRequest, rb_mEnumerable); rb_undef_method(CLASS_OF(rb_cApacheRequest), "new"); rb_define_method(rb_cApacheRequest, "inspect", rb_any_to_s, 0); rb_define_method(rb_cApacheRequest, "to_s", request_output_buffer, 0); rb_define_method(rb_cApacheRequest, "output_buffer", request_output_buffer, 0); rb_define_method(rb_cApacheRequest, "replace", request_replace, -1); rb_define_method(rb_cApacheRequest, "cancel", request_cancel, 0); rb_define_method(rb_cApacheRequest, "sync_header", request_get_sync_header, 0); rb_define_method(rb_cApacheRequest, "sync_header=", request_set_sync_header, 1); rb_define_method(rb_cApacheRequest, "sync_output", request_get_sync_output, 0); rb_define_method(rb_cApacheRequest, "sync_output=", request_set_sync_output, 1); rb_define_method(rb_cApacheRequest, "sync=", request_set_sync, 1); rb_define_method(rb_cApacheRequest, "write", request_write, 1); rb_define_method(rb_cApacheRequest, "putc", request_putc, 1); rb_define_method(rb_cApacheRequest, "print", request_print, -1); rb_define_method(rb_cApacheRequest, "printf", request_printf, -1); rb_define_method(rb_cApacheRequest, "puts", request_puts, -1); rb_define_method(rb_cApacheRequest, "<<", request_addstr, 1); rb_define_method(rb_cApacheRequest, "send_http_header", rb_apache_request_send_http_header, 0); rb_define_method(rb_cApacheRequest, "sent_http_header?", request_sent_http_header, 0); rb_define_method(rb_cApacheRequest, "connection", request_connection, 0); rb_define_method(rb_cApacheRequest, "server", request_server, 0); rb_define_method(rb_cApacheRequest, "next", request_next, 0); rb_define_method(rb_cApacheRequest, "prev", request_prev, 0); rb_define_method(rb_cApacheRequest, "last", request_last, 0); rb_define_method(rb_cApacheRequest, "main", request_main, 0); rb_define_method(rb_cApacheRequest, "protocol", request_protocol, 0); rb_define_method(rb_cApacheRequest, "hostname", request_hostname, 0); rb_define_method(rb_cApacheRequest, "unparsed_uri", request_unparsed_uri, 0); rb_define_method(rb_cApacheRequest, "uri", request_get_uri, 0); rb_define_method(rb_cApacheRequest, "uri=", request_set_uri, 1); rb_define_method(rb_cApacheRequest, "filename", request_get_filename, 0); rb_define_method(rb_cApacheRequest, "filename=", request_set_filename, 1); rb_define_method(rb_cApacheRequest, "path_info", request_get_path_info, 0); rb_define_method(rb_cApacheRequest, "path_info=", request_set_path_info, 1); rb_define_method(rb_cApacheRequest, "request_time", request_request_time, 0); rb_define_method(rb_cApacheRequest, "status", request_get_status, 0); rb_define_method(rb_cApacheRequest, "status=", request_set_status, 1); rb_define_method(rb_cApacheRequest, "status_line", request_get_status_line, 0); rb_define_method(rb_cApacheRequest, "status_line=", request_set_status_line, 1); rb_define_method(rb_cApacheRequest, "request_method", request_request_method, 0); rb_define_method(rb_cApacheRequest, "method_number", request_method_number, 0); rb_define_method(rb_cApacheRequest, "allowed", request_get_allowed, 0); rb_define_method(rb_cApacheRequest, "allowed=", request_set_allowed, 1); rb_define_method(rb_cApacheRequest, "the_request", request_the_request, 0); rb_define_method(rb_cApacheRequest, "assbackwards?", request_get_assbackwards, 0); rb_define_method(rb_cApacheRequest, "assbackwards=", request_set_assbackwards, 1); rb_define_method(rb_cApacheRequest, "header_only?", request_header_only, 0); rb_define_method(rb_cApacheRequest, "args", request_get_args, 0); rb_define_method(rb_cApacheRequest, "args=", request_set_args, 1); rb_define_method(rb_cApacheRequest, "content_length", request_content_length, 0); rb_define_method(rb_cApacheRequest, "content_type", request_get_content_type, 0); rb_define_method(rb_cApacheRequest, "content_type=", request_set_content_type, 1); rb_define_method(rb_cApacheRequest, "content_encoding", request_get_content_encoding, 0); rb_define_method(rb_cApacheRequest, "content_encoding=", request_set_content_encoding, 1); rb_define_method(rb_cApacheRequest, "content_languages", request_get_content_languages, 0); rb_define_method(rb_cApacheRequest, "content_languages=", request_set_content_languages, 1); rb_define_method(rb_cApacheRequest, "headers_in", request_headers_in, 0); rb_define_method(rb_cApacheRequest, "headers_out", request_headers_out, 0); rb_define_method(rb_cApacheRequest, "err_headers_out", request_err_headers_out, 0); rb_define_method(rb_cApacheRequest, "subprocess_env", request_subprocess_env, 0); rb_define_method(rb_cApacheRequest, "notes", request_notes, 0); rb_define_method(rb_cApacheRequest, "finfo", request_finfo, 0); rb_define_method(rb_cApacheRequest, "parsed_uri", request_parsed_uri, 0); rb_define_method(rb_cApacheRequest, "attributes", request_attributes, 0); rb_define_method(rb_cApacheRequest, "setup_client_block", request_setup_client_block, -1); rb_define_method(rb_cApacheRequest, "should_client_block", request_should_client_block, 0); rb_define_method(rb_cApacheRequest, "should_client_block?", request_should_client_block, 0); rb_define_method(rb_cApacheRequest, "get_client_block", request_get_client_block, 1); rb_define_method(rb_cApacheRequest, "read", request_read, -1); rb_define_method(rb_cApacheRequest, "getc", request_getc, 0); rb_define_method(rb_cApacheRequest, "eof", request_eof, 0); rb_define_method(rb_cApacheRequest, "eof?", request_eof, 0); rb_define_method(rb_cApacheRequest, "binmode", request_binmode, 0); rb_define_method(rb_cApacheRequest, "allow_options", request_allow_options, 0); rb_define_method(rb_cApacheRequest, "allow_overrides", request_allow_overrides, 0); rb_define_method(rb_cApacheRequest, "default_type", request_default_type, 0); rb_define_method(rb_cApacheRequest, "default_port", request_default_port, 0); rb_define_method(rb_cApacheRequest, "remote_host", request_remote_host, -1); rb_define_method(rb_cApacheRequest, "remote_logname", request_remote_logname, 0); rb_define_method(rb_cApacheRequest, "construct_url", request_construct_url, 1); rb_define_method(rb_cApacheRequest, "server_name", request_server_name, 0); rb_define_method(rb_cApacheRequest, "server_port", request_server_port, 0); rb_define_method(rb_cApacheRequest, "satisfies", request_satisfies, 0); rb_define_method(rb_cApacheRequest, "requires", request_requires, 0); rb_define_method(rb_cApacheRequest, "escape_html", request_escape_html, 1); rb_define_method(rb_cApacheRequest, "signature", request_signature, 0); rb_define_method(rb_cApacheRequest, "reset_timeout", request_reset_timeout, 0); rb_define_method(rb_cApacheRequest, "hard_timeout", request_hard_timeout, 1); rb_define_method(rb_cApacheRequest, "soft_timeout", request_soft_timeout, 1); rb_define_method(rb_cApacheRequest, "kill_timeout", request_kill_timeout, 0); rb_define_method(rb_cApacheRequest, "internal_redirect", request_internal_redirect, 1); rb_define_method(rb_cApacheRequest, "custom_response", request_custom_response, 2); rb_define_method(rb_cApacheRequest, "main?", request_is_main, 0); rb_define_method(rb_cApacheRequest, "initial?", request_is_initial, 0); rb_define_method(rb_cApacheRequest, "note_auth_failure", request_note_auth_failure, 0); rb_define_method(rb_cApacheRequest, "note_basic_auth_failure", request_note_basic_auth_failure, 0); rb_define_method(rb_cApacheRequest, "note_digest_auth_failure", request_note_digest_auth_failure, 0); rb_define_method(rb_cApacheRequest, "get_basic_auth_pw", request_get_basic_auth_pw, 0); rb_define_method(rb_cApacheRequest, "add_common_vars", request_add_common_vars, 0); rb_define_method(rb_cApacheRequest, "add_cgi_vars", request_add_cgi_vars, 0); rb_define_method(rb_cApacheRequest, "setup_cgi_env", request_setup_cgi_env, 0); rb_define_method(rb_cApacheRequest, "log_reason", request_log_reason, 2); rb_define_method(rb_cApacheRequest, "error_message", request_error_message, 0); rb_define_method(rb_cApacheRequest, "exception", request_exception, 0); rb_define_method(rb_cApacheRequest, "user", request_user, 0); rb_define_method(rb_cApacheRequest, "user=", request_set_user, 1); rb_define_method(rb_cApacheRequest, "auth_type", request_auth_type, 0); rb_define_method(rb_cApacheRequest, "auth_type=", request_set_auth_type, 1); rb_define_method(rb_cApacheRequest, "auth_name", request_auth_name, 0); rb_define_method(rb_cApacheRequest, "auth_name=", request_set_auth_name, 1); rb_define_method(rb_cApacheRequest, "default_charset", request_default_charset, 0); rb_define_method(rb_cApacheRequest, "bytes_sent", request_bytes_sent, 0); rb_define_method(rb_cApacheRequest, "send_fd", request_send_fd, 1); rb_define_method(rb_cApacheRequest, "proxy?", request_proxy_q, 0); rb_define_method(rb_cApacheRequest, "proxy_pass?", request_proxy_pass_q, 0); rb_define_method(rb_cApacheRequest, "dispatch_handler", request_get_dispatch_handler, 0); rb_define_method(rb_cApacheRequest, "dispatch_handler=", request_set_dispatch_handler, 1); rb_define_method(rb_cApacheRequest, "cache_resp", request_get_cache_resp, 0); rb_define_method(rb_cApacheRequest, "cache_resp=", request_set_cache_resp, 1); rb_define_method(rb_cApacheRequest, "lookup_uri", request_lookup_uri, 1); rb_define_method(rb_cApacheRequest, "lookup_file", request_lookup_file, 1); rb_define_method(rb_cApacheRequest, "register_cleanup", request_register_cleanup, -1); rb_define_method(rb_cApacheRequest, "options", request_options, 0); rb_define_singleton_method(rb_cApacheRequest, "libapreq?", request_libapreq_p, 0 ); id_post_max = rb_intern( "post_max" ); id_disable_uploads = rb_intern( "disable_uploads" ); id_temp_dir = rb_intern( "temp_dir" ); id_hook_data = rb_intern( "hook_data" ); id_upload_hook = rb_intern( "upload_hook" ); rb_define_method(rb_cApacheRequest, "parse", request_parse, -1); rb_define_method(rb_cApacheRequest, "script_name", request_script_name, 0); rb_define_method(rb_cApacheRequest, "script_path", request_script_path, 0); rb_define_method(rb_cApacheRequest, "param", request_param, 1); rb_define_method(rb_cApacheRequest, "params", request_params, 1); rb_define_method(rb_cApacheRequest, "all_params", request_all_params, 0); rb_define_method(rb_cApacheRequest, "paramtable", request_paramtable, 0); rb_define_method(rb_cApacheRequest, "params_as_string", request_params_as_string, 1); rb_define_method(rb_cApacheRequest, "uploads", request_uploads, 0); rb_define_method(rb_cApacheRequest, "cookies", request_cookies, 0); rb_define_method(rb_cApacheRequest, "cookies=", request_cookies_eq, 1); rb_define_method(rb_cApacheRequest, "post_max=", request_post_max_eq, 1); rb_define_method(rb_cApacheRequest, "post_max", request_post_max, 0); rb_define_method(rb_cApacheRequest, "disable_uploads=", request_disable_uploads_eq, 1); rb_define_method(rb_cApacheRequest, "disable_uploads?", request_disable_uploads_p, 0); rb_define_alias (rb_cApacheRequest, "uploads_disabled?", "disable_uploads?"); rb_define_method(rb_cApacheRequest, "temp_dir=", request_temp_dir_eq, 1); rb_define_method(rb_cApacheRequest, "temp_dir", request_temp_dir, 0); rb_define_method(rb_cApacheRequest, "upload_hook=", request_upload_hook_eq, 1); rb_define_method(rb_cApacheRequest, "upload_hook", request_upload_hook, 0); rb_define_method(rb_cApacheRequest, "upload_hook_data=", request_upload_hook_data_eq, 1); rb_define_method(rb_cApacheRequest, "upload_hook_data", request_upload_hook_data, 0); } /* * Local variables: * mode: C * tab-width: 8 * End: */ /* vim: set filetype=c ts=8 sw=4 : */
/* * Copyright (c) 2010, Anima Games, Benjamin Karaban, Laurent Schneider, * Jérémie Comarmond, Didier Colin. * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * - Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * - Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * - Neither the name of the copyright holder nor the names of its * contributors may be used to endorse or promote products derived from * this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS * IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED * TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A * PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER * OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #ifndef RENDERER_IRECTANGLE_H_ #define RENDERER_IRECTANGLE_H_ #include <Core/Standard.h> #include <Core/Math/Vector.h> #include <Renderer/IPictureBank.h> namespace Renderer { class LM_API_RDR IRectangle { public: virtual ~IRectangle() {}; virtual void setPosition(const Core::Vector2f & position) = 0; virtual const Core::Vector2f & getPosition() const = 0; virtual void setSize(const Core::Vector2f & size) = 0; virtual const Core::Vector2f & getSize() const = 0; virtual void setPicture(const PictureInfos & pic) = 0; virtual const PictureInfos & getPicture() const = 0; virtual void setPriority(int32 p) = 0; virtual int32 getPriority() const = 0; virtual void setColor(const Core::Vector4f & color) = 0; virtual const Core::Vector4f & getColor() const = 0; virtual void setVisible(bool flag) = 0; virtual bool isVisible() const = 0; virtual void kill() = 0; virtual bool isAlive() const = 0; }; } #endif
#ifndef PROCESS_H #define PROCESS_H #include <string> /* Basic class for Process representation It contains relevant attributes as shown below */ class Process { public: Process(int pid); int Pid(); std::string User(); std::string Command(); float CpuUtilization() const; std::string Ram(); long int UpTime(); bool operator<(Process const& a) const; static bool Compare (Process &a, Process &b); private: int pid_; std::string user_; std::string command_; }; #endif
#if (__LSB_VERSION__ >= 31 ) #ifndef _QTCORE_QTRANSLATOR_H_ #define _QTCORE_QTRANSLATOR_H_ class QTranslator; // *INDENT-OFF* class QTranslator; /* Function prototypes */ extern struct QMetaObject _ZN11QTranslator16staticMetaObjectE; // *INDENT-ON* #endif /* protection */ #endif /* LSB version */
// Auto-generated file. Do not edit! // Template: src/qs8-gemm/c2-neon-mull-dup.c.in // Generator: tools/xngen // // Copyright 2021 Google LLC // // This source code is licensed under the BSD-style license found in the // LICENSE file in the root directory of this source tree. #include <assert.h> #include <arm_neon.h> #include <xnnpack/gemm.h> #include <xnnpack/math.h> void xnn_qs8_gemm_minmax_fp32_ukernel_2x8c2__neon_mlal_dup( size_t mr, size_t nc, size_t kc, const int8_t* restrict a, size_t a_stride, const void* restrict w, int8_t* restrict c, size_t cm_stride, size_t cn_stride, const union xnn_qs8_conv_minmax_params params[restrict XNN_MIN_ELEMENTS(1)]) XNN_OOB_READS { assert(mr != 0); assert(mr <= 2); assert(nc != 0); assert(kc != 0); assert(kc % sizeof(int8_t) == 0); assert(a != NULL); assert(w != NULL); assert(c != NULL); kc = round_up_po2(kc, 2 * sizeof(int8_t)); const int8_t* a0 = a; int8_t* c0 = c; const int8_t* a1 = (const int8_t*) ((uintptr_t) a0 + a_stride); int8_t* c1 = (int8_t*) ((uintptr_t) c0 + cm_stride); if XNN_UNPREDICTABLE(mr != 2) { a1 = a0; c1 = c0; } do { int32x4_t vacc0x0123 = vld1q_s32(w); w = (const void*) ((uintptr_t) w + 4 * sizeof(int32_t)); int32x4_t vacc0x4567 = vld1q_s32(w); w = (const void*) ((uintptr_t) w + 4 * sizeof(int32_t)); int32x4_t vacc1x0123 = vacc0x0123; int32x4_t vacc1x4567 = vacc0x4567; size_t k = kc; while (k >= 16 * sizeof(int8_t)) { const int8x8_t va0x0 = vld1_s8(a0); a0 += 8; const int8x8_t va0x1 = vld1_s8(a0); a0 += 8; const int8x8_t va1x0 = vld1_s8(a1); a1 += 8; const int8x8_t va1x1 = vld1_s8(a1); a1 += 8; const int8x8_t vb0123c0x0 = vld1_s8(w); w = (const void*) ((uintptr_t) w + 8 * sizeof(int8_t)); const int8x8_t vb4567c0x0 = vld1_s8(w); w = (const void*) ((uintptr_t) w + 8 * sizeof(int8_t)); const int8x8_t vb0123c1x0 = vld1_s8(w); w = (const void*) ((uintptr_t) w + 8 * sizeof(int8_t)); const int8x8_t vb4567c1x0 = vld1_s8(w); w = (const void*) ((uintptr_t) w + 8 * sizeof(int8_t)); const int8x8_t vb0123c2x0 = vld1_s8(w); w = (const void*) ((uintptr_t) w + 8 * sizeof(int8_t)); const int8x8_t vb4567c2x0 = vld1_s8(w); w = (const void*) ((uintptr_t) w + 8 * sizeof(int8_t)); const int8x8_t vb0123c3x0 = vld1_s8(w); w = (const void*) ((uintptr_t) w + 8 * sizeof(int8_t)); const int8x8_t vb4567c3x0 = vld1_s8(w); w = (const void*) ((uintptr_t) w + 8 * sizeof(int8_t)); const int8x8_t va0c0x0 = vreinterpret_s8_s16(vdup_lane_s16(vreinterpret_s16_s8(va0x0), 0)); const int8x8_t va0c0x1 = vreinterpret_s8_s16(vdup_lane_s16(vreinterpret_s16_s8(va0x1), 0)); const int8x8_t va1c0x0 = vreinterpret_s8_s16(vdup_lane_s16(vreinterpret_s16_s8(va1x0), 0)); const int8x8_t va1c0x1 = vreinterpret_s8_s16(vdup_lane_s16(vreinterpret_s16_s8(va1x1), 0)); int16x8_t vprod0x0123c0 = vmull_s8(vb0123c0x0, va0c0x0); int16x8_t vprod1x0123c0 = vmull_s8(vb0123c0x0, va1c0x0); const int8x8_t vb0123c0x1 = vld1_s8(w); w = (const void*) ((uintptr_t) w + 8 * sizeof(int8_t)); vprod0x0123c0 = vmlal_s8(vprod0x0123c0, vb0123c0x1, va0c0x1); vprod1x0123c0 = vmlal_s8(vprod1x0123c0, vb0123c0x1, va1c0x1); vacc0x0123 = vpadalq_s16(vacc0x0123, vprod0x0123c0); vacc1x0123 = vpadalq_s16(vacc1x0123, vprod1x0123c0); int16x8_t vprod0x4567c0 = vmull_s8(vb4567c0x0, va0c0x0); int16x8_t vprod1x4567c0 = vmull_s8(vb4567c0x0, va1c0x0); const int8x8_t vb4567c0x1 = vld1_s8(w); w = (const void*) ((uintptr_t) w + 8 * sizeof(int8_t)); vprod0x4567c0 = vmlal_s8(vprod0x4567c0, vb4567c0x1, va0c0x1); vprod1x4567c0 = vmlal_s8(vprod1x4567c0, vb4567c0x1, va1c0x1); vacc0x4567 = vpadalq_s16(vacc0x4567, vprod0x4567c0); vacc1x4567 = vpadalq_s16(vacc1x4567, vprod1x4567c0); const int8x8_t va0c1x0 = vreinterpret_s8_s16(vdup_lane_s16(vreinterpret_s16_s8(va0x0), 1)); const int8x8_t va0c1x1 = vreinterpret_s8_s16(vdup_lane_s16(vreinterpret_s16_s8(va0x1), 1)); const int8x8_t va1c1x0 = vreinterpret_s8_s16(vdup_lane_s16(vreinterpret_s16_s8(va1x0), 1)); const int8x8_t va1c1x1 = vreinterpret_s8_s16(vdup_lane_s16(vreinterpret_s16_s8(va1x1), 1)); int16x8_t vprod0x0123c1 = vmull_s8(vb0123c1x0, va0c1x0); int16x8_t vprod1x0123c1 = vmull_s8(vb0123c1x0, va1c1x0); const int8x8_t vb0123c1x1 = vld1_s8(w); w = (const void*) ((uintptr_t) w + 8 * sizeof(int8_t)); vprod0x0123c1 = vmlal_s8(vprod0x0123c1, vb0123c1x1, va0c1x1); vprod1x0123c1 = vmlal_s8(vprod1x0123c1, vb0123c1x1, va1c1x1); vacc0x0123 = vpadalq_s16(vacc0x0123, vprod0x0123c1); vacc1x0123 = vpadalq_s16(vacc1x0123, vprod1x0123c1); int16x8_t vprod0x4567c1 = vmull_s8(vb4567c1x0, va0c1x0); int16x8_t vprod1x4567c1 = vmull_s8(vb4567c1x0, va1c1x0); const int8x8_t vb4567c1x1 = vld1_s8(w); w = (const void*) ((uintptr_t) w + 8 * sizeof(int8_t)); vprod0x4567c1 = vmlal_s8(vprod0x4567c1, vb4567c1x1, va0c1x1); vprod1x4567c1 = vmlal_s8(vprod1x4567c1, vb4567c1x1, va1c1x1); vacc0x4567 = vpadalq_s16(vacc0x4567, vprod0x4567c1); vacc1x4567 = vpadalq_s16(vacc1x4567, vprod1x4567c1); const int8x8_t va0c2x0 = vreinterpret_s8_s16(vdup_lane_s16(vreinterpret_s16_s8(va0x0), 2)); const int8x8_t va0c2x1 = vreinterpret_s8_s16(vdup_lane_s16(vreinterpret_s16_s8(va0x1), 2)); const int8x8_t va1c2x0 = vreinterpret_s8_s16(vdup_lane_s16(vreinterpret_s16_s8(va1x0), 2)); const int8x8_t va1c2x1 = vreinterpret_s8_s16(vdup_lane_s16(vreinterpret_s16_s8(va1x1), 2)); int16x8_t vprod0x0123c2 = vmull_s8(vb0123c2x0, va0c2x0); int16x8_t vprod1x0123c2 = vmull_s8(vb0123c2x0, va1c2x0); const int8x8_t vb0123c2x1 = vld1_s8(w); w = (const void*) ((uintptr_t) w + 8 * sizeof(int8_t)); vprod0x0123c2 = vmlal_s8(vprod0x0123c2, vb0123c2x1, va0c2x1); vprod1x0123c2 = vmlal_s8(vprod1x0123c2, vb0123c2x1, va1c2x1); vacc0x0123 = vpadalq_s16(vacc0x0123, vprod0x0123c2); vacc1x0123 = vpadalq_s16(vacc1x0123, vprod1x0123c2); int16x8_t vprod0x4567c2 = vmull_s8(vb4567c2x0, va0c2x0); int16x8_t vprod1x4567c2 = vmull_s8(vb4567c2x0, va1c2x0); const int8x8_t vb4567c2x1 = vld1_s8(w); w = (const void*) ((uintptr_t) w + 8 * sizeof(int8_t)); vprod0x4567c2 = vmlal_s8(vprod0x4567c2, vb4567c2x1, va0c2x1); vprod1x4567c2 = vmlal_s8(vprod1x4567c2, vb4567c2x1, va1c2x1); vacc0x4567 = vpadalq_s16(vacc0x4567, vprod0x4567c2); vacc1x4567 = vpadalq_s16(vacc1x4567, vprod1x4567c2); const int8x8_t va0c3x0 = vreinterpret_s8_s16(vdup_lane_s16(vreinterpret_s16_s8(va0x0), 3)); const int8x8_t va0c3x1 = vreinterpret_s8_s16(vdup_lane_s16(vreinterpret_s16_s8(va0x1), 3)); const int8x8_t va1c3x0 = vreinterpret_s8_s16(vdup_lane_s16(vreinterpret_s16_s8(va1x0), 3)); const int8x8_t va1c3x1 = vreinterpret_s8_s16(vdup_lane_s16(vreinterpret_s16_s8(va1x1), 3)); int16x8_t vprod0x0123c3 = vmull_s8(vb0123c3x0, va0c3x0); int16x8_t vprod1x0123c3 = vmull_s8(vb0123c3x0, va1c3x0); const int8x8_t vb0123c3x1 = vld1_s8(w); w = (const void*) ((uintptr_t) w + 8 * sizeof(int8_t)); vprod0x0123c3 = vmlal_s8(vprod0x0123c3, vb0123c3x1, va0c3x1); vprod1x0123c3 = vmlal_s8(vprod1x0123c3, vb0123c3x1, va1c3x1); vacc0x0123 = vpadalq_s16(vacc0x0123, vprod0x0123c3); vacc1x0123 = vpadalq_s16(vacc1x0123, vprod1x0123c3); int16x8_t vprod0x4567c3 = vmull_s8(vb4567c3x0, va0c3x0); int16x8_t vprod1x4567c3 = vmull_s8(vb4567c3x0, va1c3x0); const int8x8_t vb4567c3x1 = vld1_s8(w); w = (const void*) ((uintptr_t) w + 8 * sizeof(int8_t)); vprod0x4567c3 = vmlal_s8(vprod0x4567c3, vb4567c3x1, va0c3x1); vprod1x4567c3 = vmlal_s8(vprod1x4567c3, vb4567c3x1, va1c3x1); vacc0x4567 = vpadalq_s16(vacc0x4567, vprod0x4567c3); vacc1x4567 = vpadalq_s16(vacc1x4567, vprod1x4567c3); k -= 16 * sizeof(int8_t); } if (k >= 8 * sizeof(int8_t)) { const int8x8_t va0 = vld1_s8(a0); a0 += 8; const int8x8_t va1 = vld1_s8(a1); a1 += 8; const int8x8_t vb0123c0 = vld1_s8(w); w = (const void*) ((uintptr_t) w + 8 * sizeof(int8_t)); const int8x8_t vb4567c0 = vld1_s8(w); w = (const void*) ((uintptr_t) w + 8 * sizeof(int8_t)); const int8x8_t vb0123c1 = vld1_s8(w); w = (const void*) ((uintptr_t) w + 8 * sizeof(int8_t)); const int8x8_t vb4567c1 = vld1_s8(w); w = (const void*) ((uintptr_t) w + 8 * sizeof(int8_t)); const int8x8_t vb0123c2 = vld1_s8(w); w = (const void*) ((uintptr_t) w + 8 * sizeof(int8_t)); const int8x8_t vb4567c2 = vld1_s8(w); w = (const void*) ((uintptr_t) w + 8 * sizeof(int8_t)); const int8x8_t vb0123c3 = vld1_s8(w); w = (const void*) ((uintptr_t) w + 8 * sizeof(int8_t)); const int8x8_t vb4567c3 = vld1_s8(w); w = (const void*) ((uintptr_t) w + 8 * sizeof(int8_t)); const int8x8_t va0c0 = vreinterpret_s8_s16(vdup_lane_s16(vreinterpret_s16_s8(va0), 0)); const int8x8_t va1c0 = vreinterpret_s8_s16(vdup_lane_s16(vreinterpret_s16_s8(va1), 0)); const int16x8_t vprod0x0123c0 = vmull_s8(vb0123c0, va0c0); const int16x8_t vprod1x0123c0 = vmull_s8(vb0123c0, va1c0); vacc0x0123 = vpadalq_s16(vacc0x0123, vprod0x0123c0); vacc1x0123 = vpadalq_s16(vacc1x0123, vprod1x0123c0); const int16x8_t vprod0x4567c0 = vmull_s8(vb4567c0, va0c0); const int16x8_t vprod1x4567c0 = vmull_s8(vb4567c0, va1c0); vacc0x4567 = vpadalq_s16(vacc0x4567, vprod0x4567c0); vacc1x4567 = vpadalq_s16(vacc1x4567, vprod1x4567c0); const int8x8_t va0c1 = vreinterpret_s8_s16(vdup_lane_s16(vreinterpret_s16_s8(va0), 1)); const int8x8_t va1c1 = vreinterpret_s8_s16(vdup_lane_s16(vreinterpret_s16_s8(va1), 1)); const int16x8_t vprod0x0123c1 = vmull_s8(vb0123c1, va0c1); const int16x8_t vprod1x0123c1 = vmull_s8(vb0123c1, va1c1); vacc0x0123 = vpadalq_s16(vacc0x0123, vprod0x0123c1); vacc1x0123 = vpadalq_s16(vacc1x0123, vprod1x0123c1); const int16x8_t vprod0x4567c1 = vmull_s8(vb4567c1, va0c1); const int16x8_t vprod1x4567c1 = vmull_s8(vb4567c1, va1c1); vacc0x4567 = vpadalq_s16(vacc0x4567, vprod0x4567c1); vacc1x4567 = vpadalq_s16(vacc1x4567, vprod1x4567c1); const int8x8_t va0c2 = vreinterpret_s8_s16(vdup_lane_s16(vreinterpret_s16_s8(va0), 2)); const int8x8_t va1c2 = vreinterpret_s8_s16(vdup_lane_s16(vreinterpret_s16_s8(va1), 2)); const int16x8_t vprod0x0123c2 = vmull_s8(vb0123c2, va0c2); const int16x8_t vprod1x0123c2 = vmull_s8(vb0123c2, va1c2); vacc0x0123 = vpadalq_s16(vacc0x0123, vprod0x0123c2); vacc1x0123 = vpadalq_s16(vacc1x0123, vprod1x0123c2); const int16x8_t vprod0x4567c2 = vmull_s8(vb4567c2, va0c2); const int16x8_t vprod1x4567c2 = vmull_s8(vb4567c2, va1c2); vacc0x4567 = vpadalq_s16(vacc0x4567, vprod0x4567c2); vacc1x4567 = vpadalq_s16(vacc1x4567, vprod1x4567c2); const int8x8_t va0c3 = vreinterpret_s8_s16(vdup_lane_s16(vreinterpret_s16_s8(va0), 3)); const int8x8_t va1c3 = vreinterpret_s8_s16(vdup_lane_s16(vreinterpret_s16_s8(va1), 3)); const int16x8_t vprod0x0123c3 = vmull_s8(vb0123c3, va0c3); const int16x8_t vprod1x0123c3 = vmull_s8(vb0123c3, va1c3); vacc0x0123 = vpadalq_s16(vacc0x0123, vprod0x0123c3); vacc1x0123 = vpadalq_s16(vacc1x0123, vprod1x0123c3); const int16x8_t vprod0x4567c3 = vmull_s8(vb4567c3, va0c3); const int16x8_t vprod1x4567c3 = vmull_s8(vb4567c3, va1c3); vacc0x4567 = vpadalq_s16(vacc0x4567, vprod0x4567c3); vacc1x4567 = vpadalq_s16(vacc1x4567, vprod1x4567c3); k -= 8 * sizeof(int8_t); } if XNN_UNLIKELY(k != 0) { const int8x8_t va0 = vld1_s8(a0); a0 = (const int8_t*) ((uintptr_t) a0 + k); const int8x8_t va1 = vld1_s8(a1); a1 = (const int8_t*) ((uintptr_t) a1 + k); const int8x8_t vb0123c0 = vld1_s8(w); w = (const void*) ((uintptr_t) w + 8 * sizeof(int8_t)); const int8x8_t vb4567c0 = vld1_s8(w); w = (const void*) ((uintptr_t) w + 8 * sizeof(int8_t)); const int8x8_t va0c0 = vreinterpret_s8_s16(vdup_lane_s16(vreinterpret_s16_s8(va0), 0)); const int16x8_t vprod0x0123c0 = vmull_s8(vb0123c0, va0c0); vacc0x0123 = vpadalq_s16(vacc0x0123, vprod0x0123c0); const int16x8_t vprod0x4567c0 = vmull_s8(vb4567c0, va0c0); vacc0x4567 = vpadalq_s16(vacc0x4567, vprod0x4567c0); const int8x8_t va1c0 = vreinterpret_s8_s16(vdup_lane_s16(vreinterpret_s16_s8(va1), 0)); const int16x8_t vprod1x0123c0 = vmull_s8(vb0123c0, va1c0); vacc1x0123 = vpadalq_s16(vacc1x0123, vprod1x0123c0); const int16x8_t vprod1x4567c0 = vmull_s8(vb4567c0, va1c0); vacc1x4567 = vpadalq_s16(vacc1x4567, vprod1x4567c0); if (k > 2 * sizeof(int8_t)) { const int8x8_t vb0123c1 = vld1_s8(w); w = (const void*) ((uintptr_t) w + 8 * sizeof(int8_t)); const int8x8_t vb4567c1 = vld1_s8(w); w = (const void*) ((uintptr_t) w + 8 * sizeof(int8_t)); const int8x8_t va0c1 = vreinterpret_s8_s16(vdup_lane_s16(vreinterpret_s16_s8(va0), 1)); const int16x8_t vprod0x0123c1 = vmull_s8(vb0123c1, va0c1); vacc0x0123 = vpadalq_s16(vacc0x0123, vprod0x0123c1); const int16x8_t vprod0x4567c1 = vmull_s8(vb4567c1, va0c1); vacc0x4567 = vpadalq_s16(vacc0x4567, vprod0x4567c1); const int8x8_t va1c1 = vreinterpret_s8_s16(vdup_lane_s16(vreinterpret_s16_s8(va1), 1)); const int16x8_t vprod1x0123c1 = vmull_s8(vb0123c1, va1c1); vacc1x0123 = vpadalq_s16(vacc1x0123, vprod1x0123c1); const int16x8_t vprod1x4567c1 = vmull_s8(vb4567c1, va1c1); vacc1x4567 = vpadalq_s16(vacc1x4567, vprod1x4567c1); if (k > 4 * sizeof(int8_t)) { const int8x8_t vb0123c2 = vld1_s8(w); w = (const void*) ((uintptr_t) w + 8 * sizeof(int8_t)); const int8x8_t vb4567c2 = vld1_s8(w); w = (const void*) ((uintptr_t) w + 8 * sizeof(int8_t)); const int8x8_t va0c2 = vreinterpret_s8_s16(vdup_lane_s16(vreinterpret_s16_s8(va0), 2)); const int16x8_t vprod0x0123c2 = vmull_s8(vb0123c2, va0c2); vacc0x0123 = vpadalq_s16(vacc0x0123, vprod0x0123c2); const int16x8_t vprod0x4567c2 = vmull_s8(vb4567c2, va0c2); vacc0x4567 = vpadalq_s16(vacc0x4567, vprod0x4567c2); const int8x8_t va1c2 = vreinterpret_s8_s16(vdup_lane_s16(vreinterpret_s16_s8(va1), 2)); const int16x8_t vprod1x0123c2 = vmull_s8(vb0123c2, va1c2); vacc1x0123 = vpadalq_s16(vacc1x0123, vprod1x0123c2); const int16x8_t vprod1x4567c2 = vmull_s8(vb4567c2, va1c2); vacc1x4567 = vpadalq_s16(vacc1x4567, vprod1x4567c2); } } } float32x4_t vfpacc0x0123 = vcvtq_f32_s32(vacc0x0123); float32x4_t vfpacc0x4567 = vcvtq_f32_s32(vacc0x4567); float32x4_t vfpacc1x0123 = vcvtq_f32_s32(vacc1x0123); float32x4_t vfpacc1x4567 = vcvtq_f32_s32(vacc1x4567); const float32x4_t vscale = vld1q_dup_f32(&params->fp32_neon.scale); vfpacc0x0123 = vmulq_f32(vfpacc0x0123, vscale); vfpacc0x4567 = vmulq_f32(vfpacc0x4567, vscale); vfpacc1x0123 = vmulq_f32(vfpacc1x0123, vscale); vfpacc1x4567 = vmulq_f32(vfpacc1x4567, vscale); const float32x4_t vmagic_bias = vld1q_dup_f32(&params->fp32_neon.magic_bias); vacc0x0123 = vreinterpretq_s32_f32(vaddq_f32(vfpacc0x0123, vmagic_bias)); vacc0x4567 = vreinterpretq_s32_f32(vaddq_f32(vfpacc0x4567, vmagic_bias)); vacc1x0123 = vreinterpretq_s32_f32(vaddq_f32(vfpacc1x0123, vmagic_bias)); vacc1x4567 = vreinterpretq_s32_f32(vaddq_f32(vfpacc1x4567, vmagic_bias)); const int32x4_t vmagic_bias_less_output_zero_point = vld1q_dup_s32(&params->fp32_neon.magic_bias_less_output_zero_point); vacc0x0123 = vqsubq_s32(vacc0x0123, vmagic_bias_less_output_zero_point); vacc0x4567 = vqsubq_s32(vacc0x4567, vmagic_bias_less_output_zero_point); vacc1x0123 = vqsubq_s32(vacc1x0123, vmagic_bias_less_output_zero_point); vacc1x4567 = vqsubq_s32(vacc1x4567, vmagic_bias_less_output_zero_point); #if XNN_ARCH_ARM64 int16x8_t vacc0x01234567 = vqmovn_high_s32(vqmovn_s32(vacc0x0123), vacc0x4567); int16x8_t vacc1x01234567 = vqmovn_high_s32(vqmovn_s32(vacc1x0123), vacc1x4567); int8x16_t vout0x01234567_1x01234567 = vqmovn_high_s16(vqmovn_s16(vacc0x01234567), vacc1x01234567); #else int16x8_t vacc0x01234567 = vcombine_s16(vqmovn_s32(vacc0x0123), vqmovn_s32(vacc0x4567)); int16x8_t vacc1x01234567 = vcombine_s16(vqmovn_s32(vacc1x0123), vqmovn_s32(vacc1x4567)); int8x16_t vout0x01234567_1x01234567 = vcombine_s8(vqmovn_s16(vacc0x01234567), vqmovn_s16(vacc1x01234567)); #endif const int8x16_t voutput_min = vld1q_dup_s8(&params->fp32_neon.output_min); vout0x01234567_1x01234567 = vmaxq_s8(vout0x01234567_1x01234567, voutput_min); const int8x16_t voutput_max = vld1q_dup_s8(&params->fp32_neon.output_max); vout0x01234567_1x01234567 = vminq_s8(vout0x01234567_1x01234567, voutput_max); if (nc >= 8) { vst1_s8(c0 + 0, vget_low_s8(vout0x01234567_1x01234567)); vst1_s8(c1 + 0, vget_high_s8(vout0x01234567_1x01234567)); c0 = (int8_t*) ((uintptr_t) c0 + cn_stride); c1 = (int8_t*) ((uintptr_t) c1 + cn_stride); a0 = (const int8_t*) ((uintptr_t) a0 - kc); a1 = (const int8_t*) ((uintptr_t) a1 - kc); nc -= 8; } else { // Final case where not all of the 8 columns fit in the destination. if (nc & 4) { vst1q_lane_u32((void*) c0, vreinterpretq_u32_s8(vout0x01234567_1x01234567), 0); c0 += 4; vst1q_lane_u32((void*) c1, vreinterpretq_u32_s8(vout0x01234567_1x01234567), 2); c1 += 4; vout0x01234567_1x01234567 = vextq_s8(vout0x01234567_1x01234567, vout0x01234567_1x01234567, 4); } if (nc & 2) { vst1q_lane_u16((void*) c0, vreinterpretq_u16_s8(vout0x01234567_1x01234567), 0); c0 += 2; vst1q_lane_u16((void*) c1, vreinterpretq_u16_s8(vout0x01234567_1x01234567), 4); c1 += 2; vout0x01234567_1x01234567 = vextq_s8(vout0x01234567_1x01234567, vout0x01234567_1x01234567, 2); } if (nc & 1) { vst1q_lane_s8(c0, vout0x01234567_1x01234567, 0); vst1q_lane_s8(c1, vout0x01234567_1x01234567, 8); } nc = 0; } } while (nc != 0); }
// // TBIdentifyViewController.h // TBUserIdentity // // Created by Markos Charatzas on 18/11/2012. // Copyright (c) 2012 Markos Charatzas (@qnoid). // // Permission is hereby granted, free of charge, to any person obtaining a copy of // this software and associated documentation files (the "Software"), to deal in // the Software without restriction, including without limitation the rights to // use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies // of the Software, and to permit persons to whom the Software is furnished to do // so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in all // copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE // SOFTWARE. // #import <UIKit/UIKit.h> #import "TBVerifyUserOperationDelegate.h" #import "TBCreateUserOperationDelegate.h" #import "TBEmailViewController.h" typedef NS_ENUM(NSInteger, TBEmailStatus){ TBEmailStatusError, TBEmailStatusUnknown, TBEmailStatusUnauthorised, TBEmailStatusVerified }; typedef void(^TBEmailStatusBlock)(UITableViewCell* tableViewCell); NS_INLINE TBEmailStatusBlock tbBmailStatus(TBEmailStatus emailStatus) { switch (emailStatus) { case TBEmailStatusError: return ^(UITableViewCell *tableViewCell){ tableViewCell.textLabel.enabled = NO; tableViewCell.userInteractionEnabled = YES; tableViewCell.accessoryType = UITableViewCellAccessoryDisclosureIndicator; tableViewCell.accessoryView = nil; }; case TBEmailStatusUnknown: return ^(UITableViewCell *tableViewCell){ UIActivityIndicatorView* accessoryView = [[UIActivityIndicatorView alloc] initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleGray]; [accessoryView startAnimating]; tableViewCell.selected = NO; tableViewCell.userInteractionEnabled = NO; tableViewCell.textLabel.enabled = NO; tableViewCell.accessoryView = accessoryView; }; case TBEmailStatusUnauthorised: return ^(UITableViewCell *tableViewCell){ tableViewCell.textLabel.enabled = NO; tableViewCell.userInteractionEnabled = YES; tableViewCell.accessoryType = UITableViewCellAccessoryDisclosureIndicator; tableViewCell.accessoryView = nil; }; case TBEmailStatusVerified: return ^(UITableViewCell *tableViewCell){ tableViewCell.textLabel.enabled = YES; tableViewCell.userInteractionEnabled = YES; tableViewCell.accessoryType = UITableViewCellAccessoryDisclosureIndicator; tableViewCell.accessoryView = nil; }; } } @interface TBIdentifyViewController : UIViewController <TBVerifyUserOperationDelegate, TBCreateUserOperationDelegate, TBEmailViewControllerDelegate, UITableViewDelegate> @property (nonatomic, unsafe_unretained) IBOutlet UIButton *identifyButton; @property (nonatomic, unsafe_unretained) IBOutlet UITableView *accountsTableView; +(TBIdentifyViewController*)newIdentifyViewController; -(IBAction)didTouchUpInsideIdentify:(id)sender; @end
/**************************************************************************** * binfmt/libelf/libelf_dtors.c * * Copyright (C) 2012, 2020 Gregory Nutt. All rights reserved. * Author: Gregory Nutt <gnutt@nuttx.org> * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in * the documentation and/or other materials provided with the * distribution. * 3. Neither the name NuttX nor the names of its contributors may be * used to endorse or promote products derived from this software * without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS * OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED * AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * ****************************************************************************/ /**************************************************************************** * Included Files ****************************************************************************/ #include <nuttx/config.h> #include <string.h> #include <errno.h> #include <assert.h> #include <debug.h> #include <nuttx/kmalloc.h> #include <nuttx/binfmt/elf.h> #include "libelf.h" #ifdef CONFIG_BINFMT_CONSTRUCTORS /**************************************************************************** * Pre-processor Definitions ****************************************************************************/ /**************************************************************************** * Private Types ****************************************************************************/ /**************************************************************************** * Private Constant Data ****************************************************************************/ /**************************************************************************** * Private Functions ****************************************************************************/ /**************************************************************************** * Public Functions ****************************************************************************/ /**************************************************************************** * Name: elf_loaddtors * * Description: * Load pointers to static destructors into an in-memory array. * * Input Parameters: * loadinfo - Load state information * * Returned Value: * 0 (OK) is returned on success and a negated errno is returned on * failure. * ****************************************************************************/ int elf_loaddtors(FAR struct elf_loadinfo_s *loadinfo) { FAR Elf_Shdr *shdr; size_t dtorsize; int dtoridx; int ret; int i; DEBUGASSERT(loadinfo->dtors == NULL); /* Allocate an I/O buffer if necessary. This buffer is used by * elf_sectname() to accumulate the variable length symbol name. */ ret = elf_allocbuffer(loadinfo); if (ret < 0) { berr("elf_allocbuffer failed: %d\n", ret); return -ENOMEM; } /* Find the index to the section named ".dtors." NOTE: On old ABI system, * .dtors is the name of the section containing the list of destructors; * On newer systems, the similar section is called .fini_array. It is * expected that the linker script will force the section name to be * ".dtors" in either case. */ dtoridx = elf_findsection(loadinfo, ".dtors"); if (dtoridx < 0) { /* This may not be a failure. -ENOENT indicates that the file has no * static destructor section. */ binfo("elf_findsection .dtors section failed: %d\n", dtoridx); return ret == -ENOENT ? OK : ret; } /* Now we can get a pointer to the .dtor section in the section header * table. */ shdr = &loadinfo->shdr[dtoridx]; /* Get the size of the .dtor section and the number of destructors that * will need to be called. */ dtorsize = shdr->sh_size; loadinfo->ndtors = dtorsize / sizeof(binfmt_dtor_t); binfo("dtoridx=%d dtorsize=%d sizeof(binfmt_dtor_t)=%d ndtors=%d\n", dtoridx, dtorsize, sizeof(binfmt_dtor_t), loadinfo->ndtors); /* Check if there are any destructors. It is not an error if there * are none. */ if (loadinfo->ndtors > 0) { /* Check an assumption that we made above */ DEBUGASSERT(shdr->sh_size == loadinfo->ndtors * sizeof(binfmt_dtor_t)); /* In the old ABI, the .dtors section is not allocated. In that case, * we need to allocate memory to hold the .dtors and then copy the * from the file into the allocated memory. * * SHF_ALLOC indicates that the section requires memory during * execution. */ if ((shdr->sh_flags & SHF_ALLOC) == 0) { /* Allocate memory to hold a copy of the .dtor section */ loadinfo->dtoralloc = (binfmt_dtor_t *)kumm_malloc(dtorsize); if (!loadinfo->dtoralloc) { berr("Failed to allocate memory for .dtors\n"); return -ENOMEM; } loadinfo->dtors = (binfmt_dtor_t *)loadinfo->dtoralloc; /* Read the section header table into memory */ ret = elf_read(loadinfo, (FAR uint8_t *)loadinfo->dtors, dtorsize, shdr->sh_offset); if (ret < 0) { berr("Failed to allocate .dtors: %d\n", ret); return ret; } /* Fix up all of the .dtor addresses. Since the addresses * do not lie in allocated memory, there will be no relocation * section for them. */ for (i = 0; i < loadinfo->ndtors; i++) { FAR uintptr_t *ptr = (uintptr_t *) ((FAR void *)(&loadinfo->dtors)[i]); binfo("dtor %d: %08lx + %08lx = %08lx\n", i, *ptr, (unsigned long)loadinfo->textalloc, (unsigned long)(*ptr + loadinfo->textalloc)); *ptr += loadinfo->textalloc; } } else { /* Save the address of the .dtors (actually, .init_array) where * it was loaded into memory. Since the .dtors lie in allocated * memory, they will be relocated via the normal mechanism. */ loadinfo->dtors = (binfmt_dtor_t *)shdr->sh_addr; } } return OK; } #endif /* CONFIG_BINFMT_CONSTRUCTORS */
#import <NougatUI/NougatUI.h> @interface NUALocationToggle : NUAFlipswitchButton @end
// RUN: %clang_cc1 -triple i686-windows-msvc -fms-extensions -emit-llvm -std=c11 -O0 -o - %s | FileCheck --check-prefix=CHECK --check-prefix=MS %s // RUN: %clang_cc1 -triple x86_64-windows-msvc -fms-extensions -emit-llvm -std=c11 -O0 -o - %s | FileCheck --check-prefix=CHECK --check-prefix=MS %s // RUN: %clang_cc1 -triple i686-windows-gnu -fms-extensions -emit-llvm -std=c11 -O0 -o - %s | FileCheck --check-prefix=CHECK --check-prefix=GNU %s // RUN: %clang_cc1 -triple x86_64-windows-gnu -fms-extensions -emit-llvm -std=c11 -O0 -o - %s | FileCheck --check-prefix=CHECK --check-prefix=GNU %s // RUN: %clang_cc1 -triple i686-windows-msvc -fms-extensions -emit-llvm -std=c11 -O1 -o - %s | FileCheck --check-prefix=O1 --check-prefix=MO1 %s // RUN: %clang_cc1 -triple i686-windows-gnu -fms-extensions -emit-llvm -std=c11 -O1 -o - %s | FileCheck --check-prefix=O1 --check-prefix=GO1 %s #define JOIN2(x, y) x##y #define JOIN(x, y) JOIN2(x, y) #define USEVAR(var) int JOIN(use, __LINE__)() { return var; } #define USE(func) void JOIN(use, __LINE__)() { func(); } //===----------------------------------------------------------------------===// // Globals //===----------------------------------------------------------------------===// // Import declaration. // CHECK: @ExternGlobalDecl = external dllimport global i32 __declspec(dllimport) extern int ExternGlobalDecl; USEVAR(ExternGlobalDecl) // dllimport implies a declaration. // CHECK: @GlobalDecl = external dllimport global i32 __declspec(dllimport) int GlobalDecl; USEVAR(GlobalDecl) // Redeclarations // CHECK: @GlobalRedecl1 = external dllimport global i32 __declspec(dllimport) extern int GlobalRedecl1; __declspec(dllimport) extern int GlobalRedecl1; USEVAR(GlobalRedecl1) // CHECK: @GlobalRedecl2 = external dllimport global i32 __declspec(dllimport) int GlobalRedecl2; __declspec(dllimport) int GlobalRedecl2; USEVAR(GlobalRedecl2) // NB: MSVC issues a warning and makes GlobalRedecl3 dllexport. We follow GCC // and drop the dllimport with a warning. // CHECK: @GlobalRedecl3 = external global i32 __declspec(dllimport) extern int GlobalRedecl3; extern int GlobalRedecl3; // dllimport ignored USEVAR(GlobalRedecl3) // Make sure this works even if the decl has been used before it's defined (PR20792). // MS: @GlobalRedecl4 = common dllexport global i32 // GNU: @GlobalRedecl4 = common global i32 __declspec(dllimport) extern int GlobalRedecl4; USEVAR(GlobalRedecl4) int GlobalRedecl4; // dllimport ignored // FIXME: dllimport is dropped in the AST; this should be reflected in codegen (PR02803). // CHECK: @GlobalRedecl5 = external dllimport global i32 __declspec(dllimport) extern int GlobalRedecl5; USEVAR(GlobalRedecl5) extern int GlobalRedecl5; // dllimport ignored // Redeclaration in local context. // CHECK: @GlobalRedecl6 = external dllimport global i32 __declspec(dllimport) int GlobalRedecl6; int functionScope() { extern int GlobalRedecl6; // still dllimport return GlobalRedecl6; } //===----------------------------------------------------------------------===// // Functions //===----------------------------------------------------------------------===// // Import function declaration. // CHECK-DAG: declare dllimport void @decl() __declspec(dllimport) void decl(void); // Initialize use_decl with the address of the thunk. // CHECK-DAG: @use_decl = global void ()* @decl void (*use_decl)(void) = &decl; // Import inline function. // MS-DAG: declare dllimport void @inlineFunc() // MO1-DAG: define available_externally dllimport void @inlineFunc() // GNU-DAG: declare void @inlineFunc() // GO1-DAG: define available_externally void @inlineFunc() __declspec(dllimport) inline void inlineFunc(void) {} USE(inlineFunc) // inline attributes // MS-DAG: declare dllimport void @noinline() // MO1-DAG: define available_externally dllimport void @noinline() // GNU-DAG: declare void @noinline() // GO1-DAG: define available_externally void @noinline() // CHECK-NOT: @alwaysInline() // O1-NOT: @alwaysInline() __declspec(dllimport) __attribute__((noinline)) inline void noinline(void) {} __declspec(dllimport) __attribute__((always_inline)) inline void alwaysInline(void) {} USE(noinline) USE(alwaysInline) // Redeclarations // CHECK-DAG: declare dllimport void @redecl1() __declspec(dllimport) void redecl1(void); __declspec(dllimport) void redecl1(void); USE(redecl1) // NB: MSVC issues a warning and makes redecl2/redecl3 dllexport. We follow GCC // and drop the dllimport with a warning. // CHECK-DAG: declare void @redecl2() __declspec(dllimport) void redecl2(void); void redecl2(void); USE(redecl2) // MS: define dllexport void @redecl3() // GNU: define void @redecl3() __declspec(dllimport) void redecl3(void); void redecl3(void) {} // dllimport ignored USE(redecl3) // Make sure this works even if the decl is used before it's defined (PR20792). // MS: define dllexport void @redecl4() // GNU: define void @redecl4() __declspec(dllimport) void redecl4(void); USE(redecl4) void redecl4(void) {} // dllimport ignored // FIXME: dllimport is dropped in the AST; this should be reflected in codegen (PR20803). // CHECK-DAG: declare dllimport __declspec(dllimport) void redecl5(void); USE(redecl5) void redecl5(void); // dllimport ignored
/* ************************************************************************** */ /* */ /* ::: :::::::: */ /* push_swap.h :+: :+: :+: */ /* +:+ +:+ +:+ */ /* By: gsinged <marvin@42.fr> +#+ +:+ +#+ */ /* +#+#+#+#+#+ +#+ */ /* Created: 2020/11/09 21:54:50 by gsinged #+# #+# */ /* Updated: 2020/11/09 21:54:52 by gsinged ### ########.fr */ /* */ /* ************************************************************************** */ #ifndef PUSH_SWAP_H # define PUSH_SWAP_H # include "libft.h" # include "libftprintf.h" # include <stdlib.h> typedef struct s_dllist { int n; int chunk; struct s_dllist *next; struct s_dllist *prev; } t_dllist; typedef struct s_push_swap { t_dllist *a; t_dllist *b; t_dllist *sort; int na; int nb; int len; int size; int last; int view; int chunk; } t_ps; t_dllist *ft_dllst_new(int n); void ft_dllst_insert_before(t_dllist *lst, t_dllist *new); void ft_dllst_insert_after(t_dllist *lst, t_dllist *new); void ft_dllst_insert_begin(t_dllist **lst0, t_dllist *new); void ft_dllst_insert_end(t_dllist **lst0, t_dllist *new); t_dllist *ft_dllst_begin(t_dllist *cur); t_dllist *ft_dllst_end(t_dllist *cur); void ft_dllst_pull_out(t_dllist *c); void ft_dllst_delone(t_dllist **one); void ft_dllst_delete(t_dllist **lst); t_dllist *ft_dllst_copy_one(t_dllist *one); t_dllist *ft_dllst_copy(t_dllist *a); void ft_dllst_add_sort(t_dllist *a, t_dllist *new); t_dllist *ft_dllst_copy_sort(t_dllist *a); int ft_dllst_lenght(t_dllist *d); void ft_dllst_print(t_dllist *d); void ft_dllst_change_ab(t_dllist *a); int ft_dllst_q_sort(t_dllist *a); int ft_dllst_position_min(t_dllist *d, t_dllist **lst); int ft_dllst_position_max(t_dllist *d, t_dllist **lst); t_dllist *ft_dllst_get_top_n(t_dllist *a, int n); t_dllist *ft_dllst_get_bottom_n(t_dllist *a, int n); int ft_dllst_min_n(t_dllist *a); int ft_dllst_medium_n(t_dllist *a); int ft_dllst_medium_n_chunk(t_dllist *d, int ch); int ft_dllst_min_n_chunk(t_dllist *a, int ch); int ft_dllst_max_chunk(t_dllist *a); int ft_dllst_lenght_chunk(t_dllist *d, int ch); int ft_dllst_test(t_dllist *a); int print_error(void); t_ps *init_ps(int argc, char **argv); void ft_ps_del(t_ps **ps); t_ps *ft_ps_del_null(t_ps **ps); void ft_ps_print_ab(t_ps *ps); void ft_move(t_ps *ps, int op); void ft_move_n(t_ps *ps, int m); void ft_push_move(t_ps *ps); void move_sa(t_ps *ps); void move_sb(t_ps *ps); void move_ss(t_ps *ps); void move_pa(t_ps *ps); void move_pb(t_ps *ps); void move_ra(t_ps *ps); void move_rb(t_ps *ps); void move_rr(t_ps *ps); void move_rra(t_ps *ps); void move_rrb(t_ps *ps); void move_rrr(t_ps *ps); int ft_ps(t_ps *ps); int ft_three(t_ps *ps); void ps_step_1(t_ps *ps); void ps_step1_chunk(t_ps *ps, int m); int ps_step1_ra_rra(t_ps *ps, int m); void ps_step_2(t_ps *ps); void ps_step2(t_ps *ps, int m); int ps_step2_ra_rra(t_ps *ps, int m); void ps_step_3(t_ps *ps); void ps_step3_sort(t_ps *ps); int ch(t_ps *ps); int print_res(int res); long long int ps_atoi(const char *str); int ft_is_int(long long int n); #endif
/** \file * 2d software rasterizer. <br> * * Copyright 2005-2006 Herocraft Hitech Co. Ltd.<br> * Version 1.0 beta. */ #ifndef __MD_SOFTWARE2D_H__ #define __MD_SOFTWARE2D_H__ ////////////////////////////////////////////////////////////////////////// namespace mdragon { class SpriteXScanLineInfo { public: Int x_s; Int u_s,v_s; Int x_e; Int u_e,v_e; }; #define Sprite_Transform_Sprite 1 #define Sprite_Transform_Point 2 #define Sprite_Transform_Line 3 #define Sprite_Transform_SpriteNoAngle 4 #define Sprite_Transform_Flag_SetShadow 1 #define Sprite_Transform_Flag_AddShadow 2 #define Sprite_Transform_Flag_SubShadow 4 #define Sprite_Transform_Flag_SwapU 8 #define Sprite_Transform_Flag_SwapV 16 #define Sprite_Transform_Flag_ColorRep 32 #define Sprite_Transform_Flag_NoClip 64 #define Sprite_Transform_Flag_Stencil 128 class SpriteTransformR { public: Int z_order; Byte type; Byte flags; Byte alpha; Char shadow; Sprite2D* sprite; Short xy[4][2]; Pixel color_mask; Word reserved; void Draw(Render2D* render); void DrawNoAngle(Render2D* render); }; } //namespace mdragon ////////////////////////////////////////////////////////////////////////// #endif // __MD_SOFTWARE2D_H__
// Copyright 2020 Rezantsev Sergey #ifndef MODULES_TASK_1_REZANTSEV_S_STRASSEN_STRASSEN_H_ #define MODULES_TASK_1_REZANTSEV_S_STRASSEN_STRASSEN_H_ #include <time.h> #include <random> void splitMatrix(double* a, double* a11, double* a22, double* a12, double* a21, int n); double* collectMatrix(double* a11, double* a22, double* a12, double* a21, int m); double* strassen(double* a, double* b, int n); int checkSize(int n); double* resizeMatrix(double* a, int n); double* sumMatrix(double* a, double* b, int n); double* subtMatrix(double* a, double* b, int n); double* multMatrix(double* a, double* b, int n); bool isEqMatrix(double* a, double* b, int n); #endif // MODULES_TASK_1_REZANTSEV_S_STRASSEN_STRASSEN_H_
/* main.c - Hello World demo */ /* * Copyright (c) 2012-2014 Wind River Systems, Inc. * * SPDX-License-Identifier: Apache-2.0 */ #include <zephyr.h> #include <misc/printk.h> /* * The hello world demo has two threads that utilize semaphores and sleeping * to take turns printing a greeting message at a controlled rate. The demo * shows both the static and dynamic approaches for spawning a thread; a real * world application would likely use the static approach for both threads. */ /* size of stack area used by each thread */ #define STACKSIZE 1024 /* scheduling priority used by each thread */ #define PRIORITY 7 /* delay between greetings (in ms) */ #define SLEEPTIME 500 /* * @param my_name thread identification string * @param my_sem thread's own semaphore * @param other_sem other thread's semaphore */ void helloLoop(const char *my_name, struct k_sem *my_sem, struct k_sem *other_sem) { while (1) { /* take my semaphore */ k_sem_take(my_sem, K_FOREVER); /* say "hello" */ printk("%s: Hello World from %s!\n", my_name, CONFIG_ARCH); /* wait a while, then let other thread have a turn */ k_sleep(SLEEPTIME); k_sem_give(other_sem); } } /* define semaphores */ K_SEM_DEFINE(threadA_sem, 1, 1); /* starts off "available" */ K_SEM_DEFINE(threadB_sem, 0, 1); /* starts off "not available" */ /* threadB is a dynamic thread that is spawned by threadA */ void threadB(void *dummy1, void *dummy2, void *dummy3) { /* invoke routine to ping-pong hello messages with threadA */ helloLoop(__func__, &threadB_sem, &threadA_sem); } char __noinit __stack threadB_stack_area[STACKSIZE]; /* threadA is a static thread that is spawned automatically */ void threadA(void *dummy1, void *dummy2, void *dummy3) { /* spawn threadB */ k_thread_spawn(threadB_stack_area, STACKSIZE, threadB, NULL, NULL, NULL, PRIORITY, 0, K_NO_WAIT); /* invoke routine to ping-pong hello messages with threadB */ helloLoop(__func__, &threadA_sem, &threadB_sem); } K_THREAD_DEFINE(threadA_id, STACKSIZE, threadA, NULL, NULL, NULL, PRIORITY, 0, K_NO_WAIT);
// Copyright 2013 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #ifndef CHROME_BROWSER_SYNC_FILE_SYSTEM_LOCAL_LOCAL_FILE_SYNC_SERVICE_H_ #define CHROME_BROWSER_SYNC_FILE_SYSTEM_LOCAL_LOCAL_FILE_SYNC_SERVICE_H_ #include <stdint.h> #include <map> #include <memory> #include <set> #include "base/callback.h" #include "base/memory/ref_counted.h" #include "base/memory/weak_ptr.h" #include "base/observer_list.h" #include "chrome/browser/sync_file_system/local/local_origin_change_observer.h" #include "chrome/browser/sync_file_system/remote_change_processor.h" #include "chrome/browser/sync_file_system/sync_callbacks.h" #include "chrome/browser/sync_file_system/sync_status_code.h" class GURL; class Profile; namespace storage { class FileSystemContext; } namespace leveldb { class Env; } namespace storage { class ScopedFile; } namespace sync_file_system { class FileChange; class LocalChangeProcessor; class LocalFileSyncContext; struct LocalFileSyncInfo; // Maintains local file change tracker and sync status. // Owned by SyncFileSystemService (which is a per-profile object). class LocalFileSyncService : public RemoteChangeProcessor, public LocalOriginChangeObserver, public base::SupportsWeakPtr<LocalFileSyncService> { public: typedef base::RepeatingCallback<LocalChangeProcessor*(const GURL& origin)> GetLocalChangeProcessorCallback; class Observer { public: Observer() {} Observer(const Observer&) = delete; Observer& operator=(const Observer&) = delete; virtual ~Observer() {} // This is called when there're one or more local changes available. // |pending_changes_hint| indicates the pending queue length to help sync // scheduling but the value may not be accurately reflect the real-time // value. virtual void OnLocalChangeAvailable(int64_t pending_changes_hint) = 0; }; typedef base::OnceCallback<void(SyncStatusCode status, bool has_pending_changes)> HasPendingLocalChangeCallback; static std::unique_ptr<LocalFileSyncService> Create(Profile* profile); static std::unique_ptr<LocalFileSyncService> CreateForTesting( Profile* profile, leveldb::Env* env_override); LocalFileSyncService(const LocalFileSyncService&) = delete; LocalFileSyncService& operator=(const LocalFileSyncService&) = delete; ~LocalFileSyncService() override; void Shutdown(); void MaybeInitializeFileSystemContext( const GURL& app_origin, storage::FileSystemContext* file_system_context, SyncStatusCallback callback); void AddChangeObserver(Observer* observer); // Registers |url| to wait until sync is enabled for |url|. // |on_syncable_callback| is to be called when |url| becomes syncable // (i.e. when we have no pending writes and the file is successfully locked // for sync). // Calling this method again while this already has another URL waiting // for sync will overwrite the previously registered URL. void RegisterURLForWaitingSync(const storage::FileSystemURL& url, base::OnceClosure on_syncable_callback); // Synchronize one (or a set of) local change(s) to the remote server // using local_change_processor given by SetLocalChangeProcessor(). // |processor| must have same or longer lifetime than this service. // It is invalid to call this method before calling SetLocalChangeProcessor(). void ProcessLocalChange(SyncFileCallback callback); // Sets a local change processor. The value is ignored if // SetLocalChangeProcessorCallback() is called separately. // Either this or SetLocalChangeProcessorCallback() must be called before // any ProcessLocalChange(). void SetLocalChangeProcessor(LocalChangeProcessor* local_change_processor); // Sets a closure which gets a local change processor for the given origin. // Note that once this is called it overrides the direct processor setting // done by SetLocalChangeProcessor(). // Either this or SetLocalChangeProcessor() must be called before any // ProcessLocalChange(). // // TODO(kinuko): Remove this method once we stop using multiple backends // (crbug.com/324215), or deprecate the other if we keep doing so. void SetLocalChangeProcessorCallback( GetLocalChangeProcessorCallback get_local_change_processor); // Returns true via |callback| if the given file |url| has local pending // changes. void HasPendingLocalChanges(const storage::FileSystemURL& url, HasPendingLocalChangeCallback callback); void PromoteDemotedChanges(base::RepeatingClosure callback); // Returns the metadata of a remote file pointed by |url|. virtual void GetLocalFileMetadata(const storage::FileSystemURL& url, SyncFileMetadataCallback callback); // RemoteChangeProcessor overrides. void PrepareForProcessRemoteChange(const storage::FileSystemURL& url, PrepareChangeCallback callback) override; void ApplyRemoteChange(const FileChange& change, const base::FilePath& local_path, const storage::FileSystemURL& url, SyncStatusCallback callback) override; void FinalizeRemoteSync(const storage::FileSystemURL& url, bool clear_local_changes, base::OnceClosure completion_callback) override; void RecordFakeLocalChange(const storage::FileSystemURL& url, const FileChange& change, SyncStatusCallback callback) override; // LocalOriginChangeObserver override. void OnChangesAvailableInOrigins(const std::set<GURL>& origins) override; // Called when a particular origin (app) is disabled/enabled while // the service is running. This may be called for origins/apps that // are not initialized for the service. void SetOriginEnabled(const GURL& origin, bool enabled); private: typedef std::map<GURL, storage::FileSystemContext*> OriginToContext; friend class OriginChangeMapTest; class OriginChangeMap { public: typedef std::map<GURL, int64_t> Map; OriginChangeMap(); ~OriginChangeMap(); // Sets |origin| to the next origin to process. (For now we simply apply // round-robin to pick the next origin to avoid starvation.) // Returns false if no origins to process. bool NextOriginToProcess(GURL* origin); int64_t GetTotalChangeCount() const; // Update change_count_map_ for |origin|. void SetOriginChangeCount(const GURL& origin, int64_t changes); void SetOriginEnabled(const GURL& origin, bool enabled); private: // Per-origin changes (cached info, could be stale). Map change_count_map_; Map::iterator next_; // Holds a set of disabled (but initialized) origins. std::set<GURL> disabled_origins_; }; LocalFileSyncService(Profile* profile, leveldb::Env* env_override); void DidInitializeFileSystemContext( const GURL& app_origin, storage::FileSystemContext* file_system_context, SyncStatusCallback callback, SyncStatusCode status); void DidInitializeForRemoteSync( const storage::FileSystemURL& url, storage::FileSystemContext* file_system_context, PrepareChangeCallback callback, SyncStatusCode status); // Callback for ApplyRemoteChange. void DidApplyRemoteChange(SyncStatusCallback callback, SyncStatusCode status); // Callbacks for ProcessLocalChange. void DidGetFileForLocalSync(SyncFileCallback callback, SyncStatusCode status, const LocalFileSyncInfo& sync_file_info, storage::ScopedFile snapshot); void ProcessNextChangeForURL(SyncFileCallback callback, storage::ScopedFile snapshot, const LocalFileSyncInfo& sync_file_info, const FileChange& last_change, const FileChangeList& changes, SyncStatusCode status); // A thin wrapper of get_local_change_processor_. LocalChangeProcessor* GetLocalChangeProcessor( const storage::FileSystemURL& url); Profile* profile_; scoped_refptr<LocalFileSyncContext> sync_context_; // Origin to context map. (Assuming that as far as we're in the same // profile single origin wouldn't belong to multiple FileSystemContexts.) OriginToContext origin_to_contexts_; // Origins which have pending changes but have not been initialized yet. // (Used only for handling dirty files left in the local tracker database // after a restart.) std::set<GURL> pending_origins_with_changes_; OriginChangeMap origin_change_map_; LocalChangeProcessor* local_change_processor_; GetLocalChangeProcessorCallback get_local_change_processor_; base::ObserverList<Observer>::Unchecked change_observers_; }; } // namespace sync_file_system #endif // CHROME_BROWSER_SYNC_FILE_SYSTEM_LOCAL_LOCAL_FILE_SYNC_SERVICE_H_
/* USER CODE BEGIN Header */ /** ****************************************************************************** * @file stm32f0xx_it.h * @brief This file contains the headers of the interrupt handlers. ****************************************************************************** * @attention * * <h2><center>&copy; Copyright (c) 2020 STMicroelectronics. * All rights reserved.</center></h2> * * This software component is licensed by ST under BSD 3-Clause license, * the "License"; You may not use this file except in compliance with the * License. You may obtain a copy of the License at: * opensource.org/licenses/BSD-3-Clause * ****************************************************************************** */ /* USER CODE END Header */ /* Define to prevent recursive inclusion -------------------------------------*/ #ifndef __STM32F0xx_IT_H #define __STM32F0xx_IT_H #ifdef __cplusplus extern "C" { #endif /* Exported functions prototypes ---------------------------------------------*/ void NMI_Handler(void); void HardFault_Handler(void); void SVC_Handler(void); void PendSV_Handler(void); void SysTick_Handler(void); void EXTI4_15_IRQHandler(void); #ifdef __cplusplus } #endif #endif /* __STM32F0xx_IT_H */ /************************ (C) COPYRIGHT STMicroelectronics *****END OF FILE****/
/* * This file is part of the EasyLogger Library. * * Copyright (c) 2015-2019, Qintl, <qintl_linux@163.com> * * Permission is hereby granted, free of charge, to any person obtaining * a copy of this software and associated documentation files (the * 'Software'), to deal in the Software without restriction, including * without limitation the rights to use, copy, modify, merge, publish, * distribute, sublicense, and/or sell copies of the Software, and to * permit persons to whom the Software is furnished to do so, subject to * the following conditions: * * The above copyright notice and this permission notice shall be * included in all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED 'AS IS', WITHOUT WARRANTY OF ANY KIND, * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. * IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY * CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, * TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE * SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. * * Function: Portable interface for EasyLogger's file log pulgin. * Created on: 2019-01-05 */ #include <stdio.h> #include <sys/types.h> #include <sys/stat.h> #include <fcntl.h> #include <sys/ipc.h> #include <sys/sem.h> #include <unistd.h> #include <elog_file.h> #include <elog_file_cfg.h> #define ELOG_FILE_SEM_KEY ((key_t)0x19910612) #ifdef _SEM_SEMUN_UNDEFINED union semun { int val; /* Value for SETVAL */ struct semid_ds *buf; /* Buffer for IPC_STAT, IPC_SET */ unsigned short *array; /* Array for GETALL, SETALL */ struct seminfo *__buf; /* Buffer for IPC_INFO (Linux-specific) */ }; #endif static int semid = -1; static struct sembuf const up = {0, 1, SEM_UNDO}; static struct sembuf const down = {0, -1, SEM_UNDO}; static void lock_init(void); static int lock_open(void); static void lock_deinit(void); /** * EasyLogger flile log pulgin port initialize * * @return result */ ElogErrCode elog_file_port_init(void) { ElogErrCode result = ELOG_NO_ERR; lock_init(); return result; } /** * file log lock */ void inline elog_file_port_lock(void) { semid == -1 ? -1 : semop(semid, (struct sembuf *)&down, 1); } /** * file log unlock */ void inline elog_file_port_unlock(void) { semid == -1 ? -1 : semop(semid, (struct sembuf *)&up, 1); } /** * file log deinit */ void elog_file_port_deinit(void) { lock_deinit(); } /** * initialize the lock */ static void lock_init(void) { int id, rc; union semun arg; struct sembuf sembuf; id = semget(ELOG_FILE_SEM_KEY, 1, IPC_CREAT | IPC_EXCL | 0666); if(likely(id == -1)) { id = lock_open(); if (id == -1) goto __exit; } else { arg.val = 0; rc = semctl(id, 0, SETVAL, arg); if (rc == -1) goto __exit; sembuf.sem_num = 0; sembuf.sem_op = 1; sembuf.sem_flg = 0; rc = semop(id, &sembuf, 1); if (rc == -1) goto __exit; } semid = id; __exit: return ; } /** * gets the lock */ static int lock_open(void) { int id, rc, i; union semun arg; struct semid_ds ds; id = semget(ELOG_FILE_SEM_KEY, 1, 0666); if(unlikely(id == -1)) goto err; arg.buf = &ds; for (i = 0; i < 10; i++) { rc = semctl(id, 0, IPC_STAT, arg); if (unlikely(rc == -1)) goto err; if(ds.sem_otime != 0) break; usleep(10 * 1000); } if (unlikely(ds.sem_otime == 0)) goto err; return id; err: return -1; } /** * deinitialize the lock */ static void lock_deinit(void) { semid = -1; }
// // UIPageControlProcessor.h // nib2objc // // Created by Adrian on 3/14/09. // Adrian Kosmaczewski 2009 // #import "UIControlProcessor.h" @interface UIPageControlProcessor : UIControlProcessor @end
// AUTHOR: Sean M. Marks (https://github.com/seanmarks) #include <cmath> #include <cstdlib> #include <exception> #include <fstream> #include <functional> #include <iostream> #include <memory> #include <random> #include <sstream> #include <stdexcept> #include <string> #include <vector> #include "Assert.hpp" #pragma once #ifndef STATISTICS_H #define STATISTICS_H // Object with basic statistics functions // // TODO: // - Rename variables to be consistent with prevailing style // - Standard error for different measurements class Statistics { public: Statistics(const int seed); ~Statistics(); static double average(const std::vector<double>& x); // Computes the variance of a set of data // - Default: delta_dof = 1 (sample variance) --> unbiased estimator static double variance(const std::vector<double>& x, const int delta_dof = 1); static double varianceOverAverage(const std::vector<double>& x); static double std_dev(const std::vector<double>& x, const int delta_dof = 1); static double kurtosis(const std::vector<double>& x); static double covariance(const std::vector<double>& x, const std::vector<double>& y); // TODO template<typename InputIt> static double average(InputIt begin, InputIt end); template<typename InputIt> static double variance(InputIt begin, InputIt end, const int ddof=1); template<typename InputIt> static double std_err_mean(InputIt begin, InputIt end, const int ddof=1); // Constructs a histogram of the data (TODO) // - Note: data bins must be evenly spaced void constructHistogram( const std::vector<double>& x, // Data const std::vector<double>& bins, // Bin centers const bool isNormalized, // Option to normalize the histogram // Output std::vector<double>& histogram, int& numOutliers // # data pts. which didn't fit in the bins ); // Standard error of the mean (assuming i.i.d. samples) static double std_err_mean(const std::vector<double>& x); // Uses block averaging to compute the standard error and its standard deviation void blockStatistics( const std::vector<double>& x, const int numSamplesPerBlock, // Output int& numBlocks, std::vector<double>& blockAverages, std::vector<double>& blockVariances, double& stdError_avg, // Standard error of the average double& std_dev_stdError_avg // Std. deviation of the above ); // Use moving block bootstrap to estimate the std. error of a point statistic and its std. dev. // - The point statistic should be expressable as an expected value void movingBlockBootstrap_stdError_PointStatistic( const std::string& statistic, // Point statistic of 'x' to evaluate const std::vector<double>& x, // Data const int numSamplesPerBlock, const int numBootstrapSamples, // Output double& bootstrapAverage, // Average across boostrap samples double& stdError, // Std. error of the avg. statistic double& std_dev_stdError // Std. dev. of the std. error ); // Use moving block bootstrap to estimate the std. error of the probability distribution p(x) TODO void movingBlockBootstrap_stdError_p_x( const std::vector<double>& x, // Data const std::vector<double>& bins, // Histogram bins const int numSamplesPerBlock, const int numBootstrapSamples, const bool doNegativeLog, // Do -log(p(x)) instead // Output std::vector<double>& bootstrapAverages, // Averages across boostrap samples std::vector<double>& std_devs // Std. errors of <p(x)> ); // Perform bootstrap on subsamples whose elements are separated by the correlation time // - Subsamples chosen this way contain independent data // - Each bootstrap sample should only be as large as the independent subsample // - Make sure you have enough data that a subsample can be used to produce a reliable // estimate of the target statistic! void timeCorrelationBootstrap( const std::string& statistic, // Statistic of 'x' to evaluate const std::vector<double> x, // Data const int correlationTime, // Correlation time for x [samples] const int bootstrapSampleSize, const int numBootstrapSamples, // Output double& bootstrapAverage, // Average of sample estimates double& bootstrapStdError // Standard error of the bootstrap estimates ); /* // Use moving block bootstrap to estimate the std. errors of a probability distribution TODO // - Note: Bins must be evenly spaced void blockBootstrap_stdError_p_x( const std::vector<double>& x, // Data const std::vector<double>& bins, // Bins for p(x) histogram const int numSamplesPerBlock, const int numBootstrapSamples, // Output std::vector<double>& stdErrors, std::vector<double>& std_dev_stdErrors ); */ // Moving block bootstrap for std. error of the mean with auto-block size selection TODO void blockBootstrap_stdError_avg_auto( const std::vector<double>& x, const int blockSizeGuess, const int numSubsamples, const int numBootstrapSamples, // Output double& stdError_avg, double& std_dev_stdError_avg ); private: //---- Typedefs -----// // Member function pointer for flexibility in bootstrapping algorithms // - A single bootstrap routine can work for many different point statistics // - TODO switch to std::function //using MethodPointer_PointEstimator = double (*)(const std::vector<double>&); using PointEstmator = std::function<double(const std::vector<double>&)>; // Random number generator using MersenneTwisterPtr = std::unique_ptr<std::mt19937>; MersenneTwisterPtr rng_ptr_; // Calculates the correction factor c_N for the std. dev. of normal random variables // - Multiplying the sample standard deviation by this factor makes it an unbiased // estimator for normal random variables double calc_correction_c_N(const int numSamples); // Generates a bootstrap sample from the data // - Method assumes independent samples void getBootstrapSample( const std::vector<double>& x, std::vector<double>& x_bootstrap ); // Generates a bootstrap sample of independent data from time-correlated data // - A "subsample of independent data" is defined here as a sequence of points // which are separated by the correlation time. // - The parameter 0 <= subsampleOrigin < correlationTime is the index of the // first point in the subsample which will be used to produce the bootstrap // sample void getBootstrapSampleFromTimeCorrelatedData( const std::vector<double> data, const int subsampleOrigin, const int correlationTime, const int bootstrapSampleSize, // Output std::vector<double>& bootstrapSample ); // Generates a moving block bootstrap sample from the data void getMovingBlockBootstrapSample( const std::vector<double>& x, const int numSamplesPerBlock, // block size // Output std::vector<double>& x_bootstrap ); // Estimates the optimal block size for computing the std. error of the mean TODO int estimateOptimalBlockSize_stdError_avg( const std::vector<double>& x, const int blockSizeGuess, // Initial guess for block size const int numSubsamples // Num. of subsamples for MSE estimate ); // Returns a ptr to the member function which estimates the indicated point statistic PointEstmator getPointEstimatorMethod(const std::string& statistic); }; template<typename InputIt> double Statistics::average(InputIt begin, InputIt end) { static_assert( std::is_convertible<typename std::iterator_traits<InputIt>::value_type, double>::value, "unable to convert input type to double" ); int num_samples = std::distance(begin, end); FANCY_ASSERT( num_samples > 0, "insufficient number of samples: " << num_samples ); double avg = std::accumulate(begin, end, 0.0)/static_cast<double>(num_samples); return avg; } template<typename InputIt> double Statistics::variance(InputIt begin, InputIt end, const int ddof) { using value_type = typename std::iterator_traits<InputIt>::value_type; static_assert( std::is_convertible<value_type, double>::value, "unable to convert input type to double" ); int num_samples = std::distance(begin, end); FANCY_ASSERT( num_samples - ddof > 0, "insufficient number of samples: " << num_samples << " with ddof=" << ddof ); double avg = average(begin, end); // Compute sum_i^N (x_i - avg)^2 value_type init = 0.0; // ensure the correct type is used double var = std::accumulate( begin, end, init, [&](value_type sum, value_type x) { return std::move(sum) + (x - avg)*(x - avg); } ); var /= static_cast<double>(num_samples - ddof); return var; } template<typename InputIt> double Statistics::std_err_mean(InputIt begin, InputIt end, const int ddof) { using value_type = typename std::iterator_traits<InputIt>::value_type; static_assert( std::is_convertible<value_type, double>::value, "unable to convert input type to double" ); int num_samples = std::distance(begin, end); FANCY_ASSERT( num_samples > 0, "insufficient number of samples: " << num_samples ); double var = variance(begin, end); return std::sqrt(var/static_cast<double>(num_samples)); } #endif // STATISTICS_H
/*************************************************************************************************/ /*! * \file * * \brief Wireless Data Exchange profile implementation - Stream Example. * * Copyright (c) 2013-2018 Arm Ltd. All Rights Reserved. * ARM Ltd. confidential and proprietary. * * IMPORTANT. Your use of this file is governed by a Software License Agreement * ("Agreement") that must be accepted in order to download or otherwise receive a * copy of this file. You may not use or copy this file for any purpose other than * as described in the Agreement. If you do not agree to all of the terms of the * Agreement do not use this file and delete all copies in your possession or control; * if you do not have a copy of the Agreement, you must contact ARM Ltd. prior * to any use, copying or further distribution of this software. */ /*************************************************************************************************/ #include <string.h> #include "wsf_types.h" #include "util/wstr.h" #include "wsf_trace.h" #include "wsf_assert.h" #include "wsf_efs.h" #include "util/bstream.h" #include "svc_wdxs.h" #include "wdxs/wdxs_api.h" #include "wdxs/wdxs_main.h" #include "wdxs/wdxs_stream.h" #include "dm_api.h" #include "att_api.h" #include "app_api.h" /*! Type of waveform to output from the Example Stream */ static uint8_t wdxsStreamWaveform = WDXS_STREAM_WAVEFORM_SINE; /*************************************************************************************************/ /* * Note: This file contains an example of creating Wireless Data Exchange * (WDXS) Streams. WDXS Streams are implemented as virtual Physical Media in * the Embedded File System (EFS). A Stream can be created in three steps: * * Step 1: Create a FileMedia_t (EFS Media Control structure) for the stream * containing the read function created in step 2. * * Step 2: Implement a read function for the stream. The WDXS and EFS will * call the read function to get data from the stream. * * Step 3: Register the media with the EFS, and add a file to the embedded * file system that uses the media created in step 2. */ /*************************************************************************************************/ /*************************************************************************************************/ /* Step 1: Media Control Block */ /*************************************************************************************************/ /* Prototype of stream read function */ static uint8_t wdxsStreamRead(uint8_t *pBuf, uint32_t address, uint32_t len); /* Example media control structure for a stream */ static const wsfEfsMedia_t WDXS_StreamMedia = { 0, 0, 0, NULL, NULL, wdxsStreamRead, NULL, NULL }; /*************************************************************************************************/ /* Step 2: Read Function */ /*************************************************************************************************/ /*************************************************************************************************/ /*! * \brief Example of a media read function that generates a Sine Wave. * * \param pBuf buffer to hold stream data. * \param address unused in streams. * \param len size of pBuf in bytes. * * \return None. */ /*************************************************************************************************/ static uint8_t wdxsSineRead(uint8_t *pBuf, uint32_t address, uint32_t len) { static int8_t incr = 1; static uint8_t dataVal = 0; /* Build data in sine waveform */ memset(pBuf, dataVal, len); if (dataVal <= 127) { incr++; } else { incr--; } dataVal += (incr / 2); return TRUE; } /*************************************************************************************************/ /*! * \brief Example of a media read function that generates a Step Wave. * * \param pBuf buffer to hold stream data. * \param address unused in streams. * \param len size of pBuf in bytes. * * \return None. */ /*************************************************************************************************/ static uint8_t wdxsStepRead(uint8_t *pBuf, uint32_t address, uint32_t len) { static int8_t count = 0; static int8_t incr = 25; static uint8_t dataVal = 0; /* Build data in step waveform */ memset(pBuf, dataVal, len); if (count++ == 5) { count = 0; dataVal += incr; if (dataVal == 0) incr = 25; if (dataVal == 250) incr = -25; } return TRUE; } /*************************************************************************************************/ /*! * \brief Example of a media read function that generates a Sawtooth Wave. * * \param pBuf buffer to hold stream data. * \param address unused in streams. * \param len size of pBuf in bytes. * * \return None. */ /*************************************************************************************************/ static uint8_t wdxsSawtoothRead(uint8_t *pBuf, uint32_t address, uint32_t len) { static int8_t incr = 1; static uint8_t dataVal = 0; uint32_t i; /* Build data in sawtooth waveform */ for (i=0; i<len; i++) { *pBuf++ = dataVal; dataVal += incr; if (dataVal == 0) incr = 1; else if (dataVal == 255) incr = -1; } return TRUE; } /*************************************************************************************************/ /*! * \brief Example of a media read function. * * \param pBuf buffer to hold stream data. * \param address unused in streams. * \param len size of pBuf in bytes. * * \return None. */ /*************************************************************************************************/ static uint8_t wdxsStreamRead(uint8_t *pBuf, uint32_t address, uint32_t len) { switch(wdxsStreamWaveform) { case WDXS_STREAM_WAVEFORM_SINE: wdxsSineRead(pBuf, address, len); break; case WDXS_STREAM_WAVEFORM_STEP: wdxsStepRead(pBuf, address, len); break; case WDXS_STREAM_WAVEFORM_SAWTOOTH: wdxsSawtoothRead(pBuf, address, len); break; } return TRUE; } /*************************************************************************************************/ /* Step 3: Register the stream media and adding the stream file. */ /*************************************************************************************************/ /*************************************************************************************************/ /*! * \brief Example of creating a WDXS stream. * * \param none * * \return None. */ /*************************************************************************************************/ void wdxsStreamInit(void) { wsfEsfAttributes_t attr; /* Register the media for the stream */ WsfEfsRegisterMedia(&WDXS_StreamMedia, WDX_STREAM_MEDIA); /* Set the attributes for the stream */ attr.permissions = WSF_EFS_REMOTE_VISIBLE | WSF_EFS_REMOTE_GET_PERMITTED; attr.type = WSF_EFS_FILE_TYPE_STREAM; /* Potential buffer overrun is intentional to zero out fixed length field */ /* coverity[overrun-buffer-arg] */ WstrnCpy(attr.name, "Stream", WSF_EFS_NAME_LEN); /* coverity[overrun-buffer-arg] */ WstrnCpy(attr.version, "1.0", WSF_EFS_VERSION_LEN); /* Add a file for the stream */ WsfEfsAddFile(0, WDX_STREAM_MEDIA, &attr, 0); } /*************************************************************************************************/ /*! * \brief Changes the type of waveform transmitted by the stream. * * \param type - Identifier of the waveform * * \return None. */ /*************************************************************************************************/ void wdxsSetStreamWaveform(uint8_t type) { if (type <= WDXS_STREAM_WAVEFORM_SAWTOOTH) { wdxsStreamWaveform = type; } }
/* * FreeRTOS V202112.00 * Copyright (C) 2020 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Permission is hereby granted, free of charge, to any person obtaining a copy of * this software and associated documentation files (the "Software"), to deal in * the Software without restriction, including without limitation the rights to * use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of * the Software, and to permit persons to whom the Software is furnished to do so, * subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all * copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS * FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR * COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER * IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. * * https://www.FreeRTOS.org * https://github.com/FreeRTOS * */ /* ******************************************************************************* * NOTE 1: The POSIX port is a simulation (or is that emulation?) only! Do not * expect to get real time behaviour from the POSIX port or this demo * application. It is provided as a convenient development and demonstration * test bed only. * * Linux will not be running the FreeRTOS simulator threads continuously, so * the timing information in the FreeRTOS+Trace logs have no meaningful units. * See the documentation page for the Linux simulator for an explanation of * the slow timing: * https://www.freertos.org/FreeRTOS-simulator-for-Linux.html * - READ THE WEB DOCUMENTATION FOR THIS PORT FOR MORE INFORMATION ON USING IT - * * NOTE 2: This project provides two demo applications. A simple blinky style * project, and a more comprehensive test and demo application. The * mainCREATE_SIMPLE_BLINKY_DEMO_ONLY setting in main.c is used to select * between the two. See the notes on using mainCREATE_SIMPLE_BLINKY_DEMO_ONLY * in main.c. This file implements the comprehensive test and demo version. * * NOTE 3: This file only contains the source code that is specific to the * full demo. Generic functions, such FreeRTOS hook functions, are defined in * main.c. ******************************************************************************* * * main() creates all the demo application tasks, then starts the scheduler. * The web documentation provides more details of the standard demo application * tasks, which provide no particular functionality but do provide a good * example of how to use the FreeRTOS API. * * In addition to the standard demo tasks, the following tasks and tests are * defined and/or created within this file: * * "Check" task - This only executes every five seconds but has a high priority * to ensure it gets processor time. Its main function is to check that all the * standard demo tasks are still operational. While no errors have been * discovered the check task will print out "OK" and the current simulated tick * time. If an error is discovered in the execution of a task then the check * task will print out an appropriate error message. * */ /* Standard includes. */ #include <stdlib.h> #include <string.h> #include <time.h> #include <stdio.h> /* Kernel includes. */ #include <FreeRTOS.h> #include <task.h> #include <queue.h> #include <timers.h> #include <semphr.h> /* Standard demo includes. */ #include "BlockQ.h" #include "integer.h" #include "semtest.h" #include "PollQ.h" #include "GenQTest.h" #include "QPeek.h" #include "recmutex.h" #include "flop.h" #include "TimerDemo.h" #include "countsem.h" #include "death.h" #include "dynamic.h" #include "QueueSet.h" #include "QueueOverwrite.h" #include "EventGroupsDemo.h" #include "IntSemTest.h" #include "TaskNotify.h" #include "QueueSetPolling.h" #include "StaticAllocation.h" #include "blocktim.h" #include "AbortDelay.h" #include "MessageBufferDemo.h" #include "StreamBufferDemo.h" #include "StreamBufferInterrupt.h" #include "MessageBufferAMP.h" #include "console.h" /* Priorities at which the tasks are created. */ #define mainCHECK_TASK_PRIORITY ( configMAX_PRIORITIES - 2 ) #define mainQUEUE_POLL_PRIORITY ( tskIDLE_PRIORITY + 1 ) #define mainSEM_TEST_PRIORITY ( tskIDLE_PRIORITY + 1 ) #define mainBLOCK_Q_PRIORITY ( tskIDLE_PRIORITY + 2 ) #define mainCREATOR_TASK_PRIORITY ( tskIDLE_PRIORITY + 3 ) #define mainFLASH_TASK_PRIORITY ( tskIDLE_PRIORITY + 1 ) #define mainINTEGER_TASK_PRIORITY ( tskIDLE_PRIORITY ) #define mainGEN_QUEUE_TASK_PRIORITY ( tskIDLE_PRIORITY ) #define mainFLOP_TASK_PRIORITY ( tskIDLE_PRIORITY ) #define mainQUEUE_OVERWRITE_PRIORITY ( tskIDLE_PRIORITY ) #define mainTIMER_TEST_PERIOD ( 50 ) /* * Exercises code that is not otherwise covered by the standard demo/test * tasks. */ extern BaseType_t xRunCodeCoverageTestAdditions( void ); /* Task function prototypes. */ static void prvCheckTask( void * pvParameters ); /* A task that is created from the idle task to test the functionality of * eTaskStateGet(). */ static void prvTestTask( void * pvParameters ); /* * Called from the idle task hook function to demonstrate a few utility * functions that are not demonstrated by any of the standard demo tasks. */ static void prvDemonstrateTaskStateAndHandleGetFunctions( void ); /* * Called from the idle task hook function to demonstrate the use of * xTimerPendFunctionCall() as xTimerPendFunctionCall() is not demonstrated by * any of the standard demo tasks. */ static void prvDemonstratePendingFunctionCall( void ); /* * The function that is pended by prvDemonstratePendingFunctionCall(). */ static void prvPendedFunction( void * pvParameter1, uint32_t ulParameter2 ); /* * prvDemonstrateTimerQueryFunctions() is called from the idle task hook * function to demonstrate the use of functions that query information about a * software timer. prvTestTimerCallback() is the callback function for the * timer being queried. */ static void prvDemonstrateTimerQueryFunctions( void ); static void prvTestTimerCallback( TimerHandle_t xTimer ); /* * A task to demonstrate the use of the xQueueSpacesAvailable() function. */ static void prvDemoQueueSpaceFunctions( void * pvParameters ); /* * Tasks that ensure indefinite delays are truly indefinite. */ static void prvPermanentlyBlockingSemaphoreTask( void * pvParameters ); static void prvPermanentlyBlockingNotificationTask( void * pvParameters ); /* * The test function and callback function used when exercising the timer AP * function that changes the timer's auto-reload mode. */ static void prvDemonstrateChangingTimerReloadMode( void * pvParameters ); static void prvReloadModeTestTimerCallback( TimerHandle_t xTimer ); /*-----------------------------------------------------------*/ /* The variable into which error messages are latched. */ static char * pcStatusMessage = "OK: No errors"; static int xErrorCount = 0; /* This semaphore is created purely to test using the vSemaphoreDelete() and * semaphore tracing API functions. It has no other purpose. */ static SemaphoreHandle_t xMutexToDelete = NULL; /*-----------------------------------------------------------*/ int main_full( void ) { /* Start the check task as described at the top of this file. */ xTaskCreate( prvCheckTask, "Check", configMINIMAL_STACK_SIZE, NULL, mainCHECK_TASK_PRIORITY, NULL ); /* Create the standard demo tasks. */ vStartTaskNotifyTask(); /* vStartTaskNotifyArrayTask(); */ vStartBlockingQueueTasks( mainBLOCK_Q_PRIORITY ); vStartSemaphoreTasks( mainSEM_TEST_PRIORITY ); vStartPolledQueueTasks( mainQUEUE_POLL_PRIORITY ); vStartIntegerMathTasks( mainINTEGER_TASK_PRIORITY ); vStartGenericQueueTasks( mainGEN_QUEUE_TASK_PRIORITY ); vStartQueuePeekTasks(); vStartMathTasks( mainFLOP_TASK_PRIORITY ); vStartRecursiveMutexTasks(); vStartCountingSemaphoreTasks(); vStartDynamicPriorityTasks(); vStartQueueOverwriteTask( mainQUEUE_OVERWRITE_PRIORITY ); vStartEventGroupTasks(); vStartInterruptSemaphoreTasks(); vCreateBlockTimeTasks(); vCreateAbortDelayTasks(); xTaskCreate( prvDemoQueueSpaceFunctions, "QSpace", configMINIMAL_STACK_SIZE, NULL, tskIDLE_PRIORITY, NULL ); xTaskCreate( prvPermanentlyBlockingSemaphoreTask, "BlockSem", configMINIMAL_STACK_SIZE, NULL, tskIDLE_PRIORITY, NULL ); xTaskCreate( prvPermanentlyBlockingNotificationTask, "BlockNoti", configMINIMAL_STACK_SIZE, NULL, tskIDLE_PRIORITY, NULL ); xTaskCreate( prvDemonstrateChangingTimerReloadMode, "TimerMode", configMINIMAL_STACK_SIZE, NULL, configMAX_PRIORITIES - 1, NULL ); vStartMessageBufferTasks( configMINIMAL_STACK_SIZE ); vStartStreamBufferTasks(); vStartStreamBufferInterruptDemo(); vStartMessageBufferAMPTasks( configMINIMAL_STACK_SIZE ); #if ( configUSE_QUEUE_SETS == 1 ) { vStartQueueSetTasks(); vStartQueueSetPollingTask(); } #endif #if ( configSUPPORT_STATIC_ALLOCATION == 1 ) { vStartStaticallyAllocatedTasks(); } #endif #if ( configUSE_PREEMPTION != 0 ) { /* Don't expect these tasks to pass when preemption is not used. */ vStartTimerDemoTask( mainTIMER_TEST_PERIOD ); } #endif /* The suicide tasks must be created last as they need to know how many * tasks were running prior to their creation. This then allows them to * ascertain whether or not the correct/expected number of tasks are running at * any given time. */ vCreateSuicidalTasks( mainCREATOR_TASK_PRIORITY ); /* Create the semaphore that will be deleted in the idle task hook. This * is done purely to test the use of vSemaphoreDelete(). */ xMutexToDelete = xSemaphoreCreateMutex(); /* Start the scheduler itself. */ vTaskStartScheduler(); /* Should never get here unless there was not enough heap space to create * the idle and other system tasks. */ return 0; } /*-----------------------------------------------------------*/ static void prvCheckTask( void * pvParameters ) { TickType_t xNextWakeTime; const TickType_t xCycleFrequency = pdMS_TO_TICKS( 10000UL ); /* Just to remove compiler warning. */ ( void ) pvParameters; /* Initialise xNextWakeTime - this only needs to be done once. */ xNextWakeTime = xTaskGetTickCount(); for( ; ; ) { /* Place this task in the blocked state until it is time to run again. */ vTaskDelayUntil( &xNextWakeTime, xCycleFrequency ); /* Check the standard demo tasks are running without error. */ #if ( configUSE_PREEMPTION != 0 ) { /* These tasks are only created when preemption is used. */ if( xAreTimerDemoTasksStillRunning( xCycleFrequency ) != pdTRUE ) { pcStatusMessage = "Error: TimerDemo"; xErrorCount++; } } #endif if( xAreStreamBufferTasksStillRunning() != pdTRUE ) { pcStatusMessage = "Error: StreamBuffer"; xErrorCount++; } else if( xAreMessageBufferTasksStillRunning() != pdTRUE ) { pcStatusMessage = "Error: MessageBuffer"; xErrorCount++; } else if( xAreTaskNotificationTasksStillRunning() != pdTRUE ) { pcStatusMessage = "Error: Notification"; xErrorCount++; } /* * else if( xAreTaskNotificationArrayTasksStillRunning() != pdTRUE ) * { * pcStatusMessage = "Error: NotificationArray"; * } */ else if( xAreInterruptSemaphoreTasksStillRunning() != pdTRUE ) { pcStatusMessage = "Error: IntSem"; xErrorCount++; } else if( xAreEventGroupTasksStillRunning() != pdTRUE ) { pcStatusMessage = "Error: EventGroup"; xErrorCount++; } else if( xAreIntegerMathsTaskStillRunning() != pdTRUE ) { pcStatusMessage = "Error: IntMath"; xErrorCount++; } else if( xAreGenericQueueTasksStillRunning() != pdTRUE ) { pcStatusMessage = "Error: GenQueue"; xErrorCount++; } else if( xAreQueuePeekTasksStillRunning() != pdTRUE ) { pcStatusMessage = "Error: QueuePeek"; xErrorCount++; } else if( xAreBlockingQueuesStillRunning() != pdTRUE ) { pcStatusMessage = "Error: BlockQueue"; xErrorCount++; } else if( xAreSemaphoreTasksStillRunning() != pdTRUE ) { pcStatusMessage = "Error: SemTest"; xErrorCount++; } else if( xArePollingQueuesStillRunning() != pdTRUE ) { pcStatusMessage = "Error: PollQueue"; xErrorCount++; } else if( xAreMathsTaskStillRunning() != pdPASS ) { pcStatusMessage = "Error: Flop"; xErrorCount++; } else if( xAreRecursiveMutexTasksStillRunning() != pdTRUE ) { pcStatusMessage = "Error: RecMutex"; xErrorCount++; } else if( xAreCountingSemaphoreTasksStillRunning() != pdTRUE ) { pcStatusMessage = "Error: CountSem"; xErrorCount++; } else if( xIsCreateTaskStillRunning() != pdTRUE ) { pcStatusMessage = "Error: Death"; xErrorCount++; } else if( xAreDynamicPriorityTasksStillRunning() != pdPASS ) { pcStatusMessage = "Error: Dynamic"; xErrorCount++; } else if( xIsQueueOverwriteTaskStillRunning() != pdPASS ) { pcStatusMessage = "Error: Queue overwrite"; xErrorCount++; } else if( xAreBlockTimeTestTasksStillRunning() != pdPASS ) { pcStatusMessage = "Error: Block time"; xErrorCount++; } else if( xAreAbortDelayTestTasksStillRunning() != pdPASS ) { pcStatusMessage = "Error: Abort delay"; xErrorCount++; } else if( xIsInterruptStreamBufferDemoStillRunning() != pdPASS ) { pcStatusMessage = "Error: Stream buffer interrupt"; xErrorCount++; } else if( xAreMessageBufferAMPTasksStillRunning() != pdPASS ) { pcStatusMessage = "Error: Message buffer AMP"; xErrorCount++; } #if ( configUSE_QUEUE_SETS == 1 ) else if( xAreQueueSetTasksStillRunning() != pdPASS ) { pcStatusMessage = "Error: Queue set"; xErrorCount++; } else if( xAreQueueSetPollTasksStillRunning() != pdPASS ) { pcStatusMessage = "Error: Queue set polling"; xErrorCount++; } #endif /* if ( configUSE_QUEUE_SETS == 1 ) */ #if ( configSUPPORT_STATIC_ALLOCATION == 1 ) else if( xAreStaticAllocationTasksStillRunning() != pdPASS ) { xErrorCount++; pcStatusMessage = "Error: Static allocation"; } #endif /* configSUPPORT_STATIC_ALLOCATION */ printf( "%s - tick count %lu \r\n", pcStatusMessage, xTaskGetTickCount() ); if( xErrorCount != 0 ) { exit( 1 ); } /* Reset the error condition */ pcStatusMessage = "OK: No errors"; } } /*-----------------------------------------------------------*/ static void prvTestTask( void * pvParameters ) { const unsigned long ulMSToSleep = 5; /* Just to remove compiler warnings. */ ( void ) pvParameters; /* This task is just used to test the eTaskStateGet() function. It * does not have anything to do. */ for( ; ; ) { /* Sleep to reduce CPU load, but don't sleep indefinitely in case there are * tasks waiting to be terminated by the idle task. */ vTaskDelay( pdMS_TO_TICKS( ulMSToSleep ) ); } } /*-----------------------------------------------------------*/ /* Called from vApplicationIdleHook(), which is defined in main.c. */ void vFullDemoIdleFunction( void ) { const unsigned long ulMSToSleep = 15; void * pvAllocated; /* Sleep to reduce CPU load, but don't sleep indefinitely in case there are * tasks waiting to be terminated by the idle task. */ vTaskDelay( pdMS_TO_TICKS( ulMSToSleep ) ); /* Demonstrate a few utility functions that are not demonstrated by any of * the standard demo tasks. */ prvDemonstrateTaskStateAndHandleGetFunctions(); /* Demonstrate the use of xTimerPendFunctionCall(), which is not * demonstrated by any of the standard demo tasks. */ prvDemonstratePendingFunctionCall(); /* Demonstrate the use of functions that query information about a software * timer. */ prvDemonstrateTimerQueryFunctions(); /* If xMutexToDelete has not already been deleted, then delete it now. * This is done purely to demonstrate the use of, and test, the * vSemaphoreDelete() macro. Care must be taken not to delete a semaphore * that has tasks blocked on it. */ if( xMutexToDelete != NULL ) { /* For test purposes, add the mutex to the registry, then remove it * again, before it is deleted - checking its name is as expected before * and after the assertion into the registry and its removal from the * registry. */ configASSERT( pcQueueGetName( xMutexToDelete ) == NULL ); vQueueAddToRegistry( xMutexToDelete, "Test_Mutex" ); configASSERT( strcmp( pcQueueGetName( xMutexToDelete ), "Test_Mutex" ) == 0 ); vQueueUnregisterQueue( xMutexToDelete ); configASSERT( pcQueueGetName( xMutexToDelete ) == NULL ); vSemaphoreDelete( xMutexToDelete ); xMutexToDelete = NULL; } /* Exercise heap_5 a bit. The malloc failed hook will trap failed * allocations so there is no need to test here. */ pvAllocated = pvPortMalloc( ( rand() % 500 ) + 1 ); vPortFree( pvAllocated ); /* Exit after a fixed time so code coverage results are written to the * disk. */ #if ( projCOVERAGE_TEST == 1 ) { const TickType_t xMaxRunTime = pdMS_TO_TICKS( 30000UL ); /* Exercise code not otherwise executed by standard demo/test tasks. */ if( xRunCodeCoverageTestAdditions() != pdPASS ) { pcStatusMessage = "Code coverage additions failed.\r\n"; xErrorCount++; } if( ( xTaskGetTickCount() - configINITIAL_TICK_COUNT ) >= xMaxRunTime ) { vTaskEndScheduler(); } } #endif /* if ( projCOVERAGE_TEST == 1 ) */ } /*-----------------------------------------------------------*/ /* Called by vApplicationTickHook(), which is defined in main.c. */ void vFullDemoTickHookFunction( void ) { TaskHandle_t xTimerTask; /* Call the periodic timer test, which tests the timer API functions that * can be called from an ISR. */ #if ( configUSE_PREEMPTION != 0 ) { /* Only created when preemption is used. */ vTimerPeriodicISRTests(); } #endif /* Call the periodic queue overwrite from ISR demo. */ vQueueOverwritePeriodicISRDemo(); #if ( configUSE_QUEUE_SETS == 1 ) /* Remove the tests if queue sets are not defined. */ { /* Write to a queue that is in use as part of the queue set demo to * demonstrate using queue sets from an ISR. */ vQueueSetAccessQueueSetFromISR(); vQueueSetPollingInterruptAccess(); } #endif /* Exercise event groups from interrupts. */ vPeriodicEventGroupsProcessing(); /* Exercise giving mutexes from an interrupt. */ vInterruptSemaphorePeriodicTest(); /* Exercise using task notifications from an interrupt. */ xNotifyTaskFromISR(); /* xNotifyArrayTaskFromISR(); */ /* Writes to stream buffer byte by byte to test the stream buffer trigger * level functionality. */ vPeriodicStreamBufferProcessing(); /* Writes a string to a string buffer four bytes at a time to demonstrate * a stream being sent from an interrupt to a task. */ vBasicStreamBufferSendFromISR(); /* For code coverage purposes. */ xTimerTask = xTimerGetTimerDaemonTaskHandle(); configASSERT( uxTaskPriorityGetFromISR( xTimerTask ) == configTIMER_TASK_PRIORITY ); } /*-----------------------------------------------------------*/ static void prvPendedFunction( void * pvParameter1, uint32_t ulParameter2 ) { static uintptr_t ulLastParameter1 = 1000UL, ulLastParameter2 = 0UL; uintptr_t ulParameter1; ulParameter1 = ( uintptr_t ) pvParameter1; /* Ensure the parameters are as expected. */ configASSERT( ulParameter1 == ( ulLastParameter1 + 1 ) ); configASSERT( ulParameter2 == ( ulLastParameter2 + 1 ) ); /* Remember the parameters for the next time the function is called. */ ulLastParameter1 = ulParameter1; ulLastParameter2 = ulParameter2; /* Remove compiler warnings in case configASSERT() is not defined. */ ( void ) ulLastParameter1; ( void ) ulLastParameter2; } /*-----------------------------------------------------------*/ static void prvTestTimerCallback( TimerHandle_t xTimer ) { /* This is the callback function for the timer accessed by * prvDemonstrateTimerQueryFunctions(). The callback does not do anything. */ ( void ) xTimer; } /*-----------------------------------------------------------*/ static void prvDemonstrateTimerQueryFunctions( void ) { static TimerHandle_t xTimer = NULL; const char * pcTimerName = "TestTimer"; volatile TickType_t xExpiryTime; const TickType_t xDontBlock = 0; if( xTimer == NULL ) { xTimer = xTimerCreate( pcTimerName, portMAX_DELAY, pdTRUE, NULL, prvTestTimerCallback ); if( xTimer != NULL ) { /* Called from the idle task so a block time must not be * specified. */ xTimerStart( xTimer, xDontBlock ); } } if( xTimer != NULL ) { /* Demonstrate querying a timer's name. */ configASSERT( strcmp( pcTimerGetName( xTimer ), pcTimerName ) == 0 ); /* Demonstrate querying a timer's period. */ configASSERT( xTimerGetPeriod( xTimer ) == portMAX_DELAY ); /* Demonstrate querying a timer's next expiry time, although nothing is * done with the returned value. Note if the expiry time is less than the * maximum tick count then the expiry time has overflowed from the current * time. In this case the expiry time was set to portMAX_DELAY, so it is * expected to be less than the current time until the current time has * itself overflowed. */ xExpiryTime = xTimerGetExpiryTime( xTimer ); ( void ) xExpiryTime; } } /*-----------------------------------------------------------*/ static void prvDemonstratePendingFunctionCall( void ) { static intptr_t ulParameter1 = 1000UL, ulParameter2 = 0UL; const TickType_t xDontBlock = 0; /* This is called from the idle task so must *not* attempt to block. */ /* prvPendedFunction() just expects the parameters to be incremented by one * each time it is called. */ ulParameter1++; ulParameter2++; /* Pend the function call, sending the parameters. */ xTimerPendFunctionCall( prvPendedFunction, ( void * ) ulParameter1, ulParameter2, xDontBlock ); } /*-----------------------------------------------------------*/ static void prvDemonstrateTaskStateAndHandleGetFunctions( void ) { TaskHandle_t xIdleTaskHandle, xTimerTaskHandle; char * pcTaskName; static portBASE_TYPE xPerformedOneShotTests = pdFALSE; TaskHandle_t xTestTask; TaskStatus_t xTaskInfo; extern StackType_t uxTimerTaskStack[]; /* Demonstrate the use of the xTimerGetTimerDaemonTaskHandle() and * xTaskGetIdleTaskHandle() functions. Also try using the function that sets * the task number. */ xIdleTaskHandle = xTaskGetIdleTaskHandle(); xTimerTaskHandle = xTimerGetTimerDaemonTaskHandle(); /* This is the idle hook, so the current task handle should equal the * returned idle task handle. */ if( xTaskGetCurrentTaskHandle() != xIdleTaskHandle ) { pcStatusMessage = "Error: Returned idle task handle was incorrect"; xErrorCount++; } /* Check the same handle is obtained using the idle task's name. First try * with the wrong name, then the right name. */ if( xTaskGetHandle( "Idle" ) == xIdleTaskHandle ) { pcStatusMessage = "Error: Returned handle for name Idle was incorrect"; xErrorCount++; } if( xTaskGetHandle( "IDLE" ) != xIdleTaskHandle ) { pcStatusMessage = "Error: Returned handle for name Idle was incorrect"; xErrorCount++; } /* Check the timer task handle was returned correctly. */ pcTaskName = pcTaskGetName( xTimerTaskHandle ); if( strcmp( pcTaskName, "Tmr Svc" ) != 0 ) { pcStatusMessage = "Error: Returned timer task handle was incorrect"; xErrorCount++; } if( xTaskGetHandle( "Tmr Svc" ) != xTimerTaskHandle ) { pcStatusMessage = "Error: Returned handle for name Tmr Svc was incorrect"; xErrorCount++; } /* This task is running, make sure it's state is returned as running. */ if( eTaskStateGet( xIdleTaskHandle ) != eRunning ) { pcStatusMessage = "Error: Returned idle task state was incorrect"; xErrorCount++; } /* If this task is running, then the timer task must be blocked. */ if( eTaskStateGet( xTimerTaskHandle ) != eBlocked ) { pcStatusMessage = "Error: Returned timer task state was incorrect"; xErrorCount++; } /* Also with the vTaskGetInfo() function. */ vTaskGetInfo( xTimerTaskHandle, /* The task being queried. */ &xTaskInfo, /* The structure into which information on the task will be written. */ pdTRUE, /* Include the task's high watermark in the structure. */ eInvalid ); /* Include the task state in the structure. */ /* Check the information returned by vTaskGetInfo() is as expected. */ if( ( xTaskInfo.eCurrentState != eBlocked ) || ( strcmp( xTaskInfo.pcTaskName, "Tmr Svc" ) != 0 ) || ( xTaskInfo.uxCurrentPriority != configTIMER_TASK_PRIORITY ) || ( xTaskInfo.pxStackBase != uxTimerTaskStack ) || ( xTaskInfo.xHandle != xTimerTaskHandle ) ) { pcStatusMessage = "Error: vTaskGetInfo() returned incorrect information about the timer task"; xErrorCount++; } /* Other tests that should only be performed once follow. The test task * is not created on each iteration because to do so would cause the death * task to report an error (too many tasks running). */ if( xPerformedOneShotTests == pdFALSE ) { /* Don't run this part of the test again. */ xPerformedOneShotTests = pdTRUE; /* Create a test task to use to test other eTaskStateGet() return values. */ if( xTaskCreate( prvTestTask, "Test", configMINIMAL_STACK_SIZE, NULL, tskIDLE_PRIORITY, &xTestTask ) == pdPASS ) { /* If this task is running, the test task must be in the ready state. */ if( eTaskStateGet( xTestTask ) != eReady ) { pcStatusMessage = "Error: Returned test task state was incorrect 1"; xErrorCount++; } /* Now suspend the test task and check its state is reported correctly. */ vTaskSuspend( xTestTask ); if( eTaskStateGet( xTestTask ) != eSuspended ) { pcStatusMessage = "Error: Returned test task state was incorrect 2"; xErrorCount++; } /* Now delete the task and check its state is reported correctly. */ vTaskDelete( xTestTask ); if( eTaskStateGet( xTestTask ) != eDeleted ) { pcStatusMessage = "Error: Returned test task state was incorrect 3"; xErrorCount++; } } } } /*-----------------------------------------------------------*/ static void prvDemoQueueSpaceFunctions( void * pvParameters ) { QueueHandle_t xQueue = NULL; const unsigned portBASE_TYPE uxQueueLength = 10; unsigned portBASE_TYPE uxReturn, x; /* Remove compiler warnings. */ ( void ) pvParameters; /* Create the queue that will be used. Nothing is actually going to be * sent or received so the queue item size is set to 0. */ xQueue = xQueueCreate( uxQueueLength, 0 ); configASSERT( xQueue ); for( ; ; ) { for( x = 0; x < uxQueueLength; x++ ) { /* Ask how many messages are available... */ uxReturn = uxQueueMessagesWaiting( xQueue ); /* Check the number of messages being reported as being available * is as expected, and force an assert if not. */ if( uxReturn != x ) { /* xQueue cannot be NULL so this is deliberately causing an * assert to be triggered as there is an error. */ configASSERT( xQueue == NULL ); } /* Ask how many spaces remain in the queue... */ uxReturn = uxQueueSpacesAvailable( xQueue ); /* Check the number of spaces being reported as being available * is as expected, and force an assert if not. */ if( uxReturn != ( uxQueueLength - x ) ) { /* xQueue cannot be NULL so this is deliberately causing an * assert to be triggered as there is an error. */ configASSERT( xQueue == NULL ); } /* Fill one more space in the queue. */ xQueueSendToBack( xQueue, NULL, 0 ); } /* Perform the same check while the queue is full. */ uxReturn = uxQueueMessagesWaiting( xQueue ); if( uxReturn != uxQueueLength ) { configASSERT( xQueue == NULL ); } uxReturn = uxQueueSpacesAvailable( xQueue ); if( uxReturn != 0 ) { configASSERT( xQueue == NULL ); } /* The queue is full, start again. */ xQueueReset( xQueue ); #if ( configUSE_PREEMPTION == 0 ) taskYIELD(); #endif } } /*-----------------------------------------------------------*/ static void prvPermanentlyBlockingSemaphoreTask( void * pvParameters ) { SemaphoreHandle_t xSemaphore; /* Prevent compiler warning about unused parameter in the case that * configASSERT() is not defined. */ ( void ) pvParameters; /* This task should block on a semaphore, and never return. */ xSemaphore = xSemaphoreCreateBinary(); configASSERT( xSemaphore ); xSemaphoreTake( xSemaphore, portMAX_DELAY ); /* The above xSemaphoreTake() call should never return, force an assert if * it does. */ configASSERT( pvParameters != NULL ); vTaskDelete( NULL ); } /*-----------------------------------------------------------*/ static void prvPermanentlyBlockingNotificationTask( void * pvParameters ) { /* Prevent compiler warning about unused parameter in the case that * configASSERT() is not defined. */ ( void ) pvParameters; /* This task should block on a task notification, and never return. */ ulTaskNotifyTake( pdTRUE, portMAX_DELAY ); /* The above ulTaskNotifyTake() call should never return, force an assert * if it does. */ configASSERT( pvParameters != NULL ); vTaskDelete( NULL ); } /*-----------------------------------------------------------*/ static void prvReloadModeTestTimerCallback( TimerHandle_t xTimer ) { intptr_t ulTimerID; /* Increment the timer's ID to show the callback has executed. */ ulTimerID = ( intptr_t ) pvTimerGetTimerID( xTimer ); ulTimerID++; vTimerSetTimerID( xTimer, ( void * ) ulTimerID ); } /*-----------------------------------------------------------*/ static void prvDemonstrateChangingTimerReloadMode( void * pvParameters ) { TimerHandle_t xTimer; const char * const pcTimerName = "TestTimer"; const TickType_t x100ms = pdMS_TO_TICKS( 100UL ); /* Avoid compiler warnings about unused parameter. */ ( void ) pvParameters; xTimer = xTimerCreate( pcTimerName, x100ms, pdFALSE, /* Created as a one-shot timer. */ 0, prvReloadModeTestTimerCallback ); configASSERT( xTimer ); configASSERT( xTimerIsTimerActive( xTimer ) == pdFALSE ); configASSERT( xTimerGetTimerDaemonTaskHandle() != NULL ); configASSERT( strcmp( pcTimerName, pcTimerGetName( xTimer ) ) == 0 ); configASSERT( xTimerGetPeriod( xTimer ) == x100ms ); /* Timer was created as a one-shot timer. Its callback just increments the * timer's ID - so set the ID to 0, let the timer run for a number of timeout * periods, then check the timer has only executed once. */ vTimerSetTimerID( xTimer, ( void * ) 0 ); xTimerStart( xTimer, portMAX_DELAY ); vTaskDelay( 3UL * x100ms ); configASSERT( ( ( uintptr_t ) ( pvTimerGetTimerID( xTimer ) ) ) == 1UL ); /* Now change the timer to be an auto-reload timer and check it executes * the expected number of times. */ vTimerSetReloadMode( xTimer, pdTRUE ); vTimerSetTimerID( xTimer, ( void * ) 0 ); xTimerStart( xTimer, 0 ); vTaskDelay( ( 3UL * x100ms ) + ( x100ms / 2UL ) ); /* Three full periods. */ configASSERT( ( uintptr_t ) ( pvTimerGetTimerID( xTimer ) ) == 3UL ); configASSERT( xTimerStop( xTimer, 0 ) != pdFAIL ); /* Now change the timer back to be a one-shot timer and check it only * executes once. */ vTimerSetReloadMode( xTimer, pdFALSE ); vTimerSetTimerID( xTimer, ( void * ) 0 ); xTimerStart( xTimer, 0 ); vTaskDelay( 3UL * x100ms ); configASSERT( xTimerStop( xTimer, 0 ) != pdFAIL ); configASSERT( ( uintptr_t ) ( pvTimerGetTimerID( xTimer ) ) == 1UL ); /* Clean up at the end. */ xTimerDelete( xTimer, portMAX_DELAY ); vTaskDelete( NULL ); }
/* * Copyright (c) 2016, Alliance for Open Media. All rights reserved * * This source code is subject to the terms of the BSD 2 Clause License and * the Alliance for Open Media Patent License 1.0. If the BSD 2 Clause License * was not distributed with this source code in the LICENSE file, you can * obtain it at www.aomedia.org/license/software. If the Alliance for Open * Media Patent License 1.0 was not distributed with this source code in the * PATENTS file, you can obtain it at www.aomedia.org/license/patent. */ #include <stdlib.h> #include "./macros_msa.h" void aom_plane_add_noise_msa(uint8_t *start_ptr, char *noise, char blackclamp[16], char whiteclamp[16], char bothclamp[16], uint32_t width, uint32_t height, int32_t pitch) { uint32_t i, j; for (i = 0; i < height / 2; ++i) { uint8_t *pos0_ptr = start_ptr + (2 * i) * pitch; int8_t *ref0_ptr = (int8_t *)(noise + (rand() & 0xff)); uint8_t *pos1_ptr = start_ptr + (2 * i + 1) * pitch; int8_t *ref1_ptr = (int8_t *)(noise + (rand() & 0xff)); for (j = width / 16; j--;) { v16i8 temp00_s, temp01_s; v16u8 temp00, temp01, black_clamp, white_clamp; v16u8 pos0, ref0, pos1, ref1; v16i8 const127 = __msa_ldi_b(127); pos0 = LD_UB(pos0_ptr); ref0 = LD_UB(ref0_ptr); pos1 = LD_UB(pos1_ptr); ref1 = LD_UB(ref1_ptr); black_clamp = (v16u8)__msa_fill_b(blackclamp[0]); white_clamp = (v16u8)__msa_fill_b(whiteclamp[0]); temp00 = (pos0 < black_clamp); pos0 = __msa_bmnz_v(pos0, black_clamp, temp00); temp01 = (pos1 < black_clamp); pos1 = __msa_bmnz_v(pos1, black_clamp, temp01); XORI_B2_128_UB(pos0, pos1); temp00_s = __msa_adds_s_b((v16i8)white_clamp, const127); temp00 = (v16u8)(temp00_s < pos0); pos0 = (v16u8)__msa_bmnz_v((v16u8)pos0, (v16u8)temp00_s, temp00); temp01_s = __msa_adds_s_b((v16i8)white_clamp, const127); temp01 = (temp01_s < pos1); pos1 = (v16u8)__msa_bmnz_v((v16u8)pos1, (v16u8)temp01_s, temp01); XORI_B2_128_UB(pos0, pos1); pos0 += ref0; ST_UB(pos0, pos0_ptr); pos1 += ref1; ST_UB(pos1, pos1_ptr); pos0_ptr += 16; pos1_ptr += 16; ref0_ptr += 16; ref1_ptr += 16; } } }