diff --git a/RunMe First/x64/Unregister.bat b/Install/Install.bat similarity index 86% rename from RunMe First/x64/Unregister.bat rename to Install/Install.bat index 374b06c..7c76195 100644 --- a/RunMe First/x64/Unregister.bat +++ b/Install/Install.bat @@ -1,27 +1,28 @@ -@echo off - -:: BatchGotAdmin -:------------------------------------- -REM --> Check for permissions ->nul 2>&1 "%SYSTEMROOT%\system32\cacls.exe" "%SYSTEMROOT%\system32\config\system" - -REM --> If error flag set, we do not have admin. -if '%errorlevel%' NEQ '0' ( - echo Requesting administrative privileges... - goto UACPrompt -) else ( goto gotAdmin ) - -:UACPrompt - echo Set UAC = CreateObject^("Shell.Application"^) > "%temp%\getadmin.vbs" - set params = %*:"="" - echo UAC.ShellExecute "cmd.exe", "/c %~s0 %params%", "", "runas", 1 >> "%temp%\getadmin.vbs" - - "%temp%\getadmin.vbs" - del "%temp%\getadmin.vbs" - exit /B - -:gotAdmin - pushd "%CD%" - CD /D "%~dp0" - regsvr32 /u UnityCamService.dll -:-------------------------------------- +@echo off + +:: BatchGotAdmin +:------------------------------------- +REM --> Check for permissions +>nul 2>&1 "%SYSTEMROOT%\system32\cacls.exe" "%SYSTEMROOT%\system32\config\system" + +REM --> If error flag set, we do not have admin. +if '%errorlevel%' NEQ '0' ( + echo Requesting administrative privileges... + goto UACPrompt +) else ( goto gotAdmin ) + +:UACPrompt + echo Set UAC = CreateObject^("Shell.Application"^) > "%temp%\getadmin.vbs" + set params = %*:"="" + echo UAC.ShellExecute "cmd.exe", "/c %~s0 %params%", "", "runas", 1 >> "%temp%\getadmin.vbs" + + "%temp%\getadmin.vbs" + del "%temp%\getadmin.vbs" + exit /B + +:gotAdmin + pushd "%CD%" + CD /D "%~dp0" + regsvr32 "UnityCaptureFilter32.dll" + regsvr32 "UnityCaptureFilter64.dll" +:-------------------------------------- diff --git a/RunMe First/x32/Unregister.bat b/Install/InstallCustomName.bat similarity index 66% rename from RunMe First/x32/Unregister.bat rename to Install/InstallCustomName.bat index 374b06c..cc186d2 100644 --- a/RunMe First/x32/Unregister.bat +++ b/Install/InstallCustomName.bat @@ -1,27 +1,31 @@ -@echo off - -:: BatchGotAdmin -:------------------------------------- -REM --> Check for permissions ->nul 2>&1 "%SYSTEMROOT%\system32\cacls.exe" "%SYSTEMROOT%\system32\config\system" - -REM --> If error flag set, we do not have admin. -if '%errorlevel%' NEQ '0' ( - echo Requesting administrative privileges... - goto UACPrompt -) else ( goto gotAdmin ) - -:UACPrompt - echo Set UAC = CreateObject^("Shell.Application"^) > "%temp%\getadmin.vbs" - set params = %*:"="" - echo UAC.ShellExecute "cmd.exe", "/c %~s0 %params%", "", "runas", 1 >> "%temp%\getadmin.vbs" - - "%temp%\getadmin.vbs" - del "%temp%\getadmin.vbs" - exit /B - -:gotAdmin - pushd "%CD%" - CD /D "%~dp0" - regsvr32 /u UnityCamService.dll -:-------------------------------------- +@echo off + +:: BatchGotAdmin +:------------------------------------- +REM --> Check for permissions +>nul 2>&1 "%SYSTEMROOT%\system32\cacls.exe" "%SYSTEMROOT%\system32\config\system" + +REM --> If error flag set, we do not have admin. +if '%errorlevel%' NEQ '0' ( + echo Requesting administrative privileges... + goto UACPrompt +) else ( goto gotAdmin ) + +:UACPrompt + echo Set UAC = CreateObject^("Shell.Application"^) > "%temp%\getadmin.vbs" + set params = %*:"="" + echo UAC.ShellExecute "cmd.exe", "/c %~s0 %params%", "", "runas", 1 >> "%temp%\getadmin.vbs" + + "%temp%\getadmin.vbs" + del "%temp%\getadmin.vbs" + exit /B + +:gotAdmin + pushd "%CD%" + CD /D "%~dp0" + set /P "UCCAPNAME=Enter a custom filter name to register as (default is 'Unity Video Capture'): " + echo Installing capture device named '%UCCAPNAME%' ... + regsvr32 "UnityCaptureFilter32.dll" "/i:UnityCaptureName=%UCCAPNAME%" + regsvr32 "UnityCaptureFilter64.dll" "/i:UnityCaptureName=%UCCAPNAME%" + echo "Done" +:-------------------------------------- diff --git a/RunMe First/x64/Register.bat b/Install/InstallMultipleDevices.bat similarity index 68% rename from RunMe First/x64/Register.bat rename to Install/InstallMultipleDevices.bat index 25e4e66..069c3e3 100644 --- a/RunMe First/x64/Register.bat +++ b/Install/InstallMultipleDevices.bat @@ -1,27 +1,31 @@ -@echo off - -:: BatchGotAdmin -:------------------------------------- -REM --> Check for permissions ->nul 2>&1 "%SYSTEMROOT%\system32\cacls.exe" "%SYSTEMROOT%\system32\config\system" - -REM --> If error flag set, we do not have admin. -if '%errorlevel%' NEQ '0' ( - echo Requesting administrative privileges... - goto UACPrompt -) else ( goto gotAdmin ) - -:UACPrompt - echo Set UAC = CreateObject^("Shell.Application"^) > "%temp%\getadmin.vbs" - set params = %*:"="" - echo UAC.ShellExecute "cmd.exe", "/c %~s0 %params%", "", "runas", 1 >> "%temp%\getadmin.vbs" - - "%temp%\getadmin.vbs" - del "%temp%\getadmin.vbs" - exit /B - -:gotAdmin - pushd "%CD%" - CD /D "%~dp0" - regsvr32 UnityCamService.dll -:-------------------------------------- +@echo off + +:: BatchGotAdmin +:------------------------------------- +REM --> Check for permissions +>nul 2>&1 "%SYSTEMROOT%\system32\cacls.exe" "%SYSTEMROOT%\system32\config\system" + +REM --> If error flag set, we do not have admin. +if '%errorlevel%' NEQ '0' ( + echo Requesting administrative privileges... + goto UACPrompt +) else ( goto gotAdmin ) + +:UACPrompt + echo Set UAC = CreateObject^("Shell.Application"^) > "%temp%\getadmin.vbs" + set params = %*:"="" + echo UAC.ShellExecute "cmd.exe", "/c %~s0 %params%", "", "runas", 1 >> "%temp%\getadmin.vbs" + + "%temp%\getadmin.vbs" + del "%temp%\getadmin.vbs" + exit /B + +:gotAdmin + pushd "%CD%" + CD /D "%~dp0" + set /P "UCNUMCAP=Enter number of capture devices you want to register: " + echo "Installing %UCNUMCAP% capture devices ..." + regsvr32 "UnityCaptureFilter32.dll" "/i:UnityCaptureDevices=%UCNUMCAP%" + regsvr32 "UnityCaptureFilter64.dll" "/i:UnityCaptureDevices=%UCNUMCAP%" + echo "Done" +:-------------------------------------- diff --git a/RunMe First/x32/Register.bat b/Install/Uninstall.bat similarity index 86% rename from RunMe First/x32/Register.bat rename to Install/Uninstall.bat index 25e4e66..291f8a9 100644 --- a/RunMe First/x32/Register.bat +++ b/Install/Uninstall.bat @@ -1,27 +1,28 @@ -@echo off - -:: BatchGotAdmin -:------------------------------------- -REM --> Check for permissions ->nul 2>&1 "%SYSTEMROOT%\system32\cacls.exe" "%SYSTEMROOT%\system32\config\system" - -REM --> If error flag set, we do not have admin. -if '%errorlevel%' NEQ '0' ( - echo Requesting administrative privileges... - goto UACPrompt -) else ( goto gotAdmin ) - -:UACPrompt - echo Set UAC = CreateObject^("Shell.Application"^) > "%temp%\getadmin.vbs" - set params = %*:"="" - echo UAC.ShellExecute "cmd.exe", "/c %~s0 %params%", "", "runas", 1 >> "%temp%\getadmin.vbs" - - "%temp%\getadmin.vbs" - del "%temp%\getadmin.vbs" - exit /B - -:gotAdmin - pushd "%CD%" - CD /D "%~dp0" - regsvr32 UnityCamService.dll -:-------------------------------------- +@echo off + +:: BatchGotAdmin +:------------------------------------- +REM --> Check for permissions +>nul 2>&1 "%SYSTEMROOT%\system32\cacls.exe" "%SYSTEMROOT%\system32\config\system" + +REM --> If error flag set, we do not have admin. +if '%errorlevel%' NEQ '0' ( + echo Requesting administrative privileges... + goto UACPrompt +) else ( goto gotAdmin ) + +:UACPrompt + echo Set UAC = CreateObject^("Shell.Application"^) > "%temp%\getadmin.vbs" + set params = %*:"="" + echo UAC.ShellExecute "cmd.exe", "/c %~s0 %params%", "", "runas", 1 >> "%temp%\getadmin.vbs" + + "%temp%\getadmin.vbs" + del "%temp%\getadmin.vbs" + exit /B + +:gotAdmin + pushd "%CD%" + CD /D "%~dp0" + regsvr32 /u "UnityCaptureFilter32.dll" + regsvr32 /u "UnityCaptureFilter64.dll" +:-------------------------------------- diff --git a/Install/UnityCaptureFilter32.dll b/Install/UnityCaptureFilter32.dll new file mode 100644 index 0000000..da0b410 Binary files /dev/null and b/Install/UnityCaptureFilter32.dll differ diff --git a/Install/UnityCaptureFilter64.dll b/Install/UnityCaptureFilter64.dll new file mode 100644 index 0000000..cd6d7de Binary files /dev/null and b/Install/UnityCaptureFilter64.dll differ diff --git a/LICENSE b/LICENSE deleted file mode 100644 index 18b7244..0000000 --- a/LICENSE +++ /dev/null @@ -1,21 +0,0 @@ -The MIT License (MIT) - -Copyright (c) 2016 MHD Yamen Saraiji - -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. diff --git a/README.md b/README.md index c8ae1a8..8268e62 100644 --- a/README.md +++ b/README.md @@ -1,50 +1,154 @@ -UnityCam -======== -![UnityCam](http://myamens.com/Uploads/UnityCam/UnityCam.gif) - -This plugin provides a way for unity3D applications and games to output the viewport to an external application and use the viewport as a webcamera for such applications. - -For example: Recording viewport in a webcamera capture software (Sharpcap), or using it in browser applications (tested in Chrome). - -Tested Platforms: ------------------ -- Tested on Windows 64 bits -- Tested using Unity 32,64 bits - -For Skype, please use x32 version of the service found in "RunMe First" folder, check instructions bellow for how to run it. - -Usage -===== - -1) Before using, access folder "RunMe First", access the target platform folder (x32,x64) which depends on the application you will use to view the virtual camera in. Right click on "Register.bat" and choose "Run as Administrator" to register UnityCam plugin in Windows. A window will appear to confirm that the plugin was successfully registered. - -2) Inside unity, attach to the main camera the following component: - UnityCam\Scripts\UnityCam.cs - -3) Hit Play, now unity will stream whatever being rendered as a webcamera. You can use it in browser or any video capture program via the new camera UnityCam. - -Check the included sample scene for a fully working example. - - -License -------- - -Copyright (c) 2016 MHD Yamen Saraiji - -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. +# Unity Capture + +![Unity Capture and OBS](https://raw.githubusercontent.com/schellingb/UnityCapture/master/README.png) + +## Overview + +Unity Capture is a Windows DirectShow Filter that allows you to stream a rendered camera directly to another application. +In more simple terms, it essentially makes Unity simulate a web cam device on Windows that shows a rendered camera. + +This project is based on [UnityCam by Yamen Saraiji](//github.com/mrayy/UnityCam) with added features and big performance +improvements. It supports lag-free 1080p at 60 FPS on moderate PCs and can handle 4K resolutions on a faster PC. +It also supports capturing multiple cameras and alpha channel (transparency) in receiving applications that +support it (like [OBS](https://obsproject.com/)). + + +## Installation + +First download this project from GitHub with the [`Download ZIP`](../../archive/master.zip) button or by cloning the repository. + +To register the DirectShow Filter to be available in Windows programs, run the `Install.bat` inside the `Install` directory. +Make sure the files in the install directory are placed where you want them to be. +If you want to move or delete the files, run `Uninstall.bat` first. + +If you have problems registering or unregistering, right click on the Install.bat and choose "Run as Administrator". + +The script `Install.bat` registers just a single capture device usable for capturing a single Unity camera. If you want to +capture multiple cameras simultaneously you can instead run the `InstallMultipleDevices.bat` script which prompts for a +number of capture devices you wish to register. + +### Update + +When updating from a version from before April 2023 it is recommended to uninstall the old version first. +The old version is available [`here`](../../archive/7a3278dcefe37544370226e92bdfd60140434045.zip). + + +## Test in Unity + +Open the included UnityCaptureSample project in Unity, load the scene 'UnityCaptureExample' and hit play. +Then run a receiving application (like [OBS](https://obsproject.com/), any program with web cam support +or a [WebRTC website](https://webrtc.github.io/samples/src/content/getusermedia/resolution/)) and request +video from the "Unity Video Capture" device. + +You should see the rendering output from Unity displayed in your target application. + +If you see a message about matching rendering and display resolutions, use the resolution settings on +the 'Game' tab in Unity to set a fixed resolution to match the capture output. + + +## Setup in your Unity project + +Just copy the [UnityCapture asset directory from the included sample project](UnityCaptureSample/Assets/UnityCapture) +into your own project and then add the 'Unity Capture' behavior to your camera at the bottom. + +You can also enable this behavior on a secondary camera that is not your main game camera by setting a target texture +with your desired capture output resolution. + +If you want to capture multiple cameras simultaneously you can refer to the 'UnityCaptureMultiCam' scene +and the 'MultiCam' script used by it. + +If you want to capture a custom texture (generated texture, a video, another webcam feed or a static image) you +can refer to the 'UnityCaptureTextureExample' scene and the 'CaptureTexture' script used by it. + +### Settings + +There are a few settings for the 'Unity Capture' behavior. + +- 'Capture Device': Set the capture device filter number (only relevant when multiple capture devices were [installed](#installation)) +- 'Timeout': Sets how many milliseconds to wait for a new frame until sending is considered to be stopped + If rendering every frame this can be very low. Default is 1000 to allow stalls due to loading, etc. + When set to 0 the image will stay up even when Unity is ended (until the receiving application also ends). +- 'Resize Mode': It is suggested to leave this disabled and just let your capture target application handle the display + sizing/resizing because this setting can introduce frame skipping. So far only a very basic linear resize is supported. +- 'Mirror Mode': This setting should also be handled by your target application if possible and needed, but it is available. +- 'Double Buffering': See [performance caveats](#performance-caveats) below +- 'Enable V Sync': Overwrite the state of the application v-sync setting on component start +- 'Target Frame Rate': Overwrite the application target fps setting on component start +- 'Hide Warnings': Disable output of warning messages (but not errors) + +### Possible errors/warnings + +- Warning: "Capture device did skip a frame read, capture frame rate will not match render frame rate." + Output when a frame rendered by Unity was never displayed in the target capture application due + to performance problems or target application being slow. +- Warning: "Capture device is inactive" + If the target capture application has not been started yet. +- Error: "Unsupported graphics device (only D3D11 supported)" + When Unity uses a rendering back-end other than Direct 3D 11. +- Error: "Render resolution is too large to send to capture device" + When trying to send data with a resolution higher than the maximum supported 3840 x 2160 +- Error: "Render texture format is unsupported" + When the rendered data/color format would require additional conversation. +- Error: "Error while reading texture image data" + Generic error when the plugin is unable to access the rendered image pixel data. + + +## Output Device Configuration + +In your receiving application mainly two settings are of relevance. +Depending on the application, the settings might be named different or not available at all in which case it will fall back to a default. + - Resolution: Set this to match the rendering resolution in Unity. Depending on your target application you may be able + to request a custom resolution. For instance in OBS you can input 512x512 into the resolution settings textbox. + For custom resolutions, make sure width is specified in increments of 4. + - Video Format: Set this to ARGB if you want to capture the alpha channel (transparency). +Other settings like FPS, color space or buffering are irrelevant as the output from Unity controls these parameters. + +There are four additional settings in the configuration panel offered by the capture device. Some applications like OBS allow you to access +these settings with a 'Configure Video' button, other applications like web browsers might not. + +These settings control what will be displayed in the output in case of an error: +- 'Resolution mismatch': When resizing in the Unity behavior is disabled and the capture output and the rendering resolutions don't match. +- 'Unity never started': When rendering in Unity with a 'Unity Capture' behavior has never started sending video data. +- 'Unity sending stopped': When video data stops being received (i.e. Unity game stopped or crashed). + +There are four modes that can be set for the settings above: +- 'Fill Black': Show just black. +- 'Blue/Pink Pattern': A pattern that is blue and pink. +- 'Green/Yellow Pattern': A pattern that is green and yellow. +- 'Green Key (RGB #00FE00)': Fills the output with a specific color (red and blue at 0, green at 254). + This can be used for instance in OBS with the 'Color Key' video filter to show a layer behind the video capture. + You can use this if you want to show a 'Please stand by...' image layer when Unity is stopped. + +The settings 'Fill Black' and 'Green Key' are shown as completely transparent when capturing with alpha channel. + +For the two colored patterns an additional text message will be displayed detailing the error. + +The setting 'Display FPS' shows the capture frame rate (frames per second) on the capture device output. + + +## Performance caveats + +There are two main improvements to capture stream frame rate. + +One is to disable the camera setting 'Allow HDR' which causes the camera output texture format +to be in a favorable format (8-bit integer per color per pixel). If your shaders and post-processing +allow it, it's recommended to leave HDR off. + +The other is the setting 'DoubleBuffering' in the UnityCapture component. +Double buffering causes 1 frame of additional latency but improves the image data throughput. +You can check the Unity profiler for how much it impacts performance in your project. + +Otherwise it is recommended to leave scaling and mirroring disabled in the UnityCapture component. + + +## Todo + +- Saving of the output device configuration +- Bilinear filtered resizing + + +## License + +Unity Capture is divided into two parts that are separately licensed. +The filter 'UnityCaptureFilter' is available under the [MIT license](https://choosealicense.com/licenses/mit/). +The Unity plugin 'UnityCapturePlugin' is available under the [zlib license](https://choosealicense.com/licenses/zlib/) (so attribution in your Unity project is optional). diff --git a/README.png b/README.png new file mode 100644 index 0000000..fe5fafd Binary files /dev/null and b/README.png differ diff --git a/RunMe First/x32/UnityCamService.dll b/RunMe First/x32/UnityCamService.dll deleted file mode 100644 index 830a34d..0000000 Binary files a/RunMe First/x32/UnityCamService.dll and /dev/null differ diff --git a/RunMe First/x64/UnityCamService.dll b/RunMe First/x64/UnityCamService.dll deleted file mode 100644 index d4d3f57..0000000 Binary files a/RunMe First/x64/UnityCamService.dll and /dev/null differ diff --git a/Source/.gitignore b/Source/.gitignore new file mode 100644 index 0000000..68473d7 --- /dev/null +++ b/Source/.gitignore @@ -0,0 +1,7 @@ +.vs/* +Build/* +*.suo +*.user +*.sdf +*.opensdf +*.db diff --git a/UnityWebcam/UnityWebcam/IUnityGraphics.h b/Source/IUnityGraphics.h similarity index 67% rename from UnityWebcam/UnityWebcam/IUnityGraphics.h rename to Source/IUnityGraphics.h index 98b5a61..f8c8e07 100644 --- a/UnityWebcam/UnityWebcam/IUnityGraphics.h +++ b/Source/IUnityGraphics.h @@ -1,58 +1,9 @@ #pragma once #include "IUnityInterface.h" -// Which platform we are on? -#if _MSC_VER -#define UNITY_WIN 1 -#else -#define UNITY_OSX 1 -#endif - - -// Which graphics device APIs we possibly support? -#if UNITY_WIN -#define SUPPORT_D3D9 0 -#define SUPPORT_D3D11 1 // comment this out if you don't have D3D11 header/library files -#define SUPPORT_OPENGL 1 -#endif - -#if UNITY_OSX -#define SUPPORT_OPENGL 1 -#endif - - -#if SUPPORT_D3D9 -#include -#endif -#if SUPPORT_D3D11 -#include -#endif -#if SUPPORT_OPENGL -#if UNITY_WIN -#include -#else -#include -#endif -#endif - -extern void* g_GraphicsDevice; -extern int g_GraphicsDeviceType; - -// Forward declarations. -struct IDirect3DDevice9; -struct ID3D11Device; - -#if SUPPORT_D3D9 -extern IDirect3DDevice9* g_D3D9GraphicsDevice; -#endif -#if SUPPORT_D3D11 -extern ID3D11Device* g_D3D11GraphicsDevice; -#endif - - typedef enum UnityGfxRenderer { - kUnityGfxRendererOpenGL = 0, // Desktop OpenGL 2 (deprecated) + kUnityGfxRendererOpenGL = 0, // Legacy OpenGL kUnityGfxRendererD3D9 = 1, // Direct3D 9 kUnityGfxRendererD3D11 = 2, // Direct3D 11 kUnityGfxRendererGCM = 3, // PlayStation 3 @@ -62,9 +13,9 @@ typedef enum UnityGfxRenderer kUnityGfxRendererOpenGLES30 = 11, // OpenGL ES 3.x kUnityGfxRendererGXM = 12, // PlayStation Vita kUnityGfxRendererPS4 = 13, // PlayStation 4 - kUnityGfxRendererXboxOne = 14, // Xbox One + kUnityGfxRendererXboxOne = 14, // Xbox One kUnityGfxRendererMetal = 16, // iOS Metal - kUnityGfxRendererOpenGLCore = 17, // Desktop OpenGL core + kUnityGfxRendererOpenGLCore = 17, // OpenGL core kUnityGfxRendererD3D12 = 18, // Direct3D 12 } UnityGfxRenderer; diff --git a/UnityWebcam/UnityWebcam/IUnityInterface.h b/Source/IUnityInterface.h similarity index 100% rename from UnityWebcam/UnityWebcam/IUnityInterface.h rename to Source/IUnityInterface.h diff --git a/Source/Tool_RegisterOneInBuild.bat b/Source/Tool_RegisterOneInBuild.bat new file mode 100644 index 0000000..bd1533a --- /dev/null +++ b/Source/Tool_RegisterOneInBuild.bat @@ -0,0 +1,58 @@ +@echo off + +:: BatchGotAdmin +:------------------------------------- +REM --> Check for permissions +>nul 2>&1 "%SYSTEMROOT%\system32\cacls.exe" "%SYSTEMROOT%\system32\config\system" + +REM --> If error flag set, we do not have admin. +if '%errorlevel%' NEQ '0' ( + echo Requesting administrative privileges... + goto UACPrompt +) else ( goto gotAdmin ) + +:UACPrompt + echo Set UAC = CreateObject^("Shell.Application"^) > "%temp%\getadmin.vbs" + set params = %*:"="" + echo UAC.ShellExecute "cmd.exe", "/c %~s0 %params%", "", "runas", 1 >> "%temp%\getadmin.vbs" + + "%temp%\getadmin.vbs" + del "%temp%\getadmin.vbs" + exit /B + +:gotAdmin + pushd "%CD%" + CD /D "%~dp0\Build" + + ECHO Select the configuration and platform variation you want to register + CLS + ECHO 1. Debug - 64 bit + ECHO 2. Release - 64 bit + ECHO 3. Debug - 32 bit + ECHO 4. Release - 64 bit + ECHO. + + CHOICE /C 1234 /M "Enter your choice:" + + :: Note - list ERRORLEVELS in decreasing order + IF ERRORLEVEL 4 GOTO Release32bit + IF ERRORLEVEL 3 GOTO Debug32bit + IF ERRORLEVEL 2 GOTO Releae64bit + IF ERRORLEVEL 1 GOTO Debug64bit + +:Debug64bit + regsvr32 "Debug-UnityCaptureFilter64bit\UnityCaptureFilter64bit.dll" + GOTO End + +:Releae64bit + regsvr32 "Release-UnityCaptureFilter64bit\UnityCaptureFilter64bit.dll" + GOTO End + +:Debug32bit + regsvr32 "Debug-UnityCaptureFilter32bit\UnityCaptureFilter32bit.dll" + GOTO End + +:Release32bit + regsvr32 "Release-UnityCaptureFilter32bit\UnityCaptureFilter32bit.dll" + GOTO End +:-------------------------------------- diff --git a/Source/Tool_UnregisterAllInBuild.bat b/Source/Tool_UnregisterAllInBuild.bat new file mode 100644 index 0000000..3208c41 --- /dev/null +++ b/Source/Tool_UnregisterAllInBuild.bat @@ -0,0 +1,30 @@ +@echo off + +:: BatchGotAdmin +:------------------------------------- +REM --> Check for permissions +>nul 2>&1 "%SYSTEMROOT%\system32\cacls.exe" "%SYSTEMROOT%\system32\config\system" + +REM --> If error flag set, we do not have admin. +if '%errorlevel%' NEQ '0' ( + echo Requesting administrative privileges... + goto UACPrompt +) else ( goto gotAdmin ) + +:UACPrompt + echo Set UAC = CreateObject^("Shell.Application"^) > "%temp%\getadmin.vbs" + set params = %*:"="" + echo UAC.ShellExecute "cmd.exe", "/c %~s0 %params%", "", "runas", 1 >> "%temp%\getadmin.vbs" + + "%temp%\getadmin.vbs" + del "%temp%\getadmin.vbs" + exit /B + +:gotAdmin + pushd "%CD%" + CD /D "%~dp0\Build" + regsvr32 /u "Debug-UnityCaptureFilter32bit\UnityCaptureFilter32bit.dll" + regsvr32 /u "Debug-UnityCaptureFilter64bit\UnityCaptureFilter64bit.dll" + regsvr32 /u "Release-UnityCaptureFilter32bit\UnityCaptureFilter32bit.dll" + regsvr32 /u "Release-UnityCaptureFilter64bit\UnityCaptureFilter64bit.dll" +:-------------------------------------- diff --git a/Source/UnityCapture.sln b/Source/UnityCapture.sln new file mode 100644 index 0000000..92ed549 --- /dev/null +++ b/Source/UnityCapture.sln @@ -0,0 +1,37 @@ + +Microsoft Visual Studio Solution File, Format Version 12.00 +# Visual Studio 2013 +VisualStudioVersion = 12.0.40629.0 +MinimumVisualStudioVersion = 10.0.40219.1 +Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "UnityCaptureFilter", "UnityCaptureFilter.vcxproj", "{3D0A9889-9EC1-4012-9382-4FE1EB610D28}" +Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "UnityCapturePlugin", "UnityCapturePlugin.vcxproj", "{727D3AC5-27B5-4288-A475-7A471ECD71B8}" +EndProject +Global + GlobalSection(SolutionConfigurationPlatforms) = preSolution + Debug|Win32 = Debug|Win32 + Debug|x64 = Debug|x64 + Release|Win32 = Release|Win32 + Release|x64 = Release|x64 + EndGlobalSection + GlobalSection(ProjectConfigurationPlatforms) = postSolution + {3D0A9889-9EC1-4012-9382-4FE1EB610D28}.Debug|Win32.ActiveCfg = Debug|Win32 + {3D0A9889-9EC1-4012-9382-4FE1EB610D28}.Debug|Win32.Build.0 = Debug|Win32 + {3D0A9889-9EC1-4012-9382-4FE1EB610D28}.Debug|x64.ActiveCfg = Debug|x64 + {3D0A9889-9EC1-4012-9382-4FE1EB610D28}.Debug|x64.Build.0 = Debug|x64 + {3D0A9889-9EC1-4012-9382-4FE1EB610D28}.Release|Win32.ActiveCfg = Release|Win32 + {3D0A9889-9EC1-4012-9382-4FE1EB610D28}.Release|Win32.Build.0 = Release|Win32 + {3D0A9889-9EC1-4012-9382-4FE1EB610D28}.Release|x64.ActiveCfg = Release|x64 + {3D0A9889-9EC1-4012-9382-4FE1EB610D28}.Release|x64.Build.0 = Release|x64 + {727D3AC5-27B5-4288-A475-7A471ECD71B8}.Debug|Win32.ActiveCfg = Debug|Win32 + {727D3AC5-27B5-4288-A475-7A471ECD71B8}.Debug|Win32.Build.0 = Debug|Win32 + {727D3AC5-27B5-4288-A475-7A471ECD71B8}.Debug|x64.ActiveCfg = Debug|x64 + {727D3AC5-27B5-4288-A475-7A471ECD71B8}.Debug|x64.Build.0 = Debug|x64 + {727D3AC5-27B5-4288-A475-7A471ECD71B8}.Release|Win32.ActiveCfg = Release|Win32 + {727D3AC5-27B5-4288-A475-7A471ECD71B8}.Release|Win32.Build.0 = Release|Win32 + {727D3AC5-27B5-4288-A475-7A471ECD71B8}.Release|x64.ActiveCfg = Release|x64 + {727D3AC5-27B5-4288-A475-7A471ECD71B8}.Release|x64.Build.0 = Release|x64 + EndGlobalSection + GlobalSection(SolutionProperties) = preSolution + HideSolutionNode = FALSE + EndGlobalSection +EndGlobal diff --git a/Source/UnityCaptureFilter.cpp b/Source/UnityCaptureFilter.cpp new file mode 100644 index 0000000..cef64c3 --- /dev/null +++ b/Source/UnityCaptureFilter.cpp @@ -0,0 +1,1229 @@ +/* + Unity Capture + Copyright (c) 2018 Bernhard Schelling + + Based on UnityCam + https://github.com/mrayy/UnityCam + Copyright (c) 2016 MHD Yamen Saraiji + + The MIT License (MIT) + + 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. +*/ + +#include "shared.inl" +#include "streams.h" +#include +#include +#include + +#define CaptureSourceName L"Unity Video Capture" + +//Use separate GUIDs for 64bit and 32bit so both can be installed at the same time +#ifdef _WIN64 +DEFINE_GUID(CLSID_UnityCaptureService, 0x5c2cd55c, 0x92ad, 0x4999, 0x86, 0x66, 0x91, 0x2b, 0xd3, 0xe7, 0x00, 0x10); +DEFINE_GUID(CLSID_UnityCaptureProperties, 0x5c2cd55c, 0x92ad, 0x4999, 0x86, 0x66, 0x91, 0x2b, 0xd3, 0xe7, 0x00, 0x11); +#else +DEFINE_GUID(CLSID_UnityCaptureService, 0x5c2cd55c, 0x92ad, 0x4999, 0x86, 0x66, 0x91, 0x2b, 0xd3, 0xe7, 0x00, 0x20); +DEFINE_GUID(CLSID_UnityCaptureProperties, 0x5c2cd55c, 0x92ad, 0x4999, 0x86, 0x66, 0x91, 0x2b, 0xd3, 0xe7, 0x00, 0x21); +#endif + +//List of resolutions offered by this filter +//If you add a higher resolution, make sure to update MAX_SHARED_IMAGE_SIZE +static struct { int width, height; } _media[] = +{ + { 1920, 1080 }, //16:9 + { 1280, 720 }, //16:9 + { 960, 540 }, //16:9 + { 640, 360 }, //16:9 + { 480, 270 }, //16:9 + { 256, 144 }, //16:9 + { 2560, 1440 }, //16:9 + { 3840, 2160 }, //16:9 + { 1440, 1080 }, //4:3 + { 960, 720 }, //4:3 + { 640, 480 }, //4:3 + { 480, 360 }, //4:3 + { 320, 240 }, //4:3 + { 192, 144 }, //4:3 + { 1920, 1440 }, //4:3 + { 2880, 2160 }, //4:3 + { 1920, 1200 }, //16:10 + { 1280, 800 }, //16:10 + { 2880, 1800 }, //16:10 + { 2560, 1600 }, //16:10 + { 1680, 1050 }, //16:10 + { 1440, 900 }, //16:10 + { 0, 0 }, //This slot is used for custom resolutions if requested by the target application +}; + +//Error draw modes (what to display on screen in case of errors/warnings) +enum EErrorDrawCase { EDC_ResolutionMismatch, EDC_UnityNeverStarted, EDC_UnitySendingStopped, _EDC_MAX }; +enum EErrorDrawMode { EDM_GREENKEY, EDM_BLUEPINK, EDM_GREENYELLOW, EDM_BLACK }; +static EErrorDrawMode ErrorDrawModes[_EDC_MAX] = { EDM_BLUEPINK, EDM_GREENYELLOW, EDM_GREENKEY }; +static wchar_t* ErrorDrawModeNames[] = { L"Green Key (RGB #00FE00)", L"Blue/Pink Pattern", L"Green/Yellow Pattern", L"Fill Black" }; +static bool OutputFrameRate = false; + +#ifdef _DEBUG +void DebugLog(const char *format, ...) +{ + char stackbuf[1024]; + stackbuf[0] = '\0'; + va_list ap; va_start(ap, format); vsnprintf_s(stackbuf, 1024, 1024, format, ap); va_end(ap); + stackbuf[1023] = '\0'; + OutputDebugStringA(stackbuf); +} +#else +#define DebugLog(...) ((void)0) +#endif + +//Interface definition for ICamSource used by CCaptureSource +DEFINE_GUID(IID_ICamSource, 0xdd20e647, 0xf3e5, 0x4156, 0xb3, 0x7b, 0x54, 0x6f, 0xcf, 0x88, 0xec, 0x50); +DECLARE_INTERFACE_(ICamSource, IUnknown) { }; + +class CCaptureStream : CSourceStream, IKsPropertySet, IAMStreamConfig, IAMStreamControl, IAMPushSource +{ +public: + CCaptureStream(CSource* pOwner, HRESULT* phr, int CapNum) : CSourceStream("Stream", phr, pOwner, L"Output") + { + m_llFrame = m_llFrameMissCount = 0; + m_prevStartTime = 0; + m_avgTimePerFrame = 10000000 / 30; + m_pReceiver = new SharedImageMemory(CapNum); + m_iUnscaledBufSize = 0; + m_pUnscaledBuf = NULL; + m_RGBA16Table = NULL; + GetMediaType(0, &m_mt); + } + + virtual ~CCaptureStream() + { + delete m_pReceiver; + if (m_pUnscaledBuf) free(m_pUnscaledBuf); + if (m_RGBA16Table) free(m_RGBA16Table); + } + +private: + HRESULT FillBuffer(IMediaSample *pSamp) override + { + HRESULT hr; + BYTE* pBuf; + VIDEOINFO *pvi = (VIDEOINFO*)m_mt.Format(); + REFERENCE_TIME startTime = m_prevStartTime, endTime = startTime + m_avgTimePerFrame; + LONGLONG mtStart = m_llFrame, mtEnd = mtStart + 1; + m_prevStartTime = endTime; + m_llFrame = mtEnd; + UCASSERT(pSamp->GetSize() == pvi->bmiHeader.biSizeImage); + UCASSERT(DIBSIZE(pvi->bmiHeader) == pvi->bmiHeader.biSizeImage); + + if (FAILED(hr = pSamp->GetPointer(&pBuf))) return hr; + if (FAILED(hr = pSamp->SetActualDataLength(pvi->bmiHeader.biSizeImage))) return hr; + if (FAILED(hr = pSamp->SetTime(&startTime, &endTime))) return hr; + if (FAILED(hr = pSamp->SetMediaTime(&mtStart, &mtEnd))) return hr; + + ProcessState State = { pBuf, pvi->bmiHeader.biWidth, pvi->bmiHeader.biHeight, pvi->bmiHeader.biBitCount / 8, this }; + switch (m_pReceiver->Receive((SharedImageMemory::ReceiveCallbackFunc)ProcessImage, &State)) + { + case SharedImageMemory::RECEIVERES_CAPTUREINACTIVE:{ + //Show color pattern indicating that Unity is not sending frame data yet + char DisplayString[128], *DisplayStrings[] = { DisplayString }; + int DisplayStringLens[] = { sprintf_s(DisplayString, sizeof(DisplayString), "Unity has not started sending image data (Capture Device #%d)", 1+m_pReceiver->GetCapNum()) }; + FillErrorPattern(ErrorDrawModes[EDC_UnityNeverStarted], &State, 1, DisplayStrings, DisplayStringLens, m_llFrame); + Sleep((DWORD)(m_avgTimePerFrame / 10000 - 1)); //just wait a bit until capturing next frame + break;} + + case SharedImageMemory::RECEIVERES_NEWFRAME: + if (m_llFrameMissCount) m_llFrameMissCount = 0; + break; + + case SharedImageMemory::RECEIVERES_OLDFRAME:{ + if (++m_llFrameMissCount < m_llFrameMissMax) break; + //Show color pattern when received more than X frames without new image (probably Unity stopped sending data) + char DisplayString[] = "Unity has stopped sending image data", *DisplayStrings[] = { DisplayString }; + int DisplayStringLens[] = { sizeof(DisplayString) - 1 }; + FillErrorPattern(ErrorDrawModes[EDC_UnitySendingStopped], &State, 1, DisplayStrings, DisplayStringLens, m_llFrame); + break;} + } + if (OutputFrameRate) RenderFPSDisplay(&State); + return S_OK; + } + + struct ProcessJob + { + enum EType { JOB_NONE, JOB_RGBA8toBGR8, JOB_RGBA8toBGRA8, JOB_RGBA16toBGR8, JOB_RGBA16toBGRA8, JOB_BGR_RESIZE_LINEAR, JOB_BGRA_RESIZE_LINEAR, JOB_BGR_MIRROR_HORIZONTAL, JOB_BGRA_MIRROR_HORIZONTAL } Type; + const void *BufIn; void *BufOut; + size_t Width, RowStart, RowEnd, RGBAInStride, ResizeToHeight, ResizeFromWidth, ResizeFromHeight; + const uint8_t* RGBA16Table; + + inline void Execute() + { + UCASSERT(RowEnd >= RowStart); + if (RowStart == RowEnd) return; + if (Type == JOB_RGBA8toBGR8) RGBA8toBGR8(); + else if (Type == JOB_RGBA8toBGRA8) RGBA8toBGRA8(); + else if (Type == JOB_RGBA16toBGR8) RGBA16toBGR8(); + else if (Type == JOB_RGBA16toBGRA8) RGBA16toBGRA8(); + else if (Type == JOB_BGR_RESIZE_LINEAR) BGRResizeLinear(); + else if (Type == JOB_BGRA_RESIZE_LINEAR) BGRAResizeLinear(); + else if (Type == JOB_BGR_MIRROR_HORIZONTAL) BGRMirrorHorizontal(); + else if (Type == JOB_BGRA_MIRROR_HORIZONTAL) BGRAMirrorHorizontal(); + } + + void RGBA8toBGR8() + { + const uint32_t *src = (const uint32_t*)BufIn + (RowStart * RGBAInStride); + uint8_t *dst = (uint8_t*)BufOut + (RowStart * Width * 3), *dstEnd = (uint8_t*)BufOut + (RowEnd * Width * 3); + if (RGBAInStride != Width) + { + //Handle a case where the texture pitch does have a gap on the right side + const uint32_t *srcLastRow = (const uint32_t*)BufIn + ((RowEnd - 1) * RGBAInStride); + for (size_t srcStride = RGBAInStride, iMax = Width; src != srcLastRow; src += srcStride) + for (size_t i = 0; i != iMax; i++, dst += 3) + *(uint32_t*)dst = _byteswap_ulong(src[i]) >> 8; + for (size_t i = 0, iMax = Width - 1; i != iMax; i++, dst += 3, src++) + *(uint32_t*)dst = _byteswap_ulong(*src) >> 8; + } + else + { + //The fastest (implemented) path to convert from RGBA to BGR + const uint32_t *srcEnd8 = src + (((RowEnd-RowStart)*Width-1)&~7), *srcEnd1 = src + ((RowEnd-RowStart)*Width-1); + for (; src != srcEnd8; dst += 24, src += 8) + { + *(uint32_t*)(dst ) = _byteswap_ulong(src[0]) >> 8; + *(uint32_t*)(dst + 3) = _byteswap_ulong(src[1]) >> 8; + *(uint32_t*)(dst + 6) = _byteswap_ulong(src[2]) >> 8; + *(uint32_t*)(dst + 9) = _byteswap_ulong(src[3]) >> 8; + *(uint32_t*)(dst + 12) = _byteswap_ulong(src[4]) >> 8; + *(uint32_t*)(dst + 15) = _byteswap_ulong(src[5]) >> 8; + *(uint32_t*)(dst + 18) = _byteswap_ulong(src[6]) >> 8; + *(uint32_t*)(dst + 21) = _byteswap_ulong(src[7]) >> 8; + } + for (; src != srcEnd1; dst += 3, src++) + *(uint32_t*)(dst) = _byteswap_ulong(*src) >> 8; + } + uint32_t FinalPixel = _byteswap_ulong(*src) >> 8; + memcpy(dst, &FinalPixel, 3); + } + + void RGBA8toBGRA8() + { + #define RGBATOBGRA(x) ((x&0xFF00FF00)|((x&0x00FF0000)>>16)|((x&0x000000FF)<<16)) + const uint32_t *src = (const uint32_t*)BufIn + (RowStart * RGBAInStride); + uint32_t *dst = (uint32_t*)BufOut + (RowStart * Width), *dstEnd = (uint32_t*)BufOut + (RowEnd * Width); + if (RGBAInStride != Width) + { + //Handle a case where the texture pitch does have a gap on the right side + const uint32_t *srcEnd = (const uint32_t*)BufIn + ((RowEnd) * RGBAInStride); + for (size_t srcStride = RGBAInStride, iMax = Width; src != srcEnd; src += srcStride) + for (size_t i = 0; i != iMax; i++, dst++) + *dst = RGBATOBGRA(src[i]); + } + else + { + //The fastest (implemented) path to convert from RGBA to BGR + const uint32_t *srcEnd8 = src + (((RowEnd-RowStart)*Width)&~7), *srcEnd1 = src + ((RowEnd-RowStart)*Width); + for (; src != srcEnd8; dst += 8, src += 8) + { + dst[0] = RGBATOBGRA(src[0]); + dst[1] = RGBATOBGRA(src[1]); + dst[2] = RGBATOBGRA(src[2]); + dst[3] = RGBATOBGRA(src[3]); + dst[4] = RGBATOBGRA(src[4]); + dst[5] = RGBATOBGRA(src[5]); + dst[6] = RGBATOBGRA(src[6]); + dst[7] = RGBATOBGRA(src[7]); + } + for (; src != srcEnd1; dst++, src++) + *dst = RGBATOBGRA(*src); + } + #undef RGBATOBGRA + } + + void RGBA16toBGR8() + { + //16 bit color downscaling (HDR (16 bit floats) to BGR) + const uint8_t* ttbl = RGBA16Table; + #define RGBAF16toBGRU8(psrc) ((ttbl[((uint16_t*)(psrc))[0]]<<16) | (ttbl[((uint16_t*)(psrc))[1]]<<8) | ttbl[((uint16_t*)(psrc))[2]]) + const uint64_t *src = (const uint64_t*)BufIn + (RowStart * RGBAInStride); + uint8_t *dst = (uint8_t*)BufOut + (RowStart * Width * 3), *dstEnd = (uint8_t*)BufOut + (RowEnd * Width * 3); + if (RGBAInStride != Width) + { + //Handle a case where the texture pitch does have a gap on the right side + const uint64_t *srcLastRow = (const uint64_t*)BufIn + ((RowEnd - 1) * RGBAInStride); + for (size_t srcStride = RGBAInStride, iMax = Width; src != srcLastRow; src += srcStride) + for (size_t i = 0; i != iMax; i++, dst += 3) + *(uint32_t*)dst = RGBAF16toBGRU8(src + i); + for (size_t i = 0, iMax = Width - 1; i != iMax; i++, dst += 3, src++) + *(uint32_t*)dst = RGBAF16toBGRU8(src); + } + else + { + //The fastest (implemented) path to convert from RGBA to BGR + const uint64_t *srcEnd8 = src + (((RowEnd-RowStart)*Width-1)&~7), *srcEnd1 = src + ((RowEnd-RowStart)*Width-1); + for (; src != srcEnd8; dst += 24, src += 8) + { + *(uint32_t*)(dst ) = RGBAF16toBGRU8(src ); + *(uint32_t*)(dst + 3) = RGBAF16toBGRU8(src + 1); + *(uint32_t*)(dst + 6) = RGBAF16toBGRU8(src + 2); + *(uint32_t*)(dst + 9) = RGBAF16toBGRU8(src + 3); + *(uint32_t*)(dst + 12) = RGBAF16toBGRU8(src + 4); + *(uint32_t*)(dst + 15) = RGBAF16toBGRU8(src + 5); + *(uint32_t*)(dst + 18) = RGBAF16toBGRU8(src + 6); + *(uint32_t*)(dst + 21) = RGBAF16toBGRU8(src + 7); + } + for (; src != srcEnd1; dst += 3, src++) + *(uint32_t*)(dst) = RGBAF16toBGRU8(src); + } + //For the final pixel we can't use 4 byte uint32_t copy so we call memcpy + uint32_t FinalPixel = RGBAF16toBGRU8(src); + memcpy(dst, &FinalPixel, 3); + #undef RGBAF16toBGRU8 + } + + void RGBA16toBGRA8() + { + //16 bit color downscaling (HDR (16 bit floats) to BGRA) + const uint8_t* ttbl = RGBA16Table; + #define RGBAF16toBGRAU8(psrc) ((ttbl[((uint16_t*)(psrc))[3]]<<24) | (ttbl[((uint16_t*)(psrc))[0]]<<16) | (ttbl[((uint16_t*)(psrc))[1]]<<8) | ttbl[((uint16_t*)(psrc))[2]]) + const uint64_t *src = (const uint64_t*)BufIn + (RowStart * RGBAInStride); + uint32_t *dst = (uint32_t*)BufOut + (RowStart * Width), *dstEnd = (uint32_t*)BufOut + (RowEnd * Width); + if (RGBAInStride != Width) + { + //Handle a case where the texture pitch does have a gap on the right side + const uint64_t *srcEnd = (const uint64_t*)BufIn + (RowEnd * RGBAInStride); + for (size_t srcStride = RGBAInStride, iMax = Width; src != srcEnd; src += srcStride) + for (size_t i = 0; i != iMax; i++, dst++) + *dst = RGBAF16toBGRAU8(src + i); + } + else + { + //The fastest (implemented) path to convert from RGBA to BGR + const uint64_t *srcEnd8 = src + (((RowEnd-RowStart)*Width-1)&~7), *srcEnd1 = src + ((RowEnd-RowStart)*Width-1); + for (; src != srcEnd8; dst += 8, src += 8) + { + dst[0] = RGBAF16toBGRAU8(src ); + dst[1] = RGBAF16toBGRAU8(src + 1); + dst[2] = RGBAF16toBGRAU8(src + 2); + dst[3] = RGBAF16toBGRAU8(src + 3); + dst[4] = RGBAF16toBGRAU8(src + 4); + dst[5] = RGBAF16toBGRAU8(src + 5); + dst[6] = RGBAF16toBGRAU8(src + 6); + dst[7] = RGBAF16toBGRAU8(src + 7); + } + for (; src != srcEnd1; dst++, src++) + *dst = RGBAF16toBGRAU8(src); + } + #undef RGBAF16toBGRAU8 + } + + void BGRResizeLinear() + { + const size_t w = Width, h = ResizeToHeight, ResizeFromPitch = ResizeFromWidth * 3; + const double aw = (double)w, ah = (double)h; + const double scale = max(ResizeFromWidth / aw, ResizeFromHeight / ah); + const double ax = (aw - (ResizeFromWidth / scale)) / 2.0; + const double ay = (ah - (ResizeFromHeight / scale)) / 2.0; + const uint8_t *src = (const uint8_t*)BufIn, BlackPixel[3] = {0, 0, 0}; + uint8_t *dst = (uint8_t*)BufOut + (RowStart * Width * 3); + for (size_t y = RowStart, yEnd = RowEnd, isMaxW = ResizeFromWidth, isOffsetMax = ResizeFromHeight * ResizeFromPitch; y != yEnd; y++) + for (size_t x = 0; x != w; x++, dst += 3) + { + const size_t isx = (size_t)((x-ax)*scale), isy = (size_t)((y-ay)*scale); + const size_t isOffset = (isx > isMaxW ? isOffsetMax : isy * ResizeFromPitch + isx * 3); + memcpy(dst, (isOffset >= isOffsetMax ? BlackPixel : src + isOffset), 3); + } + } + + void BGRAResizeLinear() + { + const size_t w = Width, h = ResizeToHeight, fromw = ResizeFromWidth; + const double aw = (double)w, ah = (double)h; + const double scale = max(ResizeFromWidth / aw, ResizeFromHeight / ah); + const double ax = (aw - (ResizeFromWidth / scale)) / 2.0; + const double ay = (ah - (ResizeFromHeight / scale)) / 2.0; + const uint32_t *src = (const uint32_t*)BufIn; + uint32_t *dst = (uint32_t*)BufOut + (RowStart * Width); + for (size_t y = RowStart, yEnd = RowEnd, isMaxW = ResizeFromWidth, isOffsetMax = ResizeFromHeight * fromw; y != yEnd; y++) + for (size_t x = 0; x != w; x++, dst++) + { + const size_t isx = (size_t)((x-ax)*scale), isy = (size_t)((y-ay)*scale); + const size_t isOffset = (isx > isMaxW ? isOffsetMax : isy * fromw + isx); + *dst = (isOffset >= isOffsetMax ? 0 : src[isOffset]); + } + UCASSERT(dst == (uint32_t*)BufOut + (RowEnd * Width)); + } + + void BGRMirrorHorizontal() + { + uint8_t *dst = (uint8_t*)BufOut + (RowStart * Width * 3), *dstEnd = (uint8_t*)BufOut + (RowEnd * Width * 3); + for (size_t dstPitch = Width * 3; dst != dstEnd; dst += dstPitch) + for (uint8_t tmp[3], *dstA = dst, *dstB = dst + dstPitch - 3; dstA < dstB; dstA += 3, dstB -= 3) + memcpy(tmp, dstA, 3), memcpy(dstA, dstB, 3), memcpy(dstB, tmp, 3); + } + + void BGRAMirrorHorizontal() + { + uint32_t *dst = (uint32_t*)BufOut + (RowStart * Width), *dstEnd = (uint32_t*)BufOut + (RowEnd * Width); + for (size_t w = Width; dst != dstEnd; dst += w) + for (uint32_t tmp, *dstA = dst, *dstB = dst + w - 1; dstA < dstB; dstA++, dstB--) + tmp = *dstA, *dstA = *dstB, *dstB = tmp; + } + }; + + struct ProcessWorkers + { + ProcessWorkers() : WorkersRunning(WORKERCOUNT) + { + for (size_t i = 0; i != WORKERCOUNT; i++) Threads[i].Start((sThread::FUNC_t)&ProcessThread, (void*)this); + } + + ~ProcessWorkers() + { + WorkersRunning = 0; + for (size_t i = 0; i != WORKERCOUNT; i++) NewJobSemaphore.Post(); //wake up all threads + for (size_t i = 0; i != WORKERCOUNT; i++) + { + Threads[i].Stop(); + } + } + + void StartNewJob(ProcessJob NewJob) + { + //Notify threads of new work to do + WorkingJobCount = 0; + size_t Num = NewJob.RowEnd; + for (size_t i = 0; i != WORKERCOUNT; i++) + { + NewJob.RowStart = Num * (i ) / (WORKERCOUNT + 1); + NewJob.RowEnd = Num * (i+1) / (WORKERCOUNT + 1); + Jobs[i] = NewJob; + NewJobSemaphore.Post(); + } + + //Do work in the main thread as well + NewJob.RowStart = NewJob.RowEnd; + NewJob.RowEnd = Num; + NewJob.Execute(); + + //Wait for threads to finish working + for (size_t i = 0; i != WORKERCOUNT && JobDoneSemaphore.WaitForPost(); i++) {} + } + + private: + //Wrapper objects for Windows concurrency objects (thread, mutex, semaphore) + struct sThread + { + typedef DWORD(WINAPI* FUNC_t)(LPVOID); + sThread() : h(0) + { + } + sThread(FUNC_t f, void* p = NULL) : h(0) + { + Start(f, p); + } + void Start(FUNC_t f, void* p = NULL) + { + if (h) + this->~sThread(); + h = CreateThread(0, 0, f, p, 0, 0); + } + void Stop() + { + if (h) + { + WaitForSingleObject(h, INFINITE); + CloseHandle(h); + h = 0; + } + } + ~sThread() + { + if (h) + { + WaitForSingleObject(h, INFINITE); + CloseHandle(h); + } + } + private: + HANDLE h; + sThread(const sThread&); + sThread& operator=(const sThread&); + }; + + struct sMutex + { + sMutex() : h(CreateMutexA(0, 0, 0)) {} + ~sMutex() { CloseHandle(h); } + __inline void Lock() + { + WaitForSingleObject(h, INFINITE); + } + __inline void Unlock() + { + ReleaseMutex(h); + } + private: + HANDLE h; + sMutex(const sMutex&); + sMutex& operator=(const sMutex&); + }; + + struct sSemaphore + { + sSemaphore() : h(CreateSemaphoreA(0, 0, 32768, 0)) {} + ~sSemaphore() { CloseHandle(h); } + __inline void Post() + { + ReleaseSemaphore(h, 1, 0); + } + __inline bool WaitForPost() + { + return WaitForSingleObject(h, INFINITE) == WAIT_OBJECT_0; + } + private: + HANDLE h; + sSemaphore(const sSemaphore&); + sSemaphore& operator=(const sSemaphore&); + }; + + enum { WORKERCOUNT = 3 }; + sMutex JobsMutex; + sThread Threads[WORKERCOUNT]; + ProcessJob Jobs[WORKERCOUNT]; + sSemaphore NewJobSemaphore, JobDoneSemaphore; + size_t WorkingJobCount, WorkersRunning; + + static void ProcessThread(ProcessWorkers* mw) + { + while (mw->NewJobSemaphore.WaitForPost() && mw->WorkersRunning) + { + mw->JobsMutex.Lock(); + size_t MyJob = mw->WorkingJobCount++; + mw->JobsMutex.Unlock(); + mw->Jobs[MyJob].Execute(); + mw->JobDoneSemaphore.Post(); + } + } + }; + + struct ProcessState + { + uint8_t* Buf; + int BufWidth, BufHeight, BufBPP; + CCaptureStream* Owner; + }; + + static void ProcessImage(int InWidth, int InHeight, int InStride, SharedImageMemory::EFormat Format, SharedImageMemory::EResizeMode ResizeMode, SharedImageMemory::EMirrorMode MirrorMode, int Timeout, uint8_t* InBuf, ProcessState* State) + { + //Set maximum number of missed frames allowed until we show sending as having stopped + State->Owner->m_llFrameMissMax = (Timeout + SharedImageMemory::RECEIVE_MAX_WAIT - 1) / SharedImageMemory::RECEIVE_MAX_WAIT; + + const bool NeedResize = (InWidth != State->BufWidth || InHeight != State->BufHeight); + if (NeedResize && ResizeMode == SharedImageMemory::RESIZEMODE_DISABLED) + { + //Show color pattern indicating that the requested resolution does not match the resolution provided by Unity + char DisplayString1[128], DisplayString2[128], DisplayString3[128]; + char* DisplayStrings[] = { DisplayString1, DisplayString2, DisplayString3 }; + int DisplayStringLens[] = { + sprintf_s(DisplayString1, sizeof(DisplayString1), "Capture output resolution is %d x %d", State->BufWidth, State->BufHeight), + sprintf_s(DisplayString2, sizeof(DisplayString2), "Unity render resolution is %d x %d", InWidth, InHeight), + sprintf_s(DisplayString3, sizeof(DisplayString3), "please set these to match"), + }; + FillErrorPattern(ErrorDrawModes[EDC_ResolutionMismatch], State, 3, DisplayStrings, DisplayStringLens); + return; + } + + if (NeedResize) + { + //Prepare buffer for image scaling + DWORD UnscaledBufSize = (InWidth * InHeight * State->BufBPP); + if (State->Owner->m_iUnscaledBufSize != UnscaledBufSize) + { + if (State->Owner->m_pUnscaledBuf) free(State->Owner->m_pUnscaledBuf); + State->Owner->m_pUnscaledBuf = (uint8_t*)malloc(UnscaledBufSize); + State->Owner->m_iUnscaledBufSize = UnscaledBufSize; + } + } + + if (Format != SharedImageMemory::FORMAT_UINT8 && (!State->Owner->m_RGBA16Table || State->Owner->m_RGBA16TableFormat != Format)) + { + //Build a 64k table that maps 16 bit float values (either linear SRGB or gamma RGB) to 8 bit color values + const bool SRGB = (Format == SharedImageMemory::FORMAT_FP16_LINEAR); + uint8_t* RGBA16Table = State->Owner->m_RGBA16Table; + if (!RGBA16Table) RGBA16Table = State->Owner->m_RGBA16Table = (uint8_t*)malloc(0xFFFF+1); + for(int i = 0; i <= 0xFFFF; i++) + { + float f; + (i & 0x8000 ? f = 0 : (*(uint32_t*)&f = (i << 13) + 0x38000000)); + if (SRGB) f = (f <= 0.0031308f ? (f * 12.92f) : (powf(f, 1.0f / 2.4f) * 1.055f - 0.055f)); + RGBA16Table[i] = (f < 1.0f ? (uint8_t)(f * 255.9999f) : 255); + } + State->Owner->m_RGBA16TableFormat = Format; + } + + //Multi-threaded conversion of RGBA source to 8-bit BGR format while also eliminating possible row gaps (when stride != width) + ProcessJob Job; + if (State->BufBPP == 4) Job.Type = (Format == SharedImageMemory::FORMAT_UINT8 ? ProcessJob::JOB_RGBA8toBGRA8 : ProcessJob::JOB_RGBA16toBGRA8); + else Job.Type = (Format == SharedImageMemory::FORMAT_UINT8 ? ProcessJob::JOB_RGBA8toBGR8 : ProcessJob::JOB_RGBA16toBGR8 ); + Job.BufIn = InBuf, Job.BufOut = (NeedResize ? State->Owner->m_pUnscaledBuf : State->Buf); + Job.Width = InWidth, Job.RowStart = 0, Job.RowEnd = InHeight, Job.RGBAInStride = InStride; + Job.RGBA16Table = State->Owner->m_RGBA16Table; + State->Owner->m_ProcessWorkers.StartNewJob(Job); + + if (NeedResize) + { + //Multi-threaded image scaling + Job.Type = (State->BufBPP == 4 ? ProcessJob::JOB_BGRA_RESIZE_LINEAR : ProcessJob::JOB_BGR_RESIZE_LINEAR); + Job.BufIn = State->Owner->m_pUnscaledBuf, Job.BufOut = State->Buf; + Job.Width = State->BufWidth, Job.RowStart = 0, Job.RowEnd = State->BufHeight; + Job.ResizeToHeight = State->BufHeight, Job.ResizeFromWidth = InWidth, Job.ResizeFromHeight = InHeight; + State->Owner->m_ProcessWorkers.StartNewJob(Job); + } + + if (MirrorMode == SharedImageMemory::MIRRORMODE_HORIZONTALLY) + { + //Multi-threaded horizontal image flipping + Job.Type = (State->BufBPP == 4 ? ProcessJob::JOB_BGRA_MIRROR_HORIZONTAL : ProcessJob::JOB_BGR_MIRROR_HORIZONTAL); + Job.BufOut = State->Buf; + Job.Width = State->BufWidth, Job.RowStart = 0, Job.RowEnd = State->BufHeight; + State->Owner->m_ProcessWorkers.StartNewJob(Job); + } + } + + static void FillErrorPattern(EErrorDrawMode edm, ProcessState* State, int LineCount = 0, char** LineStrings = NULL, int* LineLengths = NULL, LONGLONG FrameNumber = -1) + { + if (FrameNumber >= 0 && FrameNumber < 5) edm = EDM_BLACK; //show errors as just black during the first 5 frames (when starting) + BYTE *p = State->Buf, *pEnd = State->Buf + (State->BufWidth * State->BufHeight * State->BufBPP), SkipCount = State->BufBPP - 3; + switch (edm) + { + case EDM_GREENKEY: while (p != pEnd) { *(p++) = 0x00; *(p++) = 0xFE; *(p++) = 0x00; p += SkipCount; } break; //Filled with 0x00FE00 (BGR colors) + case EDM_GREENYELLOW: while (p != pEnd) { *(p++) = 0x00; *(p++) = 0xFF; *(p++) = (size_t)p%0xFF; p += SkipCount; } break; //Green/yellow color pattern (BGR colors) + case EDM_BLUEPINK: while (p != pEnd) { *(p++) = 0xFF; *(p++) = 0x00; *(p++) = (size_t)p%0xFF; p += SkipCount; } break; //Blue/pink color pattern (BGR colors) + case EDM_BLACK: ZeroMemory(State->Buf, (State->BufWidth * State->BufHeight * State->BufBPP)); break; //Filled with black + } + + if (LineCount && edm != EDM_BLACK && edm != EDM_GREENKEY && State->BufHeight >= LineCount * 20) + { + void* pTextBuf; + HDC TextDC = CreateCompatibleDC(0); + BITMAPINFO TextBMI = { sizeof(BITMAPINFOHEADER), State->BufWidth, LineCount * 20, 1, 8 * State->BufBPP, 0, LineCount * 20 * State->BufWidth * State->BufBPP }; + TextBMI.bmiHeader.biHeight = LineCount * 20; + HBITMAP TextHBitmap = CreateDIBSection(TextDC, &TextBMI, DIB_RGB_COLORS, &pTextBuf, NULL, 0); + SelectObject(TextDC, TextHBitmap); + SetBkMode(TextDC, TRANSPARENT); + SetTextColor(TextDC, RGB(255, 0, 0)); + for (int i = 0; i < LineCount; i++) TextOutA(TextDC, 10, i * 20, LineStrings[i], LineLengths[i]); + memcpy(State->Buf + ((State->BufHeight - TextBMI.bmiHeader.biHeight) / 2) * State->BufWidth * State->BufBPP, pTextBuf, TextBMI.bmiHeader.biHeight * State->BufWidth * State->BufBPP); + DeleteObject(TextHBitmap); + DeleteDC(TextDC); + } + if (State->BufBPP == 4) + { + BYTE FillAlpha = (edm == EDM_GREENKEY ? 0x0 : (edm == EDM_BLACK ? 0x0 : 0xA0)); + for (p = State->Buf; p != pEnd; p += 4) p[3] = FillAlpha; + } + } + + static void RenderFPSDisplay(ProcessState* State) + { + static LONGLONG MyFPS = 0, MyLastFPSTime = GetTickCount64(), MyLastFPS = 0; + for (MyFPS++; GetTickCount64() - MyLastFPSTime > 1000; MyFPS = 0, MyLastFPSTime += 1000) { MyLastFPS = MyFPS; } + char DisplayString[128]; + int DisplayStringLen = sprintf_s(DisplayString, sizeof(DisplayString), "%d FPS", MyLastFPS); + + void* pTextBuf; + HDC TextDC = CreateCompatibleDC(0); + BITMAPINFO TextBMI = { sizeof(BITMAPINFOHEADER), State->BufWidth, 20, 1, 8 * State->BufBPP, 0, 20 * State->BufWidth * State->BufBPP }; + HBITMAP TextHBitmap = CreateDIBSection(TextDC, &TextBMI, DIB_RGB_COLORS, &pTextBuf, NULL, 0); + SelectObject(TextDC, TextHBitmap); + SetBkMode(TextDC, TRANSPARENT); + SetTextColor(TextDC, RGB(0, 255, 0)); + TextOutA(TextDC, 10, 0, DisplayString, DisplayStringLen); + if (State->BufBPP == 4) for (BYTE *p = (BYTE*)pTextBuf, *pEnd = p + 20 * State->BufWidth * 4; p != pEnd; p += 4) p[3] = 0xFF; + memcpy(State->Buf, pTextBuf, TextBMI.bmiHeader.biHeight * State->BufWidth * State->BufBPP); + DeleteObject(TextHBitmap); + DeleteDC(TextDC); + } + + //IUnknown + STDMETHODIMP QueryInterface(REFIID riid, void **ppv) override + { + if (ppv == NULL) return E_POINTER; + else if (riid == _uuidof(IAMStreamConfig)) { *ppv = (IAMStreamConfig*)this; AddRef(); return S_OK; } + else if (riid == _uuidof(IKsPropertySet)) { *ppv = (IKsPropertySet*)this; AddRef(); return S_OK; } + return CSourceStream::QueryInterface(riid, ppv); + } + + STDMETHODIMP_(ULONG) AddRef() override { return GetOwner()->AddRef(); } + STDMETHODIMP_(ULONG) Release() override { return GetOwner()->Release(); } + + STDMETHODIMP NonDelegatingQueryInterface(REFIID riid, void ** ppv) override + { + if (ppv == NULL) return E_POINTER; + else if (riid == IID_IKsPropertySet) { *ppv = (IKsPropertySet*)this; AddRef(); return S_OK; } + else if (riid == IID_IQualityControl) { *ppv = (IQualityControl*)this; AddRef(); return S_OK; } + else if (riid == IID_IAMStreamConfig) { *ppv = (IAMStreamConfig*)this; AddRef(); return S_OK; } + return CSourceStream::NonDelegatingQueryInterface(riid, ppv); + } + + STDMETHODIMP QuerySupported(REFGUID rguidPropSet, ULONG ulId, PULONG pulTypeSupport) override + { + if (rguidPropSet != AMPROPSETID_Pin) return E_PROP_SET_UNSUPPORTED; + if (ulId != AMPROPERTY_PIN_CATEGORY) return E_PROP_ID_UNSUPPORTED; + if (pulTypeSupport) *pulTypeSupport = KSPROPERTY_SUPPORT_GET; // We support getting this property, but not setting it. + return S_OK; + + //if(rguidPropSet == AMPROPSETID_Pin && ulId == AMPROPERTY_PIN_CATEGORY) { *pulTypeSupport = KSPROPERTY_SUPPORT_GET; return S_OK; } + //return E_NOTIMPL; + } + + STDMETHODIMP Get(REFGUID rguidPropSet, ULONG ulId, LPVOID pInstanceData, ULONG ulInstanceLength, LPVOID pPropertyData, ULONG ulDataLength, PULONG pulBytesReturned) override + { + if (rguidPropSet != AMPROPSETID_Pin) return E_PROP_SET_UNSUPPORTED; + if (ulId != AMPROPERTY_PIN_CATEGORY) return E_PROP_ID_UNSUPPORTED; + if (pPropertyData == NULL && pulBytesReturned == NULL) return E_POINTER; + + if (pulBytesReturned) *pulBytesReturned = sizeof(GUID); + if (pPropertyData == NULL) return S_OK; // Caller just wants to know the size. + if (ulDataLength < sizeof(GUID)) return E_UNEXPECTED; // The buffer is too small. + + *(GUID *)pPropertyData = PIN_CATEGORY_CAPTURE; + return S_OK; + + //if(rguidPropSet == AMPROPSETID_Pin && ulId == AMPROPERTY_PIN_CATEGORY) + //{ + // if (pPropertyData == NULL) return E_POINTER; + // if (ulDataLength != sizeof(GUID)) return E_INVALIDARG; + // memcpy(pPropertyData, &PIN_CATEGORY_CAPTURE, sizeof(GUID)); + // *pulBytesReturned = sizeof(GUID); + // return S_OK; + //} + //return E_NOTIMPL; + } + + STDMETHODIMP Set(REFGUID rguidPropSet, ULONG ulId, LPVOID pInstanceData, ULONG ulInstanceLength, LPVOID pPropertyData, ULONG ulDataLength) override { return E_NOTIMPL; } + STDMETHODIMP Notify(IBaseFilter *pSelf, Quality q) override { return S_OK; } + STDMETHODIMP SetSink(IQualityControl *piqc) override { return S_OK; } + + HRESULT DecideBufferSize(IMemAllocator * pAlloc, ALLOCATOR_PROPERTIES * pRequest) override + { + if (pAlloc == NULL || pRequest == NULL) DebugLog("[DecideBufferSize] E_POINTER\n"); + if (pAlloc == NULL || pRequest == NULL) return E_POINTER; + CAutoLock cAutoLock(m_pFilter->pStateLock()); + HRESULT hr = NOERROR; + VIDEOINFO *pvi = (VIDEOINFO*)m_mt.Format(); + pRequest->cBuffers = 1; + + DebugLog("[DecideBufferSize] Request Size: %d - Have Size: %d\n", (int)pvi->bmiHeader.biSizeImage, (int)pRequest->cbBuffer); + if (pvi->bmiHeader.biSizeImage > (DWORD)pRequest->cbBuffer) + pRequest->cbBuffer = pvi->bmiHeader.biSizeImage; + + ALLOCATOR_PROPERTIES actual; + hr = pAlloc->SetProperties(pRequest, &actual); + if (FAILED(hr)) DebugLog("[DecideBufferSize] E_SOMETHING\n"); + if (FAILED(hr)) return hr; + + DebugLog("[DecideBufferSize] Request Size: %d - Actual Size: %d\n", (int)pvi->bmiHeader.biSizeImage, (int)actual.cbBuffer); + return (actual.cbBuffer < pRequest->cbBuffer ? E_FAIL : S_OK); + } + + STDMETHODIMP SetFormat(AM_MEDIA_TYPE *pmt) override + { + if (pmt == NULL) DebugLog("[SetFormat] E_POINTER\n"); + if (pmt == NULL) return E_POINTER; + + VIDEOINFO* pvi = (VIDEOINFO*)pmt->pbFormat; + if (pvi == NULL) DebugLog("[SetFormat] E_UNEXPECTED (pvi is null)\n"); + if (pvi == NULL) return E_UNEXPECTED; + + bool HasStrideBytes = (DIBSIZE(pvi->bmiHeader) != pvi->bmiHeader.biWidth * pvi->bmiHeader.biHeight * pvi->bmiHeader.biBitCount / 8); + if (HasStrideBytes) DebugLog("[SetFormat] E_FAIL (has stride bytes)\n"); + if (HasStrideBytes) return E_FAIL; + + DebugLog("[SetFormat] WIDTH: %d - HEIGHT: %d - BITS: %d - TPS: %d - SIZE: %d - SIZE CALC: %d\n", (int)pvi->bmiHeader.biWidth, (int)pvi->bmiHeader.biHeight, (int)pvi->bmiHeader.biBitCount, (int)pvi->AvgTimePerFrame, + (int)pvi->bmiHeader.biSizeImage, (int)DIBSIZE(pvi->bmiHeader)); + m_avgTimePerFrame = pvi->AvgTimePerFrame; + m_mt = *pmt; + ((VIDEOINFO*)m_mt.pbFormat)->bmiHeader.biSizeImage = DIBSIZE(((VIDEOINFO*)m_mt.pbFormat)->bmiHeader); + return S_OK; + } + + STDMETHODIMP GetFormat(AM_MEDIA_TYPE **ppmt) override + { + if (ppmt == NULL) DebugLog("[GetFormat] E_POINTER\n"); + if (ppmt == NULL) return E_POINTER; + DebugLog("[GetFormat] RETURNING WIDTH: %d - HEIGHT: %d - BITS: %d - TPS: %d - SIZEIMAGE: %d - SIZECALC: %d\n", (int)((VIDEOINFO*)m_mt.Format())->bmiHeader.biWidth, (int)((VIDEOINFO*)m_mt.Format())->bmiHeader.biHeight, (int)((VIDEOINFO*)m_mt.Format())->bmiHeader.biBitCount, (int)((VIDEOINFO*)m_mt.Format())->AvgTimePerFrame, (int)((VIDEOINFO*)m_mt.Format())->bmiHeader.biSizeImage, (int)DIBSIZE(((VIDEOINFO*)m_mt.Format())->bmiHeader)); + *ppmt = CreateMediaType(&m_mt); + return S_OK; + } + + STDMETHODIMP GetNumberOfCapabilities(int *piCount, int *piSize) override + { + if (piCount == NULL || piSize == NULL) DebugLog("[GetNumberOfCapabilities] E_POINTER\n"); + if (piCount == NULL || piSize == NULL) return E_POINTER; + *piCount = (sizeof(_media)/sizeof(_media[0])*2); //RGB and RGBA variations + *piSize = sizeof(VIDEO_STREAM_CONFIG_CAPS); + DebugLog("[GetNumberOfCapabilities] Returning Count: %d - Size: %d\n", *piCount, *piSize); + return S_OK; + } + + STDMETHODIMP GetStreamCaps(int iIndex, AM_MEDIA_TYPE **ppmt, BYTE *pSCC) override + { + if (ppmt == NULL || pSCC == NULL) DebugLog("[GetStreamCaps] E_POINTER\n"); + if (ppmt == NULL || pSCC == NULL) return E_POINTER; + + CMediaType mt; + HRESULT hr = GetMediaType(iIndex, &mt); + if (FAILED(hr)) return hr; + VIDEOINFO *pvi = (VIDEOINFO*)mt.Format(); + + *ppmt = CreateMediaType(&mt); + + VIDEO_STREAM_CONFIG_CAPS* pCaps = (VIDEO_STREAM_CONFIG_CAPS*)pSCC; + ZeroMemory(pCaps, sizeof(VIDEO_STREAM_CONFIG_CAPS)); + + pCaps->guid = FORMAT_VideoInfo; + pCaps->VideoStandard = 0; + pCaps->CropAlignX = 1; + pCaps->CropAlignY = 1; + pCaps->OutputGranularityX = 1; + pCaps->OutputGranularityY = 1; + pCaps->StretchTapsX = 2; + pCaps->StretchTapsY = 2; + pCaps->ShrinkTapsX = 2; + pCaps->ShrinkTapsY = 2; + pCaps->InputSize.cx = pvi->bmiHeader.biWidth; + pCaps->InputSize.cy = pvi->bmiHeader.biHeight; + pCaps->MinCroppingSize.cx = 1; + pCaps->MinCroppingSize.cy = 1; + pCaps->MaxCroppingSize.cx = pvi->bmiHeader.biWidth; + pCaps->MaxCroppingSize.cy = pvi->bmiHeader.biHeight; + pCaps->CropGranularityX = 1; + pCaps->CropGranularityY = 1; + pCaps->MinOutputSize.cx = 4; + pCaps->MinOutputSize.cy = 4; + pCaps->MaxOutputSize.cx = pvi->bmiHeader.biWidth; + pCaps->MaxOutputSize.cy = pvi->bmiHeader.biHeight; + pCaps->MinFrameInterval = 10000000 / 120; + pCaps->MaxFrameInterval = 10000000 / 30; + pCaps->MinBitsPerSecond = pCaps->MinOutputSize.cx * pCaps->MinOutputSize.cy * pvi->bmiHeader.biBitCount * 30; + pCaps->MaxBitsPerSecond = pCaps->MaxOutputSize.cx * pCaps->MaxOutputSize.cy * pvi->bmiHeader.biBitCount * 120; + DebugLog("[GetStreamCaps] Index: %d - MINWIDTH: %d - MINHEIGHT: %d - MAXWIDTH: %d - MAXHEIGHT: %d - BITS: %d - TPS: %d - SIZEIMAGE: %d - SIZECALC: %d\n", iIndex, (int)pCaps->MinOutputSize.cx, (int)pCaps->MinOutputSize.cy, (int)pCaps->MaxOutputSize.cx, (int)pCaps->MaxOutputSize.cy, (int)pvi->bmiHeader.biBitCount, (int)pvi->AvgTimePerFrame, (int)pvi->bmiHeader.biSizeImage, (int)DIBSIZE(pvi->bmiHeader)); + return S_OK; + } + + HRESULT SetMediaType(const CMediaType *pmt) override + { + VIDEOINFOHEADER* pvi = (VIDEOINFOHEADER*)(pmt->Format()); + DebugLog("[SetMediaType] [ASKD] WIDTH: %d - HEIGHT: %d - BITS: %d - TPS: %d - SIZEIMAGE: %d - SIZECALC: %d\n", (int)pvi->bmiHeader.biWidth, (int)pvi->bmiHeader.biHeight, (int)pvi->bmiHeader.biBitCount, (int)pvi->AvgTimePerFrame, (int)pvi->bmiHeader.biSizeImage, (int)DIBSIZE(pvi->bmiHeader)); + DebugLog("[SetMediaType] [HAVE] WIDTH: %d - HEIGHT: %d - BITS: %d - TPS: %d - SIZEIMAGE: %d - SIZECALC: %d\n", (int)((VIDEOINFO*)m_mt.Format())->bmiHeader.biWidth, (int)((VIDEOINFO*)m_mt.Format())->bmiHeader.biHeight, (int)((VIDEOINFO*)m_mt.Format())->bmiHeader.biBitCount, (int)((VIDEOINFO*)m_mt.Format())->AvgTimePerFrame, (int)((VIDEOINFO*)m_mt.Format())->bmiHeader.biSizeImage, (int)DIBSIZE(((VIDEOINFO*)m_mt.Format())->bmiHeader)); + HRESULT hr = CSourceStream::SetMediaType(pmt); + return hr; + } + + HRESULT CheckMediaType(const CMediaType *pMediaType) override + { + CAutoLock lock(m_pFilter->pStateLock()); + VIDEOINFOHEADER *pvi = (VIDEOINFOHEADER *)(pMediaType->Format()); + if (!pvi) DebugLog("[CheckMediaType] WANT VIDEO INFO NULL\n"); + else DebugLog("[CheckMediaType] [WANT] WIDTH: %d - HEIGHT: %d - BITS: %d - TPS: %d - SIZEIMAGE: %d - SIZECALC: %d - CBFORMAT: %d\n", (int)pvi->bmiHeader.biWidth, (int)pvi->bmiHeader.biHeight, (int)pvi->bmiHeader.biBitCount, (int)pvi->AvgTimePerFrame, (int)pvi->bmiHeader.biSizeImage, (int)DIBSIZE(pvi->bmiHeader), (int)pMediaType->cbFormat); + DebugLog("[CheckMediaType] [HAVE] WIDTH: %d - HEIGHT: %d - BITS: %d - TPS: %d - SIZEIMAGE: %d - SIZECALC: %d - CBFORMAT: %d\n", (int)((VIDEOINFO*)m_mt.Format())->bmiHeader.biWidth, (int)((VIDEOINFO*)m_mt.Format())->bmiHeader.biHeight, (int)((VIDEOINFO*)m_mt.Format())->bmiHeader.biBitCount, (int)((VIDEOINFO*)m_mt.Format())->AvgTimePerFrame, (int)((VIDEOINFO*)m_mt.Format())->bmiHeader.biSizeImage, (int)DIBSIZE(((VIDEOINFO*)m_mt.Format())->bmiHeader), (int)m_mt.cbFormat); + DebugLog("[CheckMediaType] [RETURNING] %s\n", (*pMediaType != m_mt ? "E_INVALIDARG" : "S_OK")); + return (*pMediaType != m_mt ? E_INVALIDARG : S_OK); + } + + HRESULT GetMediaType(int iPos, CMediaType *pMediaType) override + { + CheckPointer(pMediaType, E_POINTER); + if (iPos < 0) return E_INVALIDARG; + if (iPos >= (sizeof(_media)/sizeof(_media[0])*2)) return VFW_S_NO_MORE_ITEMS; + CAutoLock cAutoLock(m_pFilter->pStateLock()); + + int iMedia = iPos%(sizeof(_media)/sizeof(_media[0])); + UCASSERT(_media[iMedia].width * _media[iMedia].height * 4 * sizeof(short) <= MAX_SHARED_IMAGE_SIZE); + VIDEOINFO *pvi = (VIDEOINFO *)pMediaType->AllocFormatBuffer(sizeof(VIDEOINFO)); + ZeroMemory(pvi, sizeof(VIDEOINFO)); + pvi->AvgTimePerFrame = m_avgTimePerFrame; + BITMAPINFOHEADER *pBmi = &(pvi->bmiHeader); + pBmi->biSize = sizeof(BITMAPINFOHEADER); + pBmi->biWidth = (_media[iMedia].width ? _media[iMedia].width : ((VIDEOINFO*)m_mt.pbFormat)->bmiHeader.biWidth ); + pBmi->biHeight = (_media[iMedia].height ? _media[iMedia].height : ((VIDEOINFO*)m_mt.pbFormat)->bmiHeader.biHeight); + pBmi->biPlanes = 1; + pBmi->biBitCount = (iPos >= (sizeof(_media)/sizeof(_media[0])) ? 32 : 24); + pBmi->biCompression = BI_RGB; + pvi->bmiHeader.biSizeImage = DIBSIZE(pvi->bmiHeader); + + //DebugLog("[GetMediaType] iPos: %d - WIDTH: %d - HEIGHT: %d - BITS: %d - TPS: %d\n", iPos, (int)pvi->bmiHeader.biWidth, (int)pvi->bmiHeader.biHeight, (int)pvi->bmiHeader.biBitCount, (int)pvi->AvgTimePerFrame); + + pMediaType->SetType(&MEDIATYPE_Video); + pMediaType->SetFormatType(&FORMAT_VideoInfo); + pMediaType->SetSubtype(&(pBmi->biBitCount == 32 ? MEDIASUBTYPE_ARGB32 : MEDIASUBTYPE_RGB24)); + pMediaType->SetSampleSize(pvi->bmiHeader.biSizeImage); + pMediaType->SetTemporalCompression(FALSE); + return S_OK; + } + + HRESULT OnThreadStartPlay() override + { + DebugLog("[OnThreadStartPlay] OnThreadStartPlay\n"); + m_llFrame = m_llFrameMissCount = 0; + m_llFrameMissMax = 5; + return CSourceStream::OnThreadStartPlay(); + } + + CMediaType m_mt; + LONGLONG m_llFrame, m_llFrameMissCount, m_llFrameMissMax; + REFERENCE_TIME m_prevStartTime; + REFERENCE_TIME m_avgTimePerFrame; + SharedImageMemory* m_pReceiver; + ProcessWorkers m_ProcessWorkers; + DWORD m_iUnscaledBufSize; + uint8_t *m_pUnscaledBuf, *m_RGBA16Table; + SharedImageMemory::EFormat m_RGBA16TableFormat; + + //IAMStreamControl + HRESULT STDMETHODCALLTYPE StartAt(const REFERENCE_TIME *ptStart, DWORD dwCookie) override { return NOERROR; } + HRESULT STDMETHODCALLTYPE StopAt(const REFERENCE_TIME *ptStop, BOOL bSendExtra, DWORD dwCookie) override { return NOERROR; } + HRESULT STDMETHODCALLTYPE GetInfo(AM_STREAM_INFO *pInfo) override { return NOERROR; } + + // IAMPushSource + HRESULT STDMETHODCALLTYPE GetLatency(REFERENCE_TIME *prtLatency) override { return NOERROR; } + HRESULT STDMETHODCALLTYPE GetPushSourceFlags(ULONG *pFlags) override { *pFlags = AM_PUSHSOURCECAPS_INTERNAL_RM; return NOERROR; } + HRESULT STDMETHODCALLTYPE SetPushSourceFlags(ULONG Flags) override { return E_NOTIMPL; } + HRESULT STDMETHODCALLTYPE SetStreamOffset(REFERENCE_TIME rtOffset) override { return NOERROR; } + HRESULT STDMETHODCALLTYPE GetStreamOffset(REFERENCE_TIME *prtOffset) override { *prtOffset = 0; return NOERROR; } + HRESULT STDMETHODCALLTYPE GetMaxStreamOffset(REFERENCE_TIME *prtMaxOffset) override { *prtMaxOffset = 0; return NOERROR; } + HRESULT STDMETHODCALLTYPE SetMaxStreamOffset(REFERENCE_TIME rtMaxOffset) override { return NOERROR; } +}; + +class CCaptureProperties : public CBasePropertyPage +{ +public: + static CUnknown * WINAPI CreateInstance(LPUNKNOWN lpunk, HRESULT *phr) + { + CUnknown *punk = new CCaptureProperties(lpunk, phr); + *phr = (punk ? S_OK : E_OUTOFMEMORY); + return punk; + } + +private: + CCaptureProperties(LPUNKNOWN lpunk, HRESULT *phr) : CBasePropertyPage("", lpunk, -1, -1) { } + + STDMETHODIMP Activate(HWND hwndParent, LPCRECT prect, BOOL fModal) + { + struct MyData + { + #pragma pack(4) + DLGTEMPLATE Header; + #pragma pack(2) + WORD NoMenu, StdClass; wchar_t Title[1]; // 0 - no menu | 0 - standard dialog class | No title + #pragma pack(4) + struct Item + { + #pragma pack(4) + DLGITEMTEMPLATE Header; + #pragma pack(2) + WORD FFFF, ClassID; wchar_t Text[2]; WORD NoData; + #pragma pack(4) + } Items[8]; + #pragma pack(4) + } md = { + { WS_CHILD | WS_VISIBLE | DS_CENTER, NULL, sizeof(md.Items)/sizeof(MyData::Item) }, 0, 0, L"", { + { { WS_VISIBLE | WS_CHILD | SS_LEFT, NULL , 5, 18, 80, 10, 1000 }, 0xFFFF, 0x0082, L"-" }, //Label + { { WS_VISIBLE | WS_CHILD | WS_TABSTOP | CBS_DROPDOWNLIST, NULL , 90, 17, 150, 100, 1001 }, 0xFFFF, 0x0085, L"-" }, //Combo Box + { { WS_VISIBLE | WS_CHILD | SS_LEFT, NULL , 5, 36, 80, 10, 1002 }, 0xFFFF, 0x0082, L"-" }, //Label + { { WS_VISIBLE | WS_CHILD | WS_TABSTOP | CBS_DROPDOWNLIST, NULL , 90, 35, 150, 100, 1003 }, 0xFFFF, 0x0085, L"-" }, //Combo Box + { { WS_VISIBLE | WS_CHILD | SS_LEFT, NULL , 5, 54, 80, 10, 1004 }, 0xFFFF, 0x0082, L"-" }, //Label + { { WS_VISIBLE | WS_CHILD | WS_TABSTOP | CBS_DROPDOWNLIST, NULL , 90, 53, 150, 100, 1005 }, 0xFFFF, 0x0085, L"-" }, //Combo Box + { { WS_VISIBLE | WS_CHILD | SS_LEFT, NULL , 5, 72, 80, 10, 1006 }, 0xFFFF, 0x0082, L"-" }, //Label + { { WS_VISIBLE | WS_CHILD | WS_TABSTOP | BS_CHECKBOX, NULL , 90, 71, 150, 10, 1007 }, 0xFFFF, 0x0080, L"-" }, //Check Box + }}; + + HWND hwnd = CreateDialogIndirectParamW(NULL, &md.Header, hwndParent, &MyDialogProc, (LPARAM)this); + SetDlgItemTextW(hwnd, 1000, L"Resolution mismatch:"); + SetDlgItemTextW(hwnd, 1002, L"Unity never started:"); + SetDlgItemTextW(hwnd, 1004, L"Unity sending stopped:"); + SetDlgItemTextW(hwnd, 1006, L"Display FPS:"); + SetDlgItemTextW(hwnd, 1007, L"Show capture frame rate"); + for (int i = 0; i < 3; i++) + { + HWND hWndComboBox = GetDlgItem(hwnd, 1001 + i*2); + for (int j = 0; j < sizeof(ErrorDrawModeNames)/sizeof(ErrorDrawModeNames[0]); j++) + SendMessageW(hWndComboBox, (UINT)CB_ADDSTRING, (WPARAM)0, (LPARAM)ErrorDrawModeNames[j]); + SendMessageA(hWndComboBox, CB_SETCURSEL, (WPARAM)ErrorDrawModes[i], (LPARAM)0); + } + SendMessage(GetDlgItem(hwnd, 1007), BM_SETCHECK, (OutputFrameRate ? BST_CHECKED : BST_UNCHECKED), 0); + + SetWindowPos(hwnd, NULL, prect->left, prect->top, prect->right-prect->left, prect->bottom-prect->top, 0); //show in tab page + return S_OK; + } + + static INT_PTR CALLBACK MyDialogProc(HWND hwnd, UINT uMsg, WPARAM wParam, LPARAM lParam) + { + if (uMsg == WM_INITDIALOG) return TRUE; + if (uMsg == WM_COMMAND) + { + //DebugLog("[DIALOG] WM_COMMAND - ItemID: %d - SubCommand: %d - Value: %d\n", (int)LOWORD(wParam), (int)HIWORD(wParam), (int)lParam); + int ItemID = LOWORD(wParam), SubCommand = HIWORD(wParam); + HWND hWndItem = GetDlgItem(hwnd, ItemID); + int SelectionIndex = (int)SendMessageA(hWndItem, CB_GETCURSEL, 0, 0); + if (ItemID == 1001 && SubCommand == 1) ErrorDrawModes[EDC_ResolutionMismatch] = (EErrorDrawMode)SelectionIndex; + if (ItemID == 1003 && SubCommand == 1) ErrorDrawModes[EDC_UnityNeverStarted] = (EErrorDrawMode)SelectionIndex; + if (ItemID == 1005 && SubCommand == 1) ErrorDrawModes[EDC_UnitySendingStopped] = (EErrorDrawMode)SelectionIndex; + if (ItemID == 1007) SendMessage(hWndItem, BM_SETCHECK, ((OutputFrameRate ^= 1) ? BST_CHECKED : BST_UNCHECKED), 0); + return TRUE; + } + return FALSE; + } + + STDMETHODIMP GetPageInfo(__out LPPROPPAGEINFO pPageInfo) + { + pPageInfo->pszTitle = (WCHAR*)CoTaskMemAlloc(sizeof(CaptureSourceName)); + memcpy(pPageInfo->pszTitle, CaptureSourceName, sizeof(CaptureSourceName)); + pPageInfo->size.cx = 490; + pPageInfo->size.cy = 200; + pPageInfo->pszDocString = NULL; + pPageInfo->pszHelpFile = NULL; + pPageInfo->dwHelpContext= 0; + return NOERROR; + } +}; + +class CCaptureSource : CSource, IQualityControl, ICamSource, ISpecifyPropertyPages +{ +public: + static CUnknown * CreateInstance(LPUNKNOWN lpunk, HRESULT *phr, int32_t CapNum) + { + UCASSERT(phr); + *phr = S_OK; + + CCaptureSource *pSource = new CCaptureSource(lpunk, phr); + if (FAILED(*phr) || !pSource) + { + if (!pSource) *phr = E_OUTOFMEMORY; + delete pSource; + return NULL; + } + + CCaptureStream* pStream = new CCaptureStream(pSource, phr, CapNum); + if (FAILED(*phr) || !pStream) + { + if (!pStream) *phr = E_OUTOFMEMORY; + delete pStream; + delete pSource; + return NULL; + } + + return pSource; + } + +private: + DECLARE_IUNKNOWN; + + CCaptureSource(LPUNKNOWN lpunk, HRESULT* phr) : CSource("Source", lpunk, CLSID_UnityCaptureService, phr) { } + + //CSource + STDMETHODIMP NonDelegatingQueryInterface(REFIID riid, void ** ppv) override + { + if (ppv == NULL) return E_POINTER; + if (riid == IID_IQualityControl ) { *ppv = (IQualityControl*)this; AddRef(); return S_OK; } + else if (riid == IID_ICamSource ) { *ppv = (ICamSource*)this; AddRef(); return S_OK; } + else if (riid == IID_ISpecifyPropertyPages) { *ppv = (ISpecifyPropertyPages*)this; AddRef(); return S_OK; } // + return CSource::NonDelegatingQueryInterface(riid, ppv); + } + + //IQualityControl + STDMETHODIMP Notify(IBaseFilter *pSelf, Quality q) override { return S_OK; } + STDMETHODIMP SetSink(IQualityControl *piqc) override { return S_OK; } + + //ISpecifyPropertyPages + STDMETHODIMP GetPages(CAUUID * pPages) override + { + CheckPointer(pPages,E_POINTER); + pPages->cElems = 1; + pPages->pElems = (GUID *) CoTaskMemAlloc(sizeof(GUID)); + if (pPages->pElems == NULL) return E_OUTOFMEMORY; + *(pPages->pElems) = CLSID_UnityCaptureProperties; + return NOERROR; + } +}; + +static const AMOVIESETUP_MEDIATYPE sudMediaTypesCaptureSourceOut = { &MEDIATYPE_Video, &MEDIASUBTYPE_NULL }; +static const AMOVIESETUP_PIN sudCaptureSourceOut = { + L"Output", // Pin string name + FALSE, // Is it rendered + TRUE, // Is it an output + FALSE, // Can we have none + FALSE, // Can we have many + &CLSID_NULL, // Connects to filter + NULL, // Connects to pin + 1, // Number of types + &sudMediaTypesCaptureSourceOut // Pin Media types +}; + +struct WStringHolder { wchar_t str[256]; }; +__inline static WStringHolder GetCaptureSourceNameNum(const wchar_t* pCaptureSourceName, int i) +{ + WStringHolder res; + StringCchPrintfW(res.str, sizeof(res.str)/sizeof(*res.str), (i == 0 ? L"%s" : L"%s #%d"), pCaptureSourceName, i + 1); + return res; +} + +__inline static GUID GetCLSIDUnityCaptureServiceNum(int i) +{ + GUID NumCLSID = CLSID_UnityCaptureService; + if (i != 0) NumCLSID.Data4[7] += 1 + i; + return NumCLSID; +} + +extern "C" int CustomGetFactoryType(const IID &rClsID) +{ + if (IsEqualCLSID(rClsID, CLSID_UnityCaptureProperties)) return 1; + if (memcmp(&rClsID, &CLSID_UnityCaptureService, sizeof(GUID) - 1)) return 0; + unsigned char LastByteOffset = (rClsID.Data4[7] - CLSID_UnityCaptureService.Data4[7]); + return 2 + (LastByteOffset == 0 ? 0 : LastByteOffset - 1); +} + +CUnknown *CustomCreateInstance(int FactoryType, LPUNKNOWN pUnkOuter, HRESULT* hr) +{ + if (FactoryType == 1) return CCaptureProperties::CreateInstance(pUnkOuter, hr); + if (FactoryType >= 2) return CCaptureSource::CreateInstance(pUnkOuter, hr, FactoryType - 2); + return NULL; +} + +// Stack Overflow - "Fake" DirectShow video capture device +// http://stackoverflow.com/questions/1376734/fake-directshow-video-capture-device +STDAPI AMovieSetupRegisterServer(CLSID clsServer, LPCWSTR szDescription, LPCWSTR szFileName, LPCWSTR szThreadingModel = L"Both", LPCWSTR szServerType = L"InprocServer32"); +STDAPI AMovieSetupUnregisterServer(CLSID clsServer); +static HRESULT RegisterFilters(BOOL bRegister) +{ + UCASSERT(g_hInst != 0); + WCHAR achFileName[MAX_PATH]; + if (!GetModuleFileNameW(g_hInst, achFileName, sizeof(achFileName))) return AmHresultFromWin32(GetLastError()); + HRESULT hr = CoInitialize(0); + + int MaxCapNum = (bRegister ? 1 : SharedImageMemory::MAX_CAPNUM); + const wchar_t* pCaptureSourceName = CaptureSourceName; + if (SUCCEEDED(hr) && bRegister) + { + char* CapNumParam = strstr(GetCommandLineA(), "/i:UnityCaptureDevices="); + if (CapNumParam) MaxCapNum = atoi(CapNumParam + sizeof("/i:UnityCaptureDevices=") - 1); + + const wchar_t* CapNameParam = wcsstr(GetCommandLineW(), L"/i:UnityCaptureName="); + if (CapNameParam) + { + //Parse custom filter names from /i:UnityCaptureName=NAME or "/i:UnityCaptureName=NAME NAME" or /i:UnityCaptureName="NAME NAME" + const wchar_t* CapNameStart = CapNameParam + sizeof("/i:UnityCaptureName=") - 1; + if (CapNameStart[0] == L'"') CapNameStart++; + const wchar_t* CapNameEnd = wcsstr(CapNameStart, (CapNameParam[-1] == L'"' || CapNameStart[-1] == L'"' ? L"\"" : L" ")); + if (!CapNameEnd) CapNameEnd = CapNameStart + wcslen(CapNameStart); + size_t CapNameLen = CapNameEnd - CapNameStart; + if (CapNameLen > 0 && CapNameLen < 200) + { + //Allocate memory to hold the name string (this is never freed until regsvr32 ends, which is soon after this function anyway) + wchar_t* CustomCaptureSourceName = (wchar_t*)malloc(sizeof(wchar_t) * (CapNameLen + 1)); + memcpy(CustomCaptureSourceName, CapNameStart, sizeof(wchar_t) * CapNameLen); + CustomCaptureSourceName[CapNameLen] = L'\0'; + pCaptureSourceName = CustomCaptureSourceName; + } + } + + if (MaxCapNum < 1) MaxCapNum = 1; + if (MaxCapNum > SharedImageMemory::MAX_CAPNUM) MaxCapNum = SharedImageMemory::MAX_CAPNUM; + + for (int i = 0; SUCCEEDED(hr) && i != MaxCapNum; i++) + hr = AMovieSetupRegisterServer(GetCLSIDUnityCaptureServiceNum(i), GetCaptureSourceNameNum(pCaptureSourceName, i).str, achFileName, L"Both", L"InprocServer32"); + if (SUCCEEDED(hr)) hr = AMovieSetupRegisterServer(CLSID_UnityCaptureProperties, CaptureSourceName L" Configuration", achFileName, L"Both", L"InprocServer32"); + if (FAILED(hr)) MessageBoxA(0, "AMovieSetupRegisterServer failed", "RegisterFilters setup", NULL); + } + + if (SUCCEEDED(hr)) + { + IFilterMapper2 *fm = NULL; + hr = CoCreateInstance(CLSID_FilterMapper2, NULL, CLSCTX_INPROC_SERVER, IID_IFilterMapper2, (void **)&fm); + + if (SUCCEEDED(hr)) + { + if (bRegister) + { + REGFILTER2 rf2; + rf2.dwVersion = 1; + rf2.dwMerit = MERIT_DO_NOT_USE; + rf2.cPins = 1; + rf2.rgPins = &sudCaptureSourceOut; + for (int i = 0; SUCCEEDED(hr) && i != MaxCapNum; i++) + { + hr = fm->RegisterFilter(GetCLSIDUnityCaptureServiceNum(i), GetCaptureSourceNameNum(pCaptureSourceName, i).str, 0, &CLSID_VideoInputDeviceCategory, NULL, &rf2); + + //This is needed for Unity and Skype to access the virtual camera + //Thanks to: https://social.msdn.microsoft.com/Forums/windowsdesktop/en-US/cd2b9d2d-b961-442d-8946-fdc038fed530/where-to-specify-device-id-in-the-filter?forum=windowsdirectshowdevelopment + LPOLESTR CLSID_Category_Str, CLSID_Filter_Str; WCHAR strKey[256]; HKEY hKey; + StringFromCLSID(CLSID_VideoInputDeviceCategory, &CLSID_Category_Str); + StringFromCLSID(GetCLSIDUnityCaptureServiceNum(i), &CLSID_Filter_Str); + StringCchPrintfW(strKey, 256, L"SOFTWARE\\Classes\\CLSID\\%s\\Instance\\%s", CLSID_Category_Str, CLSID_Filter_Str); + RegOpenKeyExW(HKEY_LOCAL_MACHINE, strKey, 0, KEY_ALL_ACCESS, &hKey); + RegSetValueExA(hKey, "DevicePath", 0, REG_SZ, (LPBYTE)"foo:bar", (DWORD)sizeof("foo:bar")); + RegCloseKey(hKey); + } + if (FAILED(hr)) MessageBoxA(0, "Service RegisterFilter of IFilterMapper2 failed", "RegisterFilters setup", NULL); + } + else + { + for (int i = 0; SUCCEEDED(hr) && i != MaxCapNum; i++) + hr = fm->UnregisterFilter(&CLSID_VideoInputDeviceCategory, 0, GetCLSIDUnityCaptureServiceNum(i)); + if (FAILED(hr)) MessageBoxA(0, "Service UnregisterFilter of IFilterMapper2 failed", "RegisterFilters setup", NULL); + } + } + + if (fm) fm->Release(); + } + + if (SUCCEEDED(hr) && !bRegister) + { + for (int i = 0; SUCCEEDED(hr) && i != MaxCapNum; i++) + hr = AMovieSetupUnregisterServer(GetCLSIDUnityCaptureServiceNum(i)); + if (SUCCEEDED(hr)) hr = AMovieSetupUnregisterServer(CLSID_UnityCaptureProperties); + if (FAILED(hr)) MessageBoxA(0, "AMovieSetupUnregisterServer failed", "RegisterFilters setup", NULL); + } + + CoFreeUnusedLibraries(); + CoUninitialize(); + return hr; +} + +STDAPI DllRegisterServer() +{ + return RegisterFilters(TRUE); +} + +STDAPI DllInstall(BOOL bInstall, PCWSTR pszCmdLine) +{ + return S_OK; +} + +STDAPI DllUnregisterServer() +{ + return RegisterFilters(FALSE); +} + +extern "C" BOOL WINAPI DllEntryPoint(HINSTANCE, ULONG, LPVOID); +BOOL APIENTRY DllMain( HMODULE hModule, DWORD ul_reason_for_call, LPVOID lpReserved) +{ + return DllEntryPoint((HINSTANCE)(hModule), ul_reason_for_call, lpReserved); +} diff --git a/Source/UnityCaptureFilter.def b/Source/UnityCaptureFilter.def new file mode 100644 index 0000000..5fc0402 --- /dev/null +++ b/Source/UnityCaptureFilter.def @@ -0,0 +1,7 @@ +EXPORTS + DllMain PRIVATE + DllRegisterServer PRIVATE + DllUnregisterServer PRIVATE + DllGetClassObject PRIVATE + DllCanUnloadNow PRIVATE + DllInstall PRIVATE diff --git a/Source/UnityCaptureFilter.sln b/Source/UnityCaptureFilter.sln new file mode 100644 index 0000000..f1d9290 --- /dev/null +++ b/Source/UnityCaptureFilter.sln @@ -0,0 +1,28 @@ + +Microsoft Visual Studio Solution File, Format Version 12.00 +# Visual Studio 2013 +VisualStudioVersion = 12.0.40629.0 +MinimumVisualStudioVersion = 10.0.40219.1 +Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "UnityCaptureFilter", "UnityCaptureFilter.vcxproj", "{3D0A9889-9EC1-4012-9382-4FE1EB610D28}" +EndProject +Global + GlobalSection(SolutionConfigurationPlatforms) = preSolution + Debug|Win32 = Debug|Win32 + Debug|x64 = Debug|x64 + Release|Win32 = Release|Win32 + Release|x64 = Release|x64 + EndGlobalSection + GlobalSection(ProjectConfigurationPlatforms) = postSolution + {3D0A9889-9EC1-4012-9382-4FE1EB610D28}.Debug|Win32.ActiveCfg = Debug|Win32 + {3D0A9889-9EC1-4012-9382-4FE1EB610D28}.Debug|Win32.Build.0 = Debug|Win32 + {3D0A9889-9EC1-4012-9382-4FE1EB610D28}.Debug|x64.ActiveCfg = Debug|x64 + {3D0A9889-9EC1-4012-9382-4FE1EB610D28}.Debug|x64.Build.0 = Debug|x64 + {3D0A9889-9EC1-4012-9382-4FE1EB610D28}.Release|Win32.ActiveCfg = Release|Win32 + {3D0A9889-9EC1-4012-9382-4FE1EB610D28}.Release|Win32.Build.0 = Release|Win32 + {3D0A9889-9EC1-4012-9382-4FE1EB610D28}.Release|x64.ActiveCfg = Release|x64 + {3D0A9889-9EC1-4012-9382-4FE1EB610D28}.Release|x64.Build.0 = Release|x64 + EndGlobalSection + GlobalSection(SolutionProperties) = preSolution + HideSolutionNode = FALSE + EndGlobalSection +EndGlobal diff --git a/Source/UnityCaptureFilter.vcxproj b/Source/UnityCaptureFilter.vcxproj new file mode 100644 index 0000000..4181b30 --- /dev/null +++ b/Source/UnityCaptureFilter.vcxproj @@ -0,0 +1,105 @@ + + + + + Debug + Win32 + + + Debug + x64 + + + Release + Win32 + + + Release + x64 + + + + UnityCaptureFilter + UnityCaptureFilter + {3D0A9889-9EC1-4012-9382-4FE1EB610D28} + + + + DynamicLibrary + v110_xp + v120_xp + v140 + v141 + false + MultiByte + true + true + + + + + + + UnityCaptureFilter64 + UnityCaptureFilter32 + Build\$(Configuration)-$(TargetName)\ + $(OutDir) + false + true + false + $(ProgramW6432)\OBSStudio\bin\x64\obs64.exe + $(ProgramW6432)\OBSStudio\bin\x64 + WindowsLocalDebugger + + + + false + Level3 + true + false + false + + + Win32;_DEBUG;_WINDOWS;_USRDLL;%(PreprocessorDefinitions) + Disabled + EnableFastChecks + MultiThreadedDebug + + + Win32;NDEBUG;_WINDOWS;_USRDLL;%(PreprocessorDefinitions) + Full + true + MultiThreaded + true + true + true + Speed + true + AnySuitable + false + /Gw %(AdditionalOptions) + + + true + true + Windows + false + $(ProjectName).def + + + true + true + UseLinkTimeCodeGeneration + true + false + + + + + + + + + + + \ No newline at end of file diff --git a/Source/UnityCapturePlugin.cpp b/Source/UnityCapturePlugin.cpp new file mode 100644 index 0000000..a49ceef --- /dev/null +++ b/Source/UnityCapturePlugin.cpp @@ -0,0 +1,155 @@ +/* + Unity Capture + Copyright (c) 2018 Bernhard Schelling + + Based on UnityCam + https://github.com/mrayy/UnityCam + Copyright (c) 2016 MHD Yamen Saraiji + + This software is provided 'as-is', without any express or implied + warranty. In no event will the authors be held liable for any damages + arising from the use of this software. + + Permission is granted to anyone to use this software for any purpose, + including commercial applications, and to alter it and redistribute it + freely, subject to the following restrictions: + + 1. The origin of this software must not be misrepresented; you must not + claim that you wrote the original software. If you use this software + in a product, an acknowledgment in the product documentation would be + appreciated but is not required. + 2. Altered source versions must be plainly marked as such, and must not be + misrepresented as being the original software. + 3. This notice may not be removed or altered from any source distribution. +*/ + +#include "shared.inl" +#include +#include +#include "IUnityGraphics.h" + +enum +{ + RET_SUCCESS = 0, + RET_WARNING_FRAMESKIP = 1, + RET_WARNING_CAPTUREINACTIVE = 2, + RET_ERROR_UNSUPPORTEDGRAPHICSDEVICE = 100, + RET_ERROR_PARAMETER = 101, + RET_ERROR_TOOLARGERESOLUTION = 102, + RET_ERROR_TEXTUREFORMAT = 103, + RET_ERROR_READTEXTURE = 104, +}; + +#include + +static int g_GraphicsDeviceType = -1; +static ID3D11Device* g_D3D11GraphicsDevice = 0; + +struct UnityCaptureInstance +{ + SharedImageMemory* Sender; + int Width, Height; + DXGI_FORMAT Format; + bool UseDoubleBuffering, AlternativeBuffer; + ID3D11Texture2D* Textures[2]; +}; + +extern "C" __declspec(dllexport) UnityCaptureInstance* CaptureCreateInstance(int CapNum) +{ + UnityCaptureInstance* c = new UnityCaptureInstance(); + memset(c, 0, sizeof(UnityCaptureInstance)); + c->Sender = new SharedImageMemory(CapNum); + return c; +} + +extern "C" __declspec(dllexport) void CaptureDeleteInstance(UnityCaptureInstance* c) +{ + if (!c) return; + delete c->Sender; + if (c->Textures[0]) c->Textures[0]->Release(); + if (c->Textures[1]) c->Textures[1]->Release(); + delete c; +} + +extern "C" __declspec(dllexport) int CaptureSendTexture(UnityCaptureInstance* c, void* TextureNativePtr, int Timeout, bool UseDoubleBuffering, SharedImageMemory::EResizeMode ResizeMode, SharedImageMemory::EMirrorMode MirrorMode, bool IsLinearColorSpace) +{ + if (!c || !TextureNativePtr) return RET_ERROR_PARAMETER; + if (g_GraphicsDeviceType != kUnityGfxRendererD3D11) return RET_ERROR_UNSUPPORTEDGRAPHICSDEVICE; + if (!c->Sender->SendIsReady()) return RET_WARNING_CAPTUREINACTIVE; + + //Get the active D3D11 context + ID3D11DeviceContext* ctx = NULL; + g_D3D11GraphicsDevice->GetImmediateContext(&ctx); + if (!ctx) return RET_ERROR_UNSUPPORTEDGRAPHICSDEVICE; + + //Read the size and format info from the render texture + ID3D11Texture2D* d3dtex = (ID3D11Texture2D*)TextureNativePtr; + D3D11_TEXTURE2D_DESC desc = {0}; + d3dtex->GetDesc(&desc); + if (!desc.Width || !desc.Height) return RET_ERROR_READTEXTURE; + + if (c->Width != desc.Width || c->Height != desc.Height || c->Format != desc.Format || c->UseDoubleBuffering != UseDoubleBuffering) + { + //Allocate a Texture2D resource which holds the texture with CPU memory access + D3D11_TEXTURE2D_DESC textureDesc; + ZeroMemory(&textureDesc, sizeof(textureDesc)); + textureDesc.Width = desc.Width; + textureDesc.Height = desc.Height; + textureDesc.MipLevels = desc.MipLevels; + textureDesc.ArraySize = 1; + textureDesc.Format = desc.Format; + textureDesc.SampleDesc.Count = 1; + textureDesc.SampleDesc.Quality = 0; + textureDesc.Usage = D3D11_USAGE_STAGING; + textureDesc.CPUAccessFlags = D3D11_CPU_ACCESS_READ; + textureDesc.MiscFlags = 0; + if (c->Textures[0]) c->Textures[0]->Release(); + g_D3D11GraphicsDevice->CreateTexture2D(&textureDesc, NULL, &c->Textures[0]); + if (c->Textures[1]) c->Textures[1]->Release(); + if (UseDoubleBuffering) g_D3D11GraphicsDevice->CreateTexture2D(&textureDesc, NULL, &c->Textures[1]); + else c->Textures[1] = NULL; + c->Width = desc.Width; + c->Height = desc.Height; + c->Format = desc.Format; + c->UseDoubleBuffering = UseDoubleBuffering; + } + + //Handle double buffer + if (c->UseDoubleBuffering) c->AlternativeBuffer ^= 1; + ID3D11Texture2D* WriteTexture = c->Textures[c->UseDoubleBuffering && c->AlternativeBuffer ? 1 : 0]; + ID3D11Texture2D* ReadTexture = c->Textures[c->UseDoubleBuffering && !c->AlternativeBuffer ? 1 : 0]; + + //Check texture format + SharedImageMemory::EFormat Format; + if (desc.Format == DXGI_FORMAT_R8G8B8A8_UNORM || desc.Format == DXGI_FORMAT_R8G8B8A8_UNORM_SRGB || desc.Format == DXGI_FORMAT_R8G8B8A8_UINT || desc.Format == DXGI_FORMAT_R8G8B8A8_TYPELESS) Format = SharedImageMemory::FORMAT_UINT8; + else if (desc.Format == DXGI_FORMAT_R16G16B16A16_FLOAT || desc.Format == DXGI_FORMAT_R16G16B16A16_TYPELESS) Format = (IsLinearColorSpace ? SharedImageMemory::FORMAT_FP16_LINEAR : SharedImageMemory::FORMAT_FP16_GAMMA); + else return RET_ERROR_TEXTUREFORMAT; + + //Copy render texture to texture with CPU access and map the image data to RAM + ctx->CopyResource(WriteTexture, d3dtex); + D3D11_MAPPED_SUBRESOURCE mapResource; + if (FAILED(ctx->Map(ReadTexture, 0, D3D11_MAP_READ, 0, &mapResource))) return RET_ERROR_READTEXTURE; + + //Push the captured data to the direct show filter + SharedImageMemory::ESendResult res = c->Sender->Send(desc.Width, desc.Height, mapResource.RowPitch / (Format == SharedImageMemory::FORMAT_UINT8 ? 4 : 8), mapResource.RowPitch * desc.Height, Format, ResizeMode, MirrorMode, Timeout, (const unsigned char*)mapResource.pData); + + ctx->Unmap(ReadTexture, 0); + + switch (res) + { + case SharedImageMemory::SENDRES_TOOLARGE: return RET_ERROR_TOOLARGERESOLUTION; + case SharedImageMemory::SENDRES_WARN_FRAMESKIP: return RET_WARNING_FRAMESKIP; + } + return RET_SUCCESS; +} + +// If exported by a plugin, this function will be called when graphics device is created, destroyed, and before and after it is reset (ie, resolution changed). +extern "C" void UNITY_INTERFACE_EXPORT UnitySetGraphicsDevice(void* device, int deviceType, int eventType) +{ + if (eventType == kUnityGfxDeviceEventInitialize || eventType == kUnityGfxDeviceEventAfterReset) + { + g_GraphicsDeviceType = deviceType; + if (deviceType == kUnityGfxRendererD3D11) g_D3D11GraphicsDevice = (ID3D11Device*)device; + } + else g_GraphicsDeviceType = -1; +} diff --git a/Source/UnityCapturePlugin.sln b/Source/UnityCapturePlugin.sln new file mode 100644 index 0000000..e4a93f7 --- /dev/null +++ b/Source/UnityCapturePlugin.sln @@ -0,0 +1,28 @@ + +Microsoft Visual Studio Solution File, Format Version 12.00 +# Visual Studio 2013 +VisualStudioVersion = 12.0.40629.0 +MinimumVisualStudioVersion = 10.0.40219.1 +Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "UnityCapturePlugin", "UnityCapturePlugin.vcxproj", "{727D3AC5-27B5-4288-A475-7A471ECD71B8}" +EndProject +Global + GlobalSection(SolutionConfigurationPlatforms) = preSolution + Debug|Win32 = Debug|Win32 + Debug|x64 = Debug|x64 + Release|Win32 = Release|Win32 + Release|x64 = Release|x64 + EndGlobalSection + GlobalSection(ProjectConfigurationPlatforms) = postSolution + {727D3AC5-27B5-4288-A475-7A471ECD71B8}.Debug|Win32.ActiveCfg = Debug|Win32 + {727D3AC5-27B5-4288-A475-7A471ECD71B8}.Debug|Win32.Build.0 = Debug|Win32 + {727D3AC5-27B5-4288-A475-7A471ECD71B8}.Debug|x64.ActiveCfg = Debug|x64 + {727D3AC5-27B5-4288-A475-7A471ECD71B8}.Debug|x64.Build.0 = Debug|x64 + {727D3AC5-27B5-4288-A475-7A471ECD71B8}.Release|Win32.ActiveCfg = Release|Win32 + {727D3AC5-27B5-4288-A475-7A471ECD71B8}.Release|Win32.Build.0 = Release|Win32 + {727D3AC5-27B5-4288-A475-7A471ECD71B8}.Release|x64.ActiveCfg = Release|x64 + {727D3AC5-27B5-4288-A475-7A471ECD71B8}.Release|x64.Build.0 = Release|x64 + EndGlobalSection + GlobalSection(SolutionProperties) = preSolution + HideSolutionNode = FALSE + EndGlobalSection +EndGlobal diff --git a/Source/UnityCapturePlugin.vcxproj b/Source/UnityCapturePlugin.vcxproj new file mode 100644 index 0000000..7bfc92c --- /dev/null +++ b/Source/UnityCapturePlugin.vcxproj @@ -0,0 +1,116 @@ + + + + + Debug + Win32 + + + Debug + x64 + + + Release + Win32 + + + Release + x64 + + + + UnityCapturePlugin + UnityCapturePlugin + {727D3AC5-27B5-4288-A475-7A471ECD71B8} + + + + DynamicLibrary + v110_xp + v120_xp + v140 + v141 + false + MultiByte + true + true + + + + + + + Build\$(Configuration)-$(TargetName)64bit\ + Build\$(Configuration)-$(TargetName)32bit\ + $(OutDir) + false + true + false + $(ProgramW6432)\Unity\Editor\Unity.exe + -projectPath "$(ProjectDir)..\UnityCaptureSample" + WindowsLocalDebugger + + + + false + Level3 + true + false + false + + + Win32;_DEBUG;_WINDOWS;_USRDLL;%(PreprocessorDefinitions) + Disabled + EnableFastChecks + MultiThreadedDebugDLL + + + Win32;NDEBUG;_WINDOWS;_USRDLL;%(PreprocessorDefinitions) + Full + true + MultiThreaded + true + true + true + Speed + true + AnySuitable + false + StreamingSIMDExtensions2 + /Gw %(AdditionalOptions) + + + true + true + Windows + false + opengl32.lib;%(AdditionalDependencies) + + + true + true + UseLinkTimeCodeGeneration + true + false + + + + SETLOCAL + SET TARGET_PLUGIN_DIR=x86 + IF NOT "$(PlatformShortName)" == "x86" SET TARGET_PLUGIN_DIR=x86_64 + echo Copying output $(OutDir)$(TargetName) DLL and PDB to "$(SolutionDir)..\UnityCaptureSample\Assets\UnityCapture\Plugins\%TARGET_PLUGIN_DIR%\" + mkdir "$(SolutionDir)..\UnityCaptureSample\Assets\UnityCapture\Plugins\%TARGET_PLUGIN_DIR%" 2>nul + copy /Y "$(SolutionDir)$(OutDir)$(TargetName).dll" "$(SolutionDir)..\UnityCaptureSample\Assets\UnityCapture\Plugins\%TARGET_PLUGIN_DIR%\" + copy /Y "$(SolutionDir)$(OutDir)$(TargetName).pdb" "$(SolutionDir)..\UnityCaptureSample\Assets\UnityCapture\Plugins\%TARGET_PLUGIN_DIR%\" + ENDLOCAL + + + + + + + + + + + \ No newline at end of file diff --git a/Source/shared.inl b/Source/shared.inl new file mode 100644 index 0000000..b0f936c --- /dev/null +++ b/Source/shared.inl @@ -0,0 +1,165 @@ +/* + Unity Capture + Copyright (c) 2018 Bernhard Schelling + + Based on UnityCam + https://github.com/mrayy/UnityCam + Copyright (c) 2016 MHD Yamen Saraiji +*/ + +#define _HAS_EXCEPTIONS 0 +#define WIN32_LEAN_AND_MEAN +#include +#include +#include + +#define MAX_SHARED_IMAGE_SIZE (3840 * 2160 * 4 * sizeof(short)) //4K (RGBA max 16bit per pixel) + +#if _DEBUG +#define UCASSERT(cond) ((cond) ? ((void)0) : *(volatile int*)0 = 0xbad|(OutputDebugStringA("[FAILED ASSERT] " #cond "\n"),1)) +#else +#define UCASSERT(cond) ((void)0) +#endif + +struct SharedImageMemory +{ + SharedImageMemory(int32_t CapNum) + { + memset(this, 0, sizeof(*this)); + m_CapNum = CapNum; + } + + ~SharedImageMemory() + { + if (m_hMutex) CloseHandle(m_hMutex); + if (m_hWantFrameEvent) CloseHandle(m_hWantFrameEvent); + if (m_hSentFrameEvent) CloseHandle(m_hSentFrameEvent); + if (m_hSharedFile) CloseHandle(m_hSharedFile); + } + + int32_t GetCapNum() { return m_CapNum; } + enum { MAX_CAPNUM = ('z' - '0') }; //see Open() for why this number + enum { RECEIVE_MAX_WAIT = 200 }; //How many milliseconds to wait for new frame + enum EFormat { FORMAT_UINT8, FORMAT_FP16_GAMMA, FORMAT_FP16_LINEAR }; + enum EResizeMode { RESIZEMODE_DISABLED = 0, RESIZEMODE_LINEAR = 1 }; + enum EMirrorMode { MIRRORMODE_DISABLED = 0, MIRRORMODE_HORIZONTALLY = 1 }; + enum EReceiveResult { RECEIVERES_CAPTUREINACTIVE, RECEIVERES_NEWFRAME, RECEIVERES_OLDFRAME }; + + typedef void (*ReceiveCallbackFunc)(int width, int height, int stride, EFormat format, EResizeMode resizemode, EMirrorMode mirrormode, int timeout, uint8_t* buffer, void* callback_data); + + EReceiveResult Receive(ReceiveCallbackFunc callback, void* callback_data) + { + if (!Open(true) || !m_pSharedBuf->width) return RECEIVERES_CAPTUREINACTIVE; + + SetEvent(m_hWantFrameEvent); + bool IsNewFrame = (WaitForSingleObject(m_hSentFrameEvent, RECEIVE_MAX_WAIT) == WAIT_OBJECT_0); + + WaitForSingleObject(m_hMutex, INFINITE); //lock mutex + callback(m_pSharedBuf->width, m_pSharedBuf->height, m_pSharedBuf->stride, (EFormat)m_pSharedBuf->format, (EResizeMode)m_pSharedBuf->resizemode, (EMirrorMode)m_pSharedBuf->mirrormode, m_pSharedBuf->timeout, m_pSharedBuf->data, callback_data); + ReleaseMutex(m_hMutex); //unlock mutex + + return (IsNewFrame ? RECEIVERES_NEWFRAME : RECEIVERES_OLDFRAME); + } + + bool SendIsReady() + { + return Open(false); + } + + enum ESendResult { SENDRES_TOOLARGE, SENDRES_WARN_FRAMESKIP, SENDRES_OK }; + ESendResult Send(int width, int height, int stride, DWORD DataSize, EFormat format, EResizeMode resizemode, EMirrorMode mirrormode, int timeout, const uint8_t* buffer) + { + UCASSERT(buffer); + UCASSERT(m_pSharedBuf); + if (m_pSharedBuf->maxSize < DataSize) return SENDRES_TOOLARGE; + + WaitForSingleObject(m_hMutex, INFINITE); //lock mutex + m_pSharedBuf->width = width; + m_pSharedBuf->height = height; + m_pSharedBuf->stride = stride; + m_pSharedBuf->format = format; + m_pSharedBuf->resizemode = resizemode; + m_pSharedBuf->mirrormode = mirrormode; + m_pSharedBuf->timeout = timeout; + memcpy(m_pSharedBuf->data, buffer, DataSize); + ReleaseMutex(m_hMutex); //unlock mutex + + SetEvent(m_hSentFrameEvent); + bool DidSkipFrame = (WaitForSingleObject(m_hWantFrameEvent, 0) != WAIT_OBJECT_0); + + return (DidSkipFrame ? SENDRES_WARN_FRAMESKIP : SENDRES_OK); + } + +private: + bool Open(bool ForReceiving) + { + if (m_pSharedBuf) return true; //already open + + UCASSERT(m_CapNum <= MAX_CAPNUM); + if (m_CapNum > MAX_CAPNUM) m_CapNum = MAX_CAPNUM; + char CSCapNumChar = (m_CapNum ? '0' + m_CapNum : '\0'); //use NULL terminator for CapNum 0 to be compatible with old filter DLLs before multi cap + char CS_NAME_MUTEX [] = "UnityCapture_Mutx0"; CS_NAME_MUTEX [sizeof(CS_NAME_MUTEX ) - 2] = CSCapNumChar; + char CS_NAME_EVENT_WANT [] = "UnityCapture_Want0"; CS_NAME_EVENT_WANT [sizeof(CS_NAME_EVENT_WANT ) - 2] = CSCapNumChar; + char CS_NAME_EVENT_SENT [] = "UnityCapture_Sent0"; CS_NAME_EVENT_SENT [sizeof(CS_NAME_EVENT_SENT ) - 2] = CSCapNumChar; + char CS_NAME_SHARED_DATA[] = "UnityCapture_Data0"; CS_NAME_SHARED_DATA[sizeof(CS_NAME_SHARED_DATA) - 2] = CSCapNumChar; + + if (!m_hMutex) + { + if (ForReceiving) m_hMutex = CreateMutexA(NULL, FALSE, CS_NAME_MUTEX); + else m_hMutex = OpenMutexA(SYNCHRONIZE, FALSE, CS_NAME_MUTEX); + if (!m_hMutex) return false; + } + + WaitForSingleObject(m_hMutex, INFINITE); //lock mutex + struct UnlockAtReturn { ~UnlockAtReturn() { ReleaseMutex(m); }; HANDLE m; } cs = { m_hMutex }; + + if (!m_hWantFrameEvent) + { + if (ForReceiving) m_hWantFrameEvent = OpenEventA(EVENT_MODIFY_STATE, FALSE, CS_NAME_EVENT_WANT); + else m_hWantFrameEvent = CreateEventA(NULL, FALSE, FALSE, CS_NAME_EVENT_WANT); + if (!m_hWantFrameEvent) return false; + } + + if (!m_hSentFrameEvent) + { + if (ForReceiving) m_hSentFrameEvent = CreateEventA(NULL, FALSE, FALSE, CS_NAME_EVENT_SENT); + else m_hSentFrameEvent = OpenEventA(EVENT_MODIFY_STATE, FALSE, CS_NAME_EVENT_SENT); + if (!m_hSentFrameEvent) return false; + } + + if (!m_hSharedFile) + { + if (ForReceiving) m_hSharedFile = CreateFileMappingA(INVALID_HANDLE_VALUE, NULL, PAGE_READWRITE, NULL, sizeof(SharedMemHeader) + MAX_SHARED_IMAGE_SIZE, CS_NAME_SHARED_DATA); + else m_hSharedFile = OpenFileMappingA(FILE_MAP_WRITE, FALSE, CS_NAME_SHARED_DATA); + if (!m_hSharedFile) return false; + } + + m_pSharedBuf = (SharedMemHeader*)MapViewOfFile(m_hSharedFile, FILE_MAP_WRITE, 0, 0, 0); + if (!m_pSharedBuf) return false; + + if (ForReceiving && m_pSharedBuf->maxSize != MAX_SHARED_IMAGE_SIZE) + m_pSharedBuf->maxSize = MAX_SHARED_IMAGE_SIZE; + + return true; + } + + struct SharedMemHeader + { + DWORD maxSize; + int width; + int height; + int stride; + int format; + int resizemode; + int mirrormode; + int timeout; + uint8_t data[1]; + }; + + int32_t m_CapNum; + HANDLE m_hMutex; + HANDLE m_hWantFrameEvent; + HANDLE m_hSentFrameEvent; + HANDLE m_hSharedFile; + SharedMemHeader* m_pSharedBuf; +}; diff --git a/Source/streams.cpp b/Source/streams.cpp new file mode 100644 index 0000000..e3add3e --- /dev/null +++ b/Source/streams.cpp @@ -0,0 +1,13727 @@ +#include "streams.h" +#include +#include +#include +#include + +#define STREAMS_PROVIDE_CUSTOM_FACTORY + +#pragma comment(lib, "WinMM.lib") + +#include +DEFINE_GUID(IID_IPin,0x56A86891,0xAD4,0x11CE,0xB0,0x3A,0x0,0x20,0xAF,0xB,0xA7,0x70); +DEFINE_GUID(IID_IEnumPins,0x56A86892,0xAD4,0x11CE,0xB0,0x3A,0x0,0x20,0xAF,0xB,0xA7,0x70); +DEFINE_GUID(IID_IEnumMediaTypes,0x89C31040,0x846B,0x11CE,0x97,0xD3,0x0,0xAA,0x0,0x55,0x59,0x5A); +DEFINE_GUID(IID_IMediaFilter,0x56A86899,0xAD4,0x11CE,0xB0,0x3A,0x0,0x20,0xAF,0xB,0xA7,0x70); +DEFINE_GUID(IID_IBaseFilter,0x56A86895,0xAD4,0x11CE,0xB0,0x3A,0x0,0x20,0xAF,0xB,0xA7,0x70); +DEFINE_GUID(IID_IMediaSample,0x56A8689A,0xAD4,0x11CE,0xB0,0x3A,0x0,0x20,0xAF,0xB,0xA7,0x70); +DEFINE_GUID(IID_IMediaSample2,0x36B73884,0xC2C8,0x11CF,0x8B,0x46,0x0,0x80,0x5F,0x6C,0xEF,0x60); +DEFINE_GUID(IID_IMemAllocator,0x56A8689C,0xAD4,0x11CE,0xB0,0x3A,0x0,0x20,0xAF,0xB,0xA7,0x70); +DEFINE_GUID(IID_IMemAllocatorCallbackTemp,0x379A0CF0,0xC1DE,0x11D2,0xAB,0xF5,0x0,0xA0,0xC9,0x5,0xF3,0x75); +DEFINE_GUID(IID_IMemInputPin,0x56A8689D,0xAD4,0x11CE,0xB0,0x3A,0x0,0x20,0xAF,0xB,0xA7,0x70); +DEFINE_GUID(IID_IAMovieSetup,0xA3D8CEC0,0x7E5A,0x11CF,0xBB,0xC5,0x0,0x80,0x5F,0x6C,0xEF,0x20); +DEFINE_GUID(IID_IFilterMapper,0x56A868A3,0xAD4,0x11CE,0xB0,0x3A,0x0,0x20,0xAF,0xB,0xA7,0x70); +DEFINE_GUID(IID_IFilterMapper2,0xB79BB0B0,0x33C1,0x11D1,0xAB,0xE1,0x0,0xA0,0xC9,0x5,0xF3,0x75); +DEFINE_GUID(IID_IMediaEventSink,0x56A868A2,0xAD4,0x11CE,0xB0,0x3A,0x0,0x20,0xAF,0xB,0xA7,0x70); +DEFINE_GUID(IID_IFilterGraph2,0x36B73882,0xC2C8,0x11CF,0x8B,0x46,0x0,0x80,0x5F,0x6C,0xEF,0x60); +DEFINE_GUID(IID_ISeekingPassThru,0x36B73883,0xC2C8,0x11CF,0x8B,0x46,0x0,0x80,0x5F,0x6C,0xEF,0x60); +DEFINE_GUID(IID_IPinConnection,0x4A9A62D3,0x27D4,0x403D,0x91,0xE9,0x89,0xF5,0x40,0xE5,0x55,0x34); +DEFINE_GUID(IID_IPinFlowControl,0xC56E9858,0xDBF3,0x4F6B,0x81,0x19,0x38,0x4A,0xF2,0x6,0xD,0xEB); +DEFINE_GUID(IID_IAMStreamConfig,0xc6e13340,0x30ac,0x11d0,0xa1,0x8c,0x00,0xa0,0xc9,0x11,0x89,0x56); +DEFINE_GUID(IID_IKsPropertySet,0x31efac30,0x515c,0x11d0,0xa9,0xaa,0x0,0xaa,0x0,0x61,0xbe,0x93); + +#ifndef NUMELMS +#if _WIN32_WINNT < 0x0600 + #define NUMELMS(aa) (sizeof(aa)/sizeof((aa)[0])) +#else + #define NUMELMS(aa) ARRAYSIZE(aa) +#endif +#endif + +#pragma warning(push) +#pragma warning(disable: 4312 4244) +// _GetWindowLongPtr +// Templated version of GetWindowLongPtr, to suppress spurious compiler warning. +template +T _GetWindowLongPtr(HWND hwnd, int nIndex) +{ + return (T)GetWindowLongPtr(hwnd, nIndex); +} + +// _SetWindowLongPtr +// Templated version of SetWindowLongPtr, to suppress spurious compiler warning. +template +LONG_PTR _SetWindowLongPtr(HWND hwnd, int nIndex, T p) +{ + return SetWindowLongPtr(hwnd, nIndex, (LONG_PTR)p); +} +#pragma warning(pop) + +#ifdef DEBUG +#ifdef UNICODE +#ifndef _UNICODE +#define _UNICODE +#endif // _UNICODE +#endif // UNICODE +#endif // DEBUG + +//------------------------------------------------------------------------------ +// File: FourCC.h +// +// Desc: DirectShow base classes. +// +// Copyright (c) 1992-2001 Microsoft Corporation. All rights reserved. +//------------------------------------------------------------------------------ + +// FOURCCMap +// +// provides a mapping between old-style multimedia format DWORDs +// and new-style GUIDs. +// +// A range of 4 billion GUIDs has been allocated to ensure that this +// mapping can be done straightforwardly one-to-one in both directions. +// +// January 95 + +#ifndef __FOURCC__ +#define __FOURCC__ + + +// Multimedia format types are marked with DWORDs built from four 8-bit +// chars and known as FOURCCs. New multimedia AM_MEDIA_TYPE definitions include +// a subtype GUID. In order to simplify the mapping, GUIDs in the range: +// XXXXXXXX-0000-0010-8000-00AA00389B71 +// are reserved for FOURCCs. + +class FOURCCMap : public GUID +{ + +public: + FOURCCMap(); + FOURCCMap(DWORD Fourcc); + FOURCCMap(const GUID *); + + + DWORD GetFOURCC(void); + void SetFOURCC(DWORD fourcc); + void SetFOURCC(const GUID *); + +private: + void InitGUID(); +}; + +#define GUID_Data2 0 +#define GUID_Data3 0x10 +#define GUID_Data4_1 0xaa000080 +#define GUID_Data4_2 0x719b3800 + +inline void +FOURCCMap::InitGUID() { + Data2 = GUID_Data2; + Data3 = GUID_Data3; + ((DWORD *)Data4)[0] = GUID_Data4_1; + ((DWORD *)Data4)[1] = GUID_Data4_2; +} + +inline +FOURCCMap::FOURCCMap() { + InitGUID(); + SetFOURCC( DWORD(0)); +} + +inline +FOURCCMap::FOURCCMap(DWORD fourcc) +{ + InitGUID(); + SetFOURCC(fourcc); +} + +inline +FOURCCMap::FOURCCMap(const GUID * pGuid) +{ + InitGUID(); + SetFOURCC(pGuid); +} + +inline void +FOURCCMap::SetFOURCC(const GUID * pGuid) +{ + FOURCCMap * p = (FOURCCMap*) pGuid; + SetFOURCC(p->GetFOURCC()); +} + +inline void +FOURCCMap::SetFOURCC(DWORD fourcc) +{ + Data1 = fourcc; +} + +inline DWORD +FOURCCMap::GetFOURCC(void) +{ + return Data1; +} + +#endif /* __FOURCC__ */ + +//------------------------------------------------------------------------------ +// File: MsgThrd.h +// +// Desc: DirectShow base classes - provides support for a worker thread +// class to which one can asynchronously post messages. +// +// Copyright (c) 1992-2001 Microsoft Corporation. All rights reserved. +//------------------------------------------------------------------------------ + +#ifndef __MSGTHRD__ +#define __MSGTHRD__ + +// Message class - really just a structure. +// +class CMsg { +public: + UINT uMsg; + DWORD dwFlags; + LPVOID lpParam; + CAMEvent *pEvent; + + CMsg(UINT u, DWORD dw, __inout_opt LPVOID lp, __in_opt CAMEvent *pEvnt) + : uMsg(u), dwFlags(dw), lpParam(lp), pEvent(pEvnt) {} + + CMsg() + : uMsg(0), dwFlags(0L), lpParam(NULL), pEvent(NULL) {} +}; + +// This is the actual thread class. It exports all the usual thread control +// functions. The created thread is different from a normal WIN32 thread in +// that it is prompted to perform particaular tasks by responding to messages +// posted to its message queue. +// +class AM_NOVTABLE CMsgThread { +private: + static DWORD WINAPI DefaultThreadProc(__inout LPVOID lpParam); + DWORD m_ThreadId; + HANDLE m_hThread; + +protected: + + // if you want to override GetThreadMsg to block on other things + // as well as this queue, you need access to this + CGenericList m_ThreadQueue; + CCritSec m_Lock; + HANDLE m_hSem; + LONG m_lWaiting; + +public: + CMsgThread() + : m_ThreadId(0), + m_hThread(NULL), + m_lWaiting(0), + m_hSem(NULL), + // make a list with a cache of 5 items + m_ThreadQueue(NAME("MsgThread list"), 5) + { + } + + ~CMsgThread(); + // override this if you want to block on other things as well + // as the message loop + void virtual GetThreadMsg(__out CMsg *msg); + + // override this if you want to do something on thread startup + virtual void OnThreadInit() { + }; + + BOOL CreateThread(); + + BOOL WaitForThreadExit(__out LPDWORD lpdwExitCode) { + if (m_hThread != NULL) { + WaitForSingleObject(m_hThread, INFINITE); + return GetExitCodeThread(m_hThread, lpdwExitCode); + } + return FALSE; + } + + DWORD ResumeThread() { + return ::ResumeThread(m_hThread); + } + + DWORD SuspendThread() { + return ::SuspendThread(m_hThread); + } + + int GetThreadPriority() { + return ::GetThreadPriority(m_hThread); + } + + BOOL SetThreadPriority(int nPriority) { + return ::SetThreadPriority(m_hThread, nPriority); + } + + HANDLE GetThreadHandle() { + return m_hThread; + } + + DWORD GetThreadId() { + return m_ThreadId; + } + + + void PutThreadMsg(UINT uMsg, DWORD dwMsgFlags, + __in_opt LPVOID lpMsgParam, __in_opt CAMEvent *pEvent = NULL) { + CAutoLock lck(&m_Lock); + CMsg* pMsg = new CMsg(uMsg, dwMsgFlags, lpMsgParam, pEvent); + m_ThreadQueue.AddTail(pMsg); + if (m_lWaiting != 0) { + ReleaseSemaphore(m_hSem, m_lWaiting, 0); + m_lWaiting = 0; + } + } + + // This is the function prototype of the function that the client + // supplies. It is always called on the created thread, never on + // the creator thread. + // + virtual LRESULT ThreadMessageProc( + UINT uMsg, DWORD dwFlags, __inout_opt LPVOID lpParam, __in_opt CAMEvent *pEvent) = 0; +}; + +#endif /* __MSGTHRD__ */ + +//------------------------------------------------------------------------------ +// File: Schedule.h +// +// Desc: DirectShow base classes. +// +// Copyright (c) 1996-2001 Microsoft Corporation. All rights reserved. +//------------------------------------------------------------------------------ + +#ifndef __CAMSchedule__ +#define __CAMSchedule__ + +class CAMSchedule : private CBaseObject +{ +public: + virtual ~CAMSchedule(); + // ev is the event we should fire if the advise time needs re-evaluating + CAMSchedule( HANDLE ev ); + + DWORD GetAdviseCount(); + REFERENCE_TIME GetNextAdviseTime(); + + // We need a method for derived classes to add advise packets, we return the cookie + DWORD_PTR AddAdvisePacket( const REFERENCE_TIME & time1, const REFERENCE_TIME & time2, HANDLE h, BOOL periodic ); + // And a way to cancel + HRESULT Unadvise(DWORD_PTR dwAdviseCookie); + + // Tell us the time please, and we'll dispatch the expired events. We return the time of the next event. + // NB: The time returned will be "useless" if you start adding extra Advises. But that's the problem of + // whoever is using this helper class (typically a clock). + REFERENCE_TIME Advise( const REFERENCE_TIME & rtTime ); + + // Get the event handle which will be set if advise time requires re-evaluation. + HANDLE GetEvent() const { return m_ev; } + +private: + // We define the nodes that will be used in our singly linked list + // of advise packets. The list is ordered by time, with the + // elements that will expire first at the front. + class CAdvisePacket + { + public: + CAdvisePacket() + {} + + CAdvisePacket * m_next; + DWORD_PTR m_dwAdviseCookie; + REFERENCE_TIME m_rtEventTime; // Time at which event should be set + REFERENCE_TIME m_rtPeriod; // Periodic time + HANDLE m_hNotify; // Handle to event or semephore + BOOL m_bPeriodic; // TRUE => Periodic event + + CAdvisePacket( __inout_opt CAdvisePacket * next, LONGLONG time ) : m_next(next), m_rtEventTime(time) + {} + + void InsertAfter( __inout CAdvisePacket * p ) + { + p->m_next = m_next; + m_next = p; + } + + int IsZ() const // That is, is it the node that represents the end of the list + { return m_next == 0; } + + CAdvisePacket * RemoveNext() + { + CAdvisePacket *const next = m_next; + CAdvisePacket *const new_next = next->m_next; + m_next = new_next; + return next; + } + + void DeleteNext() + { + delete RemoveNext(); + } + + CAdvisePacket * Next() const + { + CAdvisePacket * result = m_next; + if (result->IsZ()) result = 0; + return result; + } + + DWORD_PTR Cookie() const + { return m_dwAdviseCookie; } + }; + + // Structure is: + // head -> elmt1 -> elmt2 -> z -> null + // So an empty list is: head -> z -> null + // Having head & z as links makes insertaion, + // deletion and shunting much easier. + CAdvisePacket head, z; // z is both a tail and a sentry + + volatile DWORD_PTR m_dwNextCookie; // Strictly increasing + volatile DWORD m_dwAdviseCount; // Number of elements on list + + CCritSec m_Serialize; + + // AddAdvisePacket: adds the packet, returns the cookie (0 if failed) + DWORD_PTR AddAdvisePacket( __inout CAdvisePacket * pPacket ); + // Event that we should set if the packed added above will be the next to fire. + const HANDLE m_ev; + + // A Shunt is where we have changed the first element in the + // list and want it re-evaluating (i.e. repositioned) in + // the list. + void ShuntHead(); + + // Rather than delete advise packets, we cache them for future use + CAdvisePacket * m_pAdviseCache; + DWORD m_dwCacheCount; + enum { dwCacheMax = 5 }; // Don't bother caching more than five + + void Delete( __inout CAdvisePacket * pLink );// This "Delete" will cache the Link + +// Attributes and methods for debugging +public: +#ifdef DEBUG + void DumpLinkedList(); +#else + void DumpLinkedList() {} +#endif + +}; + +#endif // __CAMSchedule__ + +//------------------------------------------------------------------------------ +// File: RefClock.h +// +// Desc: DirectShow base classes - defines the IReferenceClock interface. +// +// Copyright (c) 1992-2001 Microsoft Corporation. All rights reserved. +//------------------------------------------------------------------------------ + +#ifndef __BASEREFCLOCK__ +#define __BASEREFCLOCK__ + +const UINT RESOLUTION = 1; /* High resolution timer */ +const INT ADVISE_CACHE = 4; /* Default cache size */ +const LONGLONG MAX_TIME = 0x7FFFFFFFFFFFFFFF; /* Maximum LONGLONG value */ + +inline LONGLONG WINAPI ConvertToMilliseconds(const REFERENCE_TIME& RT) +{ + /* This converts an arbitrary value representing a reference time + into a MILLISECONDS value for use in subsequent system calls */ + + return (RT / (UNITS / MILLISECONDS)); +} + +/* This class hierarchy will support an IReferenceClock interface so + that an audio card (or other externally driven clock) can update the + system wide clock that everyone uses. + + The interface will be pretty thin with probably just one update method + This interface has not yet been defined. + */ + +/* This abstract base class implements the IReferenceClock + * interface. Classes that actually provide clock signals (from + * whatever source) have to be derived from this class. + * + * The abstract class provides implementations for: + * CUnknown support + * locking support (CCritSec) + * client advise code (creates a thread) + * + * Question: what can we do about quality? Change the timer + * resolution to lower the system load? Up the priority of the + * timer thread to force more responsive signals? + * + * During class construction we create a worker thread that is destroyed during + * destuction. This thread executes a series of WaitForSingleObject calls, + * waking up when a command is given to the thread or the next wake up point + * is reached. The wakeup points are determined by clients making Advise + * calls. + * + * Each advise call defines a point in time when they wish to be notified. A + * periodic advise is a series of these such events. We maintain a list of + * advise links and calculate when the nearest event notification is due for. + * We then call WaitForSingleObject with a timeout equal to this time. The + * handle we wait on is used by the class to signal that something has changed + * and that we must reschedule the next event. This typically happens when + * someone comes in and asks for an advise link while we are waiting for an + * event to timeout. + * + * While we are modifying the list of advise requests we + * are protected from interference through a critical section. Clients are NOT + * advised through callbacks. One shot clients have an event set, while + * periodic clients have a semaphore released for each event notification. A + * semaphore allows a client to be kept up to date with the number of events + * actually triggered and be assured that they can't miss multiple events being + * set. + * + * Keeping track of advises is taken care of by the CAMSchedule class. + */ + +class CBaseReferenceClock +: public CUnknown, public IReferenceClock, public CCritSec, public IReferenceClockTimerControl +{ +protected: + virtual ~CBaseReferenceClock(); // Don't let me be created on the stack! +public: + CBaseReferenceClock(__in_opt LPCTSTR pName, + __inout_opt LPUNKNOWN pUnk, + __inout HRESULT *phr, + __inout_opt CAMSchedule * pSched = 0 ); + + STDMETHODIMP NonDelegatingQueryInterface(REFIID riid, __deref_out void ** ppv); + + DECLARE_IUNKNOWN + + /* IReferenceClock methods */ + // Derived classes must implement GetPrivateTime(). All our GetTime + // does is call GetPrivateTime and then check so that time does not + // go backwards. A return code of S_FALSE implies that the internal + // clock has gone backwards and GetTime time has halted until internal + // time has caught up. (Don't know if this will be much use to folk, + // but it seems odd not to use the return code for something useful.) + STDMETHODIMP GetTime(__out REFERENCE_TIME *pTime); + // When this is called, it sets m_rtLastGotTime to the time it returns. + + /* Provide standard mechanisms for scheduling events */ + + /* Ask for an async notification that a time has elapsed */ + STDMETHODIMP AdviseTime( + REFERENCE_TIME baseTime, // base reference time + REFERENCE_TIME streamTime, // stream offset time + HEVENT hEvent, // advise via this event + __out DWORD_PTR *pdwAdviseCookie// where your cookie goes + ); + + /* Ask for an asynchronous periodic notification that a time has elapsed */ + STDMETHODIMP AdvisePeriodic( + REFERENCE_TIME StartTime, // starting at this time + REFERENCE_TIME PeriodTime, // time between notifications + HSEMAPHORE hSemaphore, // advise via a semaphore + __out DWORD_PTR *pdwAdviseCookie// where your cookie goes + ); + + /* Cancel a request for notification(s) - if the notification was + * a one shot timer then this function doesn't need to be called + * as the advise is automatically cancelled, however it does no + * harm to explicitly cancel a one-shot advise. It is REQUIRED that + * clients call Unadvise to clear a Periodic advise setting. + */ + + STDMETHODIMP Unadvise(DWORD_PTR dwAdviseCookie); + + /* Methods for the benefit of derived classes or outer objects */ + + // GetPrivateTime() is the REAL clock. GetTime is just a cover for + // it. Derived classes will probably override this method but not + // GetTime() itself. + // The important point about GetPrivateTime() is it's allowed to go + // backwards. Our GetTime() will keep returning the LastGotTime + // until GetPrivateTime() catches up. + virtual REFERENCE_TIME GetPrivateTime(); + + /* Provide a method for correcting drift */ + STDMETHODIMP SetTimeDelta( const REFERENCE_TIME& TimeDelta ); + + CAMSchedule * GetSchedule() const { return m_pSchedule; } + + // IReferenceClockTimerControl methods + // + // Setting a default of 0 disables the default of 1ms + STDMETHODIMP SetDefaultTimerResolution( + REFERENCE_TIME timerResolution // in 100ns + ); + STDMETHODIMP GetDefaultTimerResolution( + __out REFERENCE_TIME* pTimerResolution // in 100ns + ); + +private: + REFERENCE_TIME m_rtPrivateTime; // Current best estimate of time + DWORD m_dwPrevSystemTime; // Last vaule we got from timeGetTime + REFERENCE_TIME m_rtLastGotTime; // Last time returned by GetTime + REFERENCE_TIME m_rtNextAdvise; // Time of next advise + UINT m_TimerResolution; + +#ifdef PERF + int m_idGetSystemTime; +#endif + +// Thread stuff +public: + void TriggerThread() // Wakes thread up. Need to do this if + { // time to next advise needs reevaluating. + EXECUTE_ASSERT(SetEvent(m_pSchedule->GetEvent())); + } + + +private: + BOOL m_bAbort; // Flag used for thread shutdown + HANDLE m_hThread; // Thread handle + + HRESULT AdviseThread(); // Method in which the advise thread runs + static DWORD __stdcall AdviseThreadFunction(__in LPVOID); // Function used to get there + +protected: + CAMSchedule * m_pSchedule; + + void Restart (IN REFERENCE_TIME rtMinTime = 0I64) ; +}; + +#endif + +//------------------------------------------------------------------------------ +// File: VideoCtl.h +// +// Desc: DirectShow base classes. +// +// Copyright (c) 1992-2001 Microsoft Corporation. All rights reserved. +//------------------------------------------------------------------------------ + +#ifndef __VIDEOCTL__ +#define __VIDEOCTL__ + +// These help with property page implementations. The first can be used to +// load any string from a resource file. The buffer to load into is passed +// as an input parameter. The same buffer is the return value if the string +// was found otherwise it returns TEXT(""). The GetDialogSize is passed the +// resource ID of a dialog box and returns the size of it in screen pixels + +#define STR_MAX_LENGTH 256 +LPTSTR WINAPI StringFromResource(__out_ecount(STR_MAX_LENGTH) LPTSTR pBuffer, int iResourceID); + +#ifdef UNICODE +#define WideStringFromResource StringFromResource +LPSTR WINAPI StringFromResource(__out_ecount(STR_MAX_LENGTH) LPSTR pBuffer, int iResourceID); +#else +LPWSTR WINAPI WideStringFromResource(__out_ecount(STR_MAX_LENGTH) LPWSTR pBuffer, int iResourceID); +#endif + + +BOOL WINAPI GetDialogSize(int iResourceID, // Dialog box resource identifier + DLGPROC pDlgProc, // Pointer to dialog procedure + LPARAM lParam, // Any user data wanted in pDlgProc + __out SIZE *pResult);// Returns the size of dialog box + +// Class that aggregates an IDirectDraw interface + +class CAggDirectDraw : public IDirectDraw, public CUnknown +{ +protected: + + LPDIRECTDRAW m_pDirectDraw; + +public: + + DECLARE_IUNKNOWN + STDMETHODIMP NonDelegatingQueryInterface(REFIID riid,__deref_out void **ppv); + + // Constructor and destructor + + CAggDirectDraw(__in_opt LPCTSTR pName,__inout_opt LPUNKNOWN pUnk) : + CUnknown(pName,pUnk), + m_pDirectDraw(NULL) { }; + + virtual CAggDirectDraw::~CAggDirectDraw() { }; + + // Set the object we should be aggregating + void SetDirectDraw(__inout LPDIRECTDRAW pDirectDraw) { + m_pDirectDraw = pDirectDraw; + } + + // IDirectDraw methods + + STDMETHODIMP Compact(); + STDMETHODIMP CreateClipper(DWORD dwFlags,__deref_out LPDIRECTDRAWCLIPPER *lplpDDClipper,__inout_opt IUnknown *pUnkOuter); + STDMETHODIMP CreatePalette(DWORD dwFlags,__in LPPALETTEENTRY lpColorTable,__deref_out LPDIRECTDRAWPALETTE *lplpDDPalette,__inout_opt IUnknown *pUnkOuter); + STDMETHODIMP CreateSurface(__in LPDDSURFACEDESC lpDDSurfaceDesc,__deref_out LPDIRECTDRAWSURFACE *lplpDDSurface,__inout_opt IUnknown *pUnkOuter); + STDMETHODIMP DuplicateSurface(__in LPDIRECTDRAWSURFACE lpDDSurface,__deref_out LPDIRECTDRAWSURFACE *lplpDupDDSurface); + STDMETHODIMP EnumDisplayModes(DWORD dwSurfaceDescCount,__in LPDDSURFACEDESC lplpDDSurfaceDescList,__in LPVOID lpContext,__in LPDDENUMMODESCALLBACK lpEnumCallback); + STDMETHODIMP EnumSurfaces(DWORD dwFlags,__in LPDDSURFACEDESC lpDDSD,__in LPVOID lpContext,__in LPDDENUMSURFACESCALLBACK lpEnumCallback); + STDMETHODIMP FlipToGDISurface(); + STDMETHODIMP GetCaps(__out LPDDCAPS lpDDDriverCaps,__out LPDDCAPS lpDDHELCaps); + STDMETHODIMP GetDisplayMode(__out LPDDSURFACEDESC lpDDSurfaceDesc); + STDMETHODIMP GetFourCCCodes(__inout LPDWORD lpNumCodes,__out_ecount(*lpNumCodes) LPDWORD lpCodes); + STDMETHODIMP GetGDISurface(__deref_out LPDIRECTDRAWSURFACE *lplpGDIDDSurface); + STDMETHODIMP GetMonitorFrequency(__out LPDWORD lpdwFrequency); + STDMETHODIMP GetScanLine(__out LPDWORD lpdwScanLine); + STDMETHODIMP GetVerticalBlankStatus(__out LPBOOL lpblsInVB); + STDMETHODIMP Initialize(__in GUID *lpGUID); + STDMETHODIMP RestoreDisplayMode(); + STDMETHODIMP SetCooperativeLevel(HWND hWnd,DWORD dwFlags); + STDMETHODIMP SetDisplayMode(DWORD dwWidth,DWORD dwHeight,DWORD dwBpp); + STDMETHODIMP WaitForVerticalBlank(DWORD dwFlags,HANDLE hEvent); +}; + + +// Class that aggregates an IDirectDrawSurface interface + +class CAggDrawSurface : public IDirectDrawSurface, public CUnknown +{ +protected: + + LPDIRECTDRAWSURFACE m_pDirectDrawSurface; + +public: + + DECLARE_IUNKNOWN + STDMETHODIMP NonDelegatingQueryInterface(REFIID riid,__deref_out void **ppv); + + // Constructor and destructor + + CAggDrawSurface(__in_opt LPCTSTR pName,__inout_opt LPUNKNOWN pUnk) : + CUnknown(pName,pUnk), + m_pDirectDrawSurface(NULL) { }; + + virtual ~CAggDrawSurface() { }; + + // Set the object we should be aggregating + void SetDirectDrawSurface(__inout LPDIRECTDRAWSURFACE pDirectDrawSurface) { + m_pDirectDrawSurface = pDirectDrawSurface; + } + + // IDirectDrawSurface methods + + STDMETHODIMP AddAttachedSurface(__in LPDIRECTDRAWSURFACE lpDDSAttachedSurface); + STDMETHODIMP AddOverlayDirtyRect(__in LPRECT lpRect); + STDMETHODIMP Blt(__in LPRECT lpDestRect,__in LPDIRECTDRAWSURFACE lpDDSrcSurface,__in LPRECT lpSrcRect,DWORD dwFlags,__in LPDDBLTFX lpDDBltFx); + STDMETHODIMP BltBatch(__in_ecount(dwCount) LPDDBLTBATCH lpDDBltBatch,DWORD dwCount,DWORD dwFlags); + STDMETHODIMP BltFast(DWORD dwX,DWORD dwY,__in LPDIRECTDRAWSURFACE lpDDSrcSurface,__in LPRECT lpSrcRect,DWORD dwTrans); + STDMETHODIMP DeleteAttachedSurface(DWORD dwFlags,__in LPDIRECTDRAWSURFACE lpDDSAttachedSurface); + STDMETHODIMP EnumAttachedSurfaces(__in LPVOID lpContext,__in LPDDENUMSURFACESCALLBACK lpEnumSurfacesCallback); + STDMETHODIMP EnumOverlayZOrders(DWORD dwFlags,__in LPVOID lpContext,__in LPDDENUMSURFACESCALLBACK lpfnCallback); + STDMETHODIMP Flip(__in LPDIRECTDRAWSURFACE lpDDSurfaceTargetOverride,DWORD dwFlags); + STDMETHODIMP GetAttachedSurface(__in LPDDSCAPS lpDDSCaps,__deref_out LPDIRECTDRAWSURFACE *lplpDDAttachedSurface); + STDMETHODIMP GetBltStatus(DWORD dwFlags); + STDMETHODIMP GetCaps(__out LPDDSCAPS lpDDSCaps); + STDMETHODIMP GetClipper(__deref_out LPDIRECTDRAWCLIPPER *lplpDDClipper); + STDMETHODIMP GetColorKey(DWORD dwFlags,__out LPDDCOLORKEY lpDDColorKey); + STDMETHODIMP GetDC(__out HDC *lphDC); + STDMETHODIMP GetFlipStatus(DWORD dwFlags); + STDMETHODIMP GetOverlayPosition(__out LPLONG lpdwX,__out LPLONG lpdwY); + STDMETHODIMP GetPalette(__deref_out LPDIRECTDRAWPALETTE *lplpDDPalette); + STDMETHODIMP GetPixelFormat(__out LPDDPIXELFORMAT lpDDPixelFormat); + STDMETHODIMP GetSurfaceDesc(__out LPDDSURFACEDESC lpDDSurfaceDesc); + STDMETHODIMP Initialize(__in LPDIRECTDRAW lpDD,__in LPDDSURFACEDESC lpDDSurfaceDesc); + STDMETHODIMP IsLost(); + STDMETHODIMP Lock(__in LPRECT lpDestRect,__inout LPDDSURFACEDESC lpDDSurfaceDesc,DWORD dwFlags,HANDLE hEvent); + STDMETHODIMP ReleaseDC(HDC hDC); + STDMETHODIMP Restore(); + STDMETHODIMP SetClipper(__in LPDIRECTDRAWCLIPPER lpDDClipper); + STDMETHODIMP SetColorKey(DWORD dwFlags,__in LPDDCOLORKEY lpDDColorKey); + STDMETHODIMP SetOverlayPosition(LONG dwX,LONG dwY); + STDMETHODIMP SetPalette(__in LPDIRECTDRAWPALETTE lpDDPalette); + STDMETHODIMP Unlock(__in LPVOID lpSurfaceData); + STDMETHODIMP UpdateOverlay(__in LPRECT lpSrcRect,__in LPDIRECTDRAWSURFACE lpDDDestSurface,__in LPRECT lpDestRect,DWORD dwFlags,__in LPDDOVERLAYFX lpDDOverlayFX); + STDMETHODIMP UpdateOverlayDisplay(DWORD dwFlags); + STDMETHODIMP UpdateOverlayZOrder(DWORD dwFlags,__in LPDIRECTDRAWSURFACE lpDDSReference); +}; + + +class CLoadDirectDraw +{ + LPDIRECTDRAW m_pDirectDraw; // The DirectDraw driver instance + HINSTANCE m_hDirectDraw; // Handle to the loaded library + +public: + + CLoadDirectDraw(); + ~CLoadDirectDraw(); + + HRESULT LoadDirectDraw(__in LPSTR szDevice); + void ReleaseDirectDraw(); + HRESULT IsDirectDrawLoaded(); + LPDIRECTDRAW GetDirectDraw(); + BOOL IsDirectDrawVersion1(); +}; + +#endif // __VIDEOCTL__ + +//------------------------------------------------------------------------------ +// File: Measure.h +// +// Desc: DirectShow base classes. +// +// Copyright (c) 1992-2001 Microsoft Corporation. All rights reserved. +//------------------------------------------------------------------------------ + +/* + The idea is to pepper the source code with interesting measurements and + have the last few thousand of these recorded in a circular buffer that + can be post-processed to give interesting numbers. + + WHAT THE LOG LOOKS LIKE: + + Time (sec) Type Delta Incident_Name + 0.055,41 NOTE -. Incident Nine - Another note + 0.055,42 NOTE 0.000,01 Incident Nine - Another note + 0.055,44 NOTE 0.000,02 Incident Nine - Another note + 0.055,45 STOP -. Incident Eight - Also random + 0.055,47 START -. Incident Seven - Random + 0.055,49 NOTE 0.000,05 Incident Nine - Another note + ------- ---------------- + 0.125,60 STOP 0.000,03 Msr_Stop + 0.125,62 START -. Msr_Start + 0.125,63 START -. Incident Two - Start/Stop + 0.125,65 STOP 0.000,03 Msr_Start + 0.125,66 START -. Msr_Stop + 0.125,68 STOP 0.000,05 Incident Two - Start/Stop + 0.125,70 STOP 0.000,04 Msr_Stop + 0.125,72 START -. Msr_Start + 0.125,73 START -. Incident Two - Start/Stop + 0.125,75 STOP 0.000,03 Msr_Start + 0.125,77 START -. Msr_Stop + 0.125,78 STOP 0.000,05 Incident Two - Start/Stop + 0.125,80 STOP 0.000,03 Msr_Stop + 0.125,81 NOTE -. Incident Three - single Note + 0.125,83 START -. Incident Four - Start, no stop + 0.125,85 START -. Incident Five - Single Start/Stop + 0.125,87 STOP 0.000,02 Incident Five - Single Start/Stop + +Number Average StdDev Smallest Largest Incident_Name + 10 0.000,58 0.000,10 0.000,55 0.000,85 Incident One - Note + 50 0.000,05 0.000,00 0.000,05 0.000,05 Incident Two - Start/Stop + 1 -. -. -. -. Incident Three - single Note + 0 -. -. -. -. Incident Four - Start, no stop + 1 0.000,02 -. 0.000,02 0.000,02 Incident Five - Single Start/Stop + 0 -. -. -. -. Incident Six - zero occurrences + 100 0.000,25 0.000,12 0.000,02 0.000,62 Incident Seven - Random + 100 0.000,79 0.000,48 0.000,02 0.001,92 Incident Eight - Also random + 5895 0.000,01 0.000,01 0.000,01 0.000,56 Incident Nine - Another note + 10 0.000,03 0.000,00 0.000,03 0.000,04 Msr_Note + 50 0.000,03 0.000,00 0.000,03 0.000,04 Msr_Start + 50 0.000,04 0.000,03 0.000,03 0.000,31 Msr_Stop + + WHAT IT MEANS: + The log shows what happened and when. Each line shows the time at which + something happened (see WHAT YOU CODE below) what it was that happened + and (if approporate) the time since the corresponding previous event + (that's the delta column). + + The statistics show how many times each event occurred, what the average + delta time was, also the standard deviation, largest and smalles delta. + + WHAT YOU CODE: + + Before anything else executes: - register your ids + + int id1 = Msr_Register("Incident One - Note"); + int id2 = Msr_Register("Incident Two - Start/Stop"); + int id3 = Msr_Register("Incident Three - single Note"); + etc. + + At interesting moments: + + // To measure a repetitive event - e.g. end of bitblt to screen + Msr_Note(Id9); // e.g. "video frame hiting the screen NOW!" + + or + + // To measure an elapsed time e.g. time taken to decode an MPEG B-frame + Msr_Start(Id2); // e.g. "Starting to decode MPEG B-frame" + . . . + MsrStop(Id2); // "Finished MPEG decode" + + At the end: + + HANDLE hFile; + hFile = CreateFile("Perf.log", GENERIC_WRITE, 0, NULL, CREATE_ALWAYS, 0, NULL); + Msr_Dump(hFile); // This writes the log out to the file + CloseHandle(hFile); + + or + + Msr_Dump(NULL); // This writes it to DbgLog((LOG_TRACE,0, ... )); + // but if you are writing it out to the debugger + // then the times are probably all garbage because + // the debugger can make things run awfully slow. + + A given id should be used either for start / stop or Note calls. If Notes + are mixed in with Starts and Stops their statistics will be gibberish. + + If you code the calls in upper case i.e. MSR_START(idMunge); then you get + macros which will turn into nothing unless PERF is defined. + + You can reset the statistical counts for a given id by calling Reset(Id). + They are reset by default at the start. + It logs Reset as a special incident, so you can see it in the log. + + The log is a circular buffer in storage (to try to minimise disk I/O). + It overwrites the oldest entries once full. The statistics include ALL + incidents since the last Reset, whether still visible in the log or not. +*/ + +#ifndef __MEASURE__ +#define __MEASURE__ + +#ifdef PERF +#define MSR_INIT() Msr_Init() +#define MSR_TERMINATE() Msr_Terminate() +#define MSR_REGISTER(a) Msr_Register(a) +#define MSR_RESET(a) Msr_Reset(a) +#define MSR_CONTROL(a) Msr_Control(a) +#define MSR_START(a) Msr_Start(a) +#define MSR_STOP(a) Msr_Stop(a) +#define MSR_NOTE(a) Msr_Note(a) +#define MSR_INTEGER(a,b) Msr_Integer(a,b) +#define MSR_DUMP(a) Msr_Dump(a) +#define MSR_DUMPSTATS(a) Msr_DumpStats(a) +#else +#define MSR_INIT() ((void)0) +#define MSR_TERMINATE() ((void)0) +#define MSR_REGISTER(a) 0 +#define MSR_RESET(a) ((void)0) +#define MSR_CONTROL(a) ((void)0) +#define MSR_START(a) ((void)0) +#define MSR_STOP(a) ((void)0) +#define MSR_NOTE(a) ((void)0) +#define MSR_INTEGER(a,b) ((void)0) +#define MSR_DUMP(a) ((void)0) +#define MSR_DUMPSTATS(a) ((void)0) +#endif + +#ifdef __cplusplus +extern "C" { +#endif + +// This must be called first - (called by the DllEntry) + +void WINAPI Msr_Init(void); + + +// Call this last to clean up (or just let it fall off the end - who cares?) + +void WINAPI Msr_Terminate(void); + + +// Call this to get an Id for an "incident" that you can pass to Start, Stop or Note +// everything that's logged is called an "incident". + +int WINAPI Msr_Register(__in LPTSTR Incident); + + +// Reset the statistical counts for an incident + +void WINAPI Msr_Reset(int Id); + + +// Reset all the counts for all incidents +#define MSR_RESET_ALL 0 +#define MSR_PAUSE 1 +#define MSR_RUN 2 + +void WINAPI Msr_Control(int iAction); + + +// log the start of an operation + +void WINAPI Msr_Start(int Id); + + +// log the end of an operation + +void WINAPI Msr_Stop(int Id); + + +// log a one-off or repetitive operation + +void WINAPI Msr_Note(int Id); + + +// log an integer (on which we can see statistics later) +void WINAPI Msr_Integer(int Id, int n); + + +// print out all the vaialable log (it may have wrapped) and then the statistics. +// When the log wraps you lose log but the statistics are still complete. +// hFIle==NULL => use DbgLog +// otherwise hFile must have come from CreateFile or OpenFile. + +void WINAPI Msr_Dump(HANDLE hFile); + + +// just dump the statistics - never mind the log + +void WINAPI Msr_DumpStats(HANDLE hFile); + +// Type definitions in case you want to declare a pointer to the dump functions +// (makes it a trifle easier to do dynamic linking +// i.e. LoadModule, GetProcAddress and call that) + +// Typedefs so can declare MSR_DUMPPROC *MsrDumpStats; or whatever +typedef void WINAPI MSR_DUMPPROC(HANDLE hFile); +typedef void WINAPI MSR_CONTROLPROC(int iAction); + + +#ifdef __cplusplus +} +#endif + +#endif // __MEASURE__ + +//------------------------------------------------------------------------------ +// File: WinUtil.h +// +// Desc: DirectShow base classes - defines generic handler classes. +// +// Copyright (c) 1992-2001 Microsoft Corporation. All rights reserved. +//------------------------------------------------------------------------------ + +// Make sure that you call PrepareWindow to initialise the window after +// the object has been constructed. It is a separate method so that +// derived classes can override useful methods like MessageLoop. Also +// any derived class must call DoneWithWindow in its destructor. If it +// doesn't a message may be retrieved and call a derived class member +// function while a thread is executing the base class destructor code + +#ifndef __WINUTIL__ +#define __WINUTIL__ + +const int DEFWIDTH = 320; // Initial window width +const int DEFHEIGHT = 240; // Initial window height +const int CAPTION = 256; // Maximum length of caption +const int TIMELENGTH = 50; // Maximum length of times +const int PROFILESTR = 128; // Normal profile string +const WORD PALVERSION = 0x300; // GDI palette version +const LONG PALETTE_VERSION = (LONG) 1; // Initial palette version +const COLORREF VIDEO_COLOUR = 0; // Defaults to black background +const HANDLE hMEMORY = (HANDLE) (-1); // Says to open as memory file + +#define WIDTH(x) ((*(x)).right - (*(x)).left) +#define HEIGHT(x) ((*(x)).bottom - (*(x)).top) +#define SHOWSTAGE TEXT("WM_SHOWSTAGE") +#define SHOWSTAGETOP TEXT("WM_SHOWSTAGETOP") +#define REALIZEPALETTE TEXT("WM_REALIZEPALETTE") + +class AM_NOVTABLE CBaseWindow +{ +protected: + + HINSTANCE m_hInstance; // Global module instance handle + HWND m_hwnd; // Handle for our window + HDC m_hdc; // Device context for the window + LONG m_Width; // Client window width + LONG m_Height; // Client window height + BOOL m_bActivated; // Has the window been activated + LPTSTR m_pClassName; // Static string holding class name + DWORD m_ClassStyles; // Passed in to our constructor + DWORD m_WindowStyles; // Likewise the initial window styles + DWORD m_WindowStylesEx; // And the extended window styles + UINT m_ShowStageMessage; // Have the window shown with focus + UINT m_ShowStageTop; // Makes the window WS_EX_TOPMOST + UINT m_RealizePalette; // Makes us realize our new palette + HDC m_MemoryDC; // Used for fast BitBlt operations + HPALETTE m_hPalette; // Handle to any palette we may have + BYTE m_bNoRealize; // Don't realize palette now + BYTE m_bBackground; // Should we realise in background + BYTE m_bRealizing; // already realizing the palette + CCritSec m_WindowLock; // Serialise window object access + BOOL m_bDoGetDC; // Should this window get a DC + bool m_bDoPostToDestroy; // Use PostMessage to destroy + CCritSec m_PaletteLock; // This lock protects m_hPalette. + // It should be held anytime the + // program use the value of m_hPalette. + + // Maps windows message procedure into C++ methods + friend LRESULT CALLBACK WndProc(HWND hwnd, // Window handle + UINT uMsg, // Message ID + WPARAM wParam, // First parameter + LPARAM lParam); // Other parameter + + virtual LRESULT OnPaletteChange(HWND hwnd, UINT Message); + +public: + + CBaseWindow(BOOL bDoGetDC = TRUE, bool bPostToDestroy = false); + +#ifdef DEBUG + virtual ~CBaseWindow(); +#endif + + virtual HRESULT DoneWithWindow(); + virtual HRESULT PrepareWindow(); + virtual HRESULT InactivateWindow(); + virtual HRESULT ActivateWindow(); + virtual BOOL OnSize(LONG Width, LONG Height); + virtual BOOL OnClose(); + virtual RECT GetDefaultRect(); + virtual HRESULT UninitialiseWindow(); + virtual HRESULT InitialiseWindow(HWND hwnd); + + HRESULT CompleteConnect(); + HRESULT DoCreateWindow(); + + HRESULT PerformanceAlignWindow(); + HRESULT DoShowWindow(LONG ShowCmd); + void PaintWindow(BOOL bErase); + void DoSetWindowForeground(BOOL bFocus); + virtual HRESULT SetPalette(HPALETTE hPalette); + void SetRealize(BOOL bRealize) + { + m_bNoRealize = !bRealize; + } + + // Jump over to the window thread to set the current palette + HRESULT SetPalette(); + void UnsetPalette(void); + virtual HRESULT DoRealisePalette(BOOL bForceBackground = FALSE); + + void LockPaletteLock(); + void UnlockPaletteLock(); + + virtual BOOL PossiblyEatMessage(UINT uMsg, WPARAM wParam, LPARAM lParam) + { return FALSE; }; + + // Access our window information + + bool WindowExists(); + LONG GetWindowWidth(); + LONG GetWindowHeight(); + HWND GetWindowHWND(); + HDC GetMemoryHDC(); + HDC GetWindowHDC(); + + #ifdef DEBUG + HPALETTE GetPalette(); + #endif // DEBUG + + // This is the window procedure the derived object should override + + virtual LRESULT OnReceiveMessage(HWND hwnd, // Window handle + UINT uMsg, // Message ID + WPARAM wParam, // First parameter + LPARAM lParam); // Other parameter + + // Must be overriden to return class and window styles + + virtual LPTSTR GetClassWindowStyles( + __out DWORD *pClassStyles, // Class styles + __out DWORD *pWindowStyles, // Window styles + __out DWORD *pWindowStylesEx) PURE; // Extended styles +}; + + +// This helper class is entirely subservient to the owning CBaseWindow object +// All this object does is to split out the actual drawing operation from the +// main object (because it was becoming too large). We have a number of entry +// points to set things like the draw device contexts, to implement the actual +// drawing and to set the destination rectangle in the client window. We have +// no critical section locking in this class because we are used exclusively +// by the owning window object which looks after serialising calls into us + +// If you want to use this class make sure you call NotifyAllocator once the +// allocate has been agreed, also call NotifyMediaType with a pointer to a +// NON stack based CMediaType once that has been set (we keep a pointer to +// the original rather than taking a copy). When the palette changes call +// IncrementPaletteVersion (easiest thing to do is to also call this method +// in the SetMediaType method most filters implement). Finally before you +// start rendering anything call SetDrawContext so that we can get the HDCs +// for drawing from the CBaseWindow object we are given during construction + +class CDrawImage +{ +protected: + + CBaseWindow *m_pBaseWindow; // Owning video window object + CRefTime m_StartSample; // Start time for the current sample + CRefTime m_EndSample; // And likewise it's end sample time + HDC m_hdc; // Main window device context + HDC m_MemoryDC; // Offscreen draw device context + RECT m_TargetRect; // Target destination rectangle + RECT m_SourceRect; // Source image rectangle + BOOL m_bStretch; // Do we have to stretch the images + BOOL m_bUsingImageAllocator; // Are the samples shared DIBSECTIONs + CMediaType *m_pMediaType; // Pointer to the current format + int m_perfidRenderTime; // Time taken to render an image + LONG m_PaletteVersion; // Current palette version cookie + + // Draw the video images in the window + + void SlowRender(IMediaSample *pMediaSample); + void FastRender(IMediaSample *pMediaSample); + void DisplaySampleTimes(IMediaSample *pSample); + void UpdateColourTable(HDC hdc,__in BITMAPINFOHEADER *pbmi); + void SetStretchMode(); + +public: + + // Used to control the image drawing + + CDrawImage(__inout CBaseWindow *pBaseWindow); + BOOL DrawImage(IMediaSample *pMediaSample); + BOOL DrawVideoImageHere(HDC hdc, IMediaSample *pMediaSample, + __in LPRECT lprcSrc, __in LPRECT lprcDst); + void SetDrawContext(); + void SetTargetRect(__in RECT *pTargetRect); + void SetSourceRect(__in RECT *pSourceRect); + void GetTargetRect(__out RECT *pTargetRect); + void GetSourceRect(__out RECT *pSourceRect); + virtual RECT ScaleSourceRect(const RECT *pSource); + + // Handle updating palettes as they change + + LONG GetPaletteVersion(); + void ResetPaletteVersion(); + void IncrementPaletteVersion(); + + // Tell us media types and allocator assignments + + void NotifyAllocator(BOOL bUsingImageAllocator); + void NotifyMediaType(__in CMediaType *pMediaType); + BOOL UsingImageAllocator(); + + // Called when we are about to draw an image + + void NotifyStartDraw() { + MSR_START(m_perfidRenderTime); + }; + + // Called when we complete an image rendering + + void NotifyEndDraw() { + MSR_STOP(m_perfidRenderTime); + }; +}; + + +// This is the structure used to keep information about each GDI DIB. All the +// samples we create from our allocator will have a DIBSECTION allocated to +// them. When we receive the sample we know we can BitBlt straight to an HDC + +typedef struct tagDIBDATA { + + LONG PaletteVersion; // Current palette version in use + DIBSECTION DibSection; // Details of DIB section allocated + HBITMAP hBitmap; // Handle to bitmap for drawing + HANDLE hMapping; // Handle to shared memory block + BYTE *pBase; // Pointer to base memory address + +} DIBDATA; + + +// This class inherits from CMediaSample and uses all of it's methods but it +// overrides the constructor to initialise itself with the DIBDATA structure +// When we come to render an IMediaSample we will know if we are using our own +// allocator, and if we are, we can cast the IMediaSample to a pointer to one +// of these are retrieve the DIB section information and hence the HBITMAP + +class CImageSample : public CMediaSample +{ +protected: + + DIBDATA m_DibData; // Information about the DIBSECTION + BOOL m_bInit; // Is the DIB information setup + +public: + + // Constructor + + CImageSample(__inout CBaseAllocator *pAllocator, + __in_opt LPCTSTR pName, + __inout HRESULT *phr, + __in_bcount(length) LPBYTE pBuffer, + LONG length); + + // Maintain the DIB/DirectDraw state + + void SetDIBData(__in DIBDATA *pDibData); + __out DIBDATA *GetDIBData(); +}; + + +// This is an allocator based on the abstract CBaseAllocator base class that +// allocates sample buffers in shared memory. The number and size of these +// are determined when the output pin calls Prepare on us. The shared memory +// blocks are used in subsequent calls to GDI CreateDIBSection, once that +// has been done the output pin can fill the buffers with data which will +// then be handed to GDI through BitBlt calls and thereby remove one copy + +class CImageAllocator : public CBaseAllocator +{ +protected: + + CBaseFilter *m_pFilter; // Delegate reference counts to + CMediaType *m_pMediaType; // Pointer to the current format + + // Used to create and delete samples + + HRESULT Alloc(); + void Free(); + + // Manage the shared DIBSECTION and DCI/DirectDraw buffers + + HRESULT CreateDIB(LONG InSize,DIBDATA &DibData); + STDMETHODIMP CheckSizes(__in ALLOCATOR_PROPERTIES *pRequest); + virtual CImageSample *CreateImageSample(__in_bcount(Length) LPBYTE pData,LONG Length); + +public: + + // Constructor and destructor + + CImageAllocator(__inout CBaseFilter *pFilter,__in_opt LPCTSTR pName,__inout HRESULT *phr); +#ifdef DEBUG + ~CImageAllocator(); +#endif + + STDMETHODIMP_(ULONG) NonDelegatingAddRef(); + STDMETHODIMP_(ULONG) NonDelegatingRelease(); + void NotifyMediaType(__in CMediaType *pMediaType); + + // Agree the number of buffers to be used and their size + + STDMETHODIMP SetProperties( + __in ALLOCATOR_PROPERTIES *pRequest, + __out ALLOCATOR_PROPERTIES *pActual); +}; + + +// This class is a fairly specialised helper class for image renderers that +// have to create and manage palettes. The CBaseWindow class looks after +// realising palettes once they have been installed. This class can be used +// to create the palette handles from a media format (which must contain a +// VIDEOINFO structure in the format block). We try to make the palette an +// identity palette to maximise performance and also only change palettes +// if actually required to (we compare palette colours before updating). +// All the methods are virtual so that they can be overriden if so required + +class CImagePalette +{ +protected: + + CBaseWindow *m_pBaseWindow; // Window to realise palette in + CBaseFilter *m_pFilter; // Media filter to send events + CDrawImage *m_pDrawImage; // Object who will be drawing + HPALETTE m_hPalette; // The palette handle we own + +public: + + CImagePalette(__inout CBaseFilter *pBaseFilter, + __inout CBaseWindow *pBaseWindow, + __inout CDrawImage *pDrawImage); + +#ifdef DEBUG + virtual ~CImagePalette(); +#endif + + static HPALETTE MakePalette(const VIDEOINFOHEADER *pVideoInfo, __in LPSTR szDevice); + HRESULT RemovePalette(); + static HRESULT MakeIdentityPalette(__inout_ecount_full(iColours) PALETTEENTRY *pEntry,INT iColours, __in LPSTR szDevice); + HRESULT CopyPalette(const CMediaType *pSrc,__out CMediaType *pDest); + BOOL ShouldUpdate(const VIDEOINFOHEADER *pNewInfo,const VIDEOINFOHEADER *pOldInfo); + HRESULT PreparePalette(const CMediaType *pmtNew,const CMediaType *pmtOld,__in LPSTR szDevice); + + BOOL DrawVideoImageHere(HDC hdc, IMediaSample *pMediaSample, __in LPRECT lprcSrc, __in LPRECT lprcDst) + { + return m_pDrawImage->DrawVideoImageHere(hdc, pMediaSample, lprcSrc,lprcDst); + } +}; + + +// Another helper class really for video based renderers. Most such renderers +// need to know what the display format is to some degree or another. This +// class initialises itself with the display format. The format can be asked +// for through GetDisplayFormat and various other accessor functions. If a +// filter detects a display format change (perhaps it gets a WM_DEVMODECHANGE +// message then it can call RefreshDisplayType to reset that format). Also +// many video renderers will want to check formats as they are proposed by +// source filters. This class provides methods to check formats and only +// accept those video formats that can be efficiently drawn using GDI calls + +class CImageDisplay : public CCritSec +{ +protected: + + // This holds the display format; biSize should not be too big, so we can + // safely use the VIDEOINFO structure + VIDEOINFO m_Display; + + static DWORD CountSetBits(const DWORD Field); + static DWORD CountPrefixBits(const DWORD Field); + static BOOL CheckBitFields(const VIDEOINFO *pInput); + +public: + + // Constructor and destructor + + CImageDisplay(); + + // Used to manage BITMAPINFOHEADERs and the display format + + const VIDEOINFO *GetDisplayFormat(); + HRESULT RefreshDisplayType(__in_opt LPSTR szDeviceName); + static BOOL CheckHeaderValidity(const VIDEOINFO *pInput); + static BOOL CheckPaletteHeader(const VIDEOINFO *pInput); + BOOL IsPalettised(); + WORD GetDisplayDepth(); + + // Provide simple video format type checking + + HRESULT CheckMediaType(const CMediaType *pmtIn); + HRESULT CheckVideoType(const VIDEOINFO *pInput); + HRESULT UpdateFormat(__inout VIDEOINFO *pVideoInfo); + const DWORD *GetBitMasks(const VIDEOINFO *pVideoInfo); + + BOOL GetColourMask(__out DWORD *pMaskRed, + __out DWORD *pMaskGreen, + __out DWORD *pMaskBlue); +}; + +// Convert a FORMAT_VideoInfo to FORMAT_VideoInfo2 +STDAPI ConvertVideoInfoToVideoInfo2(__inout AM_MEDIA_TYPE *pmt); + +// Check a media type containing VIDEOINFOHEADER +STDAPI CheckVideoInfoType(const AM_MEDIA_TYPE *pmt); + +// Check a media type containing VIDEOINFOHEADER +STDAPI CheckVideoInfo2Type(const AM_MEDIA_TYPE *pmt); + +#endif // __WINUTIL__ + +//------------------------------------------------------------------------------ +// File: DlleEntry.cpp +// +// Desc: DirectShow base classes - implements classes used to support dll +// entry points for COM objects. +// +// Copyright (c) 1992-2001 Microsoft Corporation. All rights reserved. +//------------------------------------------------------------------------------ + +extern CFactoryTemplate g_Templates[]; +extern int g_cTemplates; + +HINSTANCE g_hInst; +DWORD g_amPlatform; // VER_PLATFORM_WIN32_WINDOWS etc... (from GetVersionEx) +OSVERSIONINFO g_osInfo; + +// +// an instance of this is created by the DLLGetClassObject entrypoint +// it uses the CFactoryTemplate object it is given to support the +// IClassFactory interface + +class CClassFactory : public IClassFactory, public CBaseObject +{ + +private: + const CFactoryTemplate *const m_pTemplate; + + ULONG m_cRef; + + static int m_cLocked; +public: + CClassFactory(const CFactoryTemplate *); + + // IUnknown + STDMETHODIMP QueryInterface(REFIID riid, __deref_out void ** ppv); + STDMETHODIMP_(ULONG)AddRef(); + STDMETHODIMP_(ULONG)Release(); + + // IClassFactory + STDMETHODIMP CreateInstance(LPUNKNOWN pUnkOuter, REFIID riid, __deref_out void **pv); + STDMETHODIMP LockServer(BOOL fLock); + + // allow DLLGetClassObject to know about global server lock status + static BOOL IsLocked() { + return (m_cLocked > 0); + }; +}; + +// process-wide dll locked state +int CClassFactory::m_cLocked = 0; + +CClassFactory::CClassFactory(const CFactoryTemplate *pTemplate) +: CBaseObject(NAME("Class Factory")) +, m_cRef(0) +, m_pTemplate(pTemplate) +{ +} + + +STDMETHODIMP +CClassFactory::QueryInterface(REFIID riid,__deref_out void **ppv) +{ + CheckPointer(ppv,E_POINTER) + ValidateReadWritePtr(ppv,sizeof(PVOID)); + *ppv = NULL; + + // any interface on this object is the object pointer. + if ((riid == IID_IUnknown) || (riid == IID_IClassFactory)) { + *ppv = (LPVOID) this; + // AddRef returned interface pointer + ((LPUNKNOWN) *ppv)->AddRef(); + return NOERROR; + } + + return ResultFromScode(E_NOINTERFACE); +} + + +STDMETHODIMP_(ULONG) +CClassFactory::AddRef() +{ + return ++m_cRef; +} + +STDMETHODIMP_(ULONG) +CClassFactory::Release() +{ + LONG lRef = InterlockedDecrement((volatile LONG *)&m_cRef); + if (lRef == 0) { + delete this; + return 0; + } else { + return lRef; + } +} + +STDMETHODIMP +CClassFactory::CreateInstance( + LPUNKNOWN pUnkOuter, + REFIID riid, + __deref_out void **pv) +{ + CheckPointer(pv,E_POINTER) + ValidateReadWritePtr(pv,sizeof(void *)); + *pv = NULL; + + /* Enforce the normal OLE rules regarding interfaces and delegation */ + + if (pUnkOuter != NULL) { + if (IsEqualIID(riid,IID_IUnknown) == FALSE) { + *pv = NULL; + return ResultFromScode(E_NOINTERFACE); + } + } + + /* Create the new object through the derived class's create function */ + + HRESULT hr = NOERROR; +#ifndef STREAMS_PROVIDE_CUSTOM_FACTORY + CUnknown *pObj = m_pTemplate->CreateInstance(pUnkOuter, &hr); +#else + CUnknown *CustomCreateInstance(int FactoryType, LPUNKNOWN pUnkOuter, HRESULT* hr); + CUnknown *pObj = CustomCreateInstance((int)(m_pTemplate - ((CFactoryTemplate*)NULL)), pUnkOuter, &hr); +#endif + + if (pObj == NULL) { + *pv = NULL; + if (SUCCEEDED(hr)) { + hr = E_OUTOFMEMORY; + } + return hr; + } + + /* Delete the object if we got a construction error */ + + if (FAILED(hr)) { + delete pObj; + *pv = NULL; + return hr; + } + + /* Get a reference counted interface on the object */ + + /* We wrap the non-delegating QI with NDAddRef & NDRelease. */ + /* This protects any outer object from being prematurely */ + /* released by an inner object that may have to be created */ + /* in order to supply the requested interface. */ + pObj->NonDelegatingAddRef(); + hr = pObj->NonDelegatingQueryInterface(riid, pv); + pObj->NonDelegatingRelease(); + /* Note that if NonDelegatingQueryInterface fails, it will */ + /* not increment the ref count, so the NonDelegatingRelease */ + /* will drop the ref back to zero and the object will "self-*/ + /* destruct". Hence we don't need additional tidy-up code */ + /* to cope with NonDelegatingQueryInterface failing. */ + + if (SUCCEEDED(hr)) { + ASSERT(*pv); + } + + return hr; +} + +STDMETHODIMP +CClassFactory::LockServer(BOOL fLock) +{ + if (fLock) { + m_cLocked++; + } else { + m_cLocked--; + } + return NOERROR; +} + + +// --- COM entrypoints ----------------------------------------- + +//called by COM to get the class factory object for a given class +__control_entrypoint(DllExport) STDAPI +DllGetClassObject( + __in REFCLSID rClsID, + __in REFIID riid, + __deref_out void **pv) +{ + *pv = NULL; + if (!(riid == IID_IUnknown) && !(riid == IID_IClassFactory)) { + return E_NOINTERFACE; + } + +#ifndef STREAMS_PROVIDE_CUSTOM_FACTORY + // traverse the array of templates looking for one with this + // class id + for (int i = 0; i < g_cTemplates; i++) { + const CFactoryTemplate * pT = &g_Templates[i]; + if (pT->IsClassID(rClsID)) { +#else + { + int CustomGetFactoryType(const IID &rClsID); + const CFactoryTemplate * pT = ((CFactoryTemplate*)NULL) + CustomGetFactoryType(rClsID); + if (pT) { +#endif + // found a template - make a class factory based on this + // template + + *pv = (LPVOID) (LPUNKNOWN) new CClassFactory(pT); + if (*pv == NULL) { + return E_OUTOFMEMORY; + } + ((LPUNKNOWN)*pv)->AddRef(); + return NOERROR; + } + } + return CLASS_E_CLASSNOTAVAILABLE; +} + +// +// Call any initialization routines +// +void +DllInitClasses(BOOL bLoading) +{ +#ifndef STREAMS_PROVIDE_CUSTOM_FACTORY + int i; + + // traverse the array of templates calling the init routine + // if they have one + for (i = 0; i < g_cTemplates; i++) { + const CFactoryTemplate * pT = &g_Templates[i]; + if (pT->m_lpfnInit != NULL) { + (*pT->m_lpfnInit)(bLoading, pT->m_ClsID); + } + } + +#endif +} + +// called by COM to determine if this dll can be unloaded +// return ok unless there are outstanding objects or a lock requested +// by IClassFactory::LockServer +// +// CClassFactory has a static function that can tell us about the locks, +// and CCOMObject has a static function that can tell us about the active +// object count +STDAPI +DllCanUnloadNow() +{ + DbgLog((LOG_MEMORY,2,TEXT("DLLCanUnloadNow called - IsLocked = %d, Active objects = %d"), + CClassFactory::IsLocked(), + CBaseObject::ObjectsActive())); + + if (CClassFactory::IsLocked() || CBaseObject::ObjectsActive()) { + return S_FALSE; + } else { + return S_OK; + } +} + + +// --- standard WIN32 entrypoints -------------------------------------- + + +extern "C" void __cdecl __security_init_cookie(void); +extern "C" BOOL WINAPI _DllEntryPoint(HINSTANCE, ULONG, __inout_opt LPVOID); +#pragma comment(linker, "/merge:.CRT=.rdata") + +extern "C" +DECLSPEC_NOINLINE +BOOL +WINAPI +DllEntryPoint( + HINSTANCE hInstance, + ULONG ulReason, + __inout_opt LPVOID pv + ) +{ + if ( ulReason == DLL_PROCESS_ATTACH ) { + // Must happen before any other code is executed. Thankfully - it's re-entrant + __security_init_cookie(); + } + return _DllEntryPoint(hInstance, ulReason, pv); +} + + +DECLSPEC_NOINLINE +BOOL +WINAPI +_DllEntryPoint( + HINSTANCE hInstance, + ULONG ulReason, + __inout_opt LPVOID pv + ) +{ +#ifdef DEBUG + extern bool g_fDbgInDllEntryPoint; + g_fDbgInDllEntryPoint = true; +#endif + + switch (ulReason) + { + + case DLL_PROCESS_ATTACH: + DisableThreadLibraryCalls(hInstance); + DbgInitialise(hInstance); + + { + // The platform identifier is used to work out whether + // full unicode support is available or not. Hence the + // default will be the lowest common denominator - i.e. N/A + g_amPlatform = VER_PLATFORM_WIN32_WINDOWS; // win95 assumed in case GetVersionEx fails + + g_osInfo.dwOSVersionInfoSize = sizeof(g_osInfo); +#pragma warning(push) +#pragma warning(disable: 4996) //warning C4996: 'GetVersionExA': was declared deprecated + if (GetVersionEx(&g_osInfo)) { +#pragma warning(pop) + g_amPlatform = g_osInfo.dwPlatformId; + } else { + DbgLog((LOG_ERROR, 1, TEXT("Failed to get the OS platform, assuming Win95"))); + } + } + + g_hInst = hInstance; + DllInitClasses(TRUE); + break; + + case DLL_PROCESS_DETACH: + DllInitClasses(FALSE); + +#ifdef DEBUG + if (CBaseObject::ObjectsActive()) { + DbgSetModuleLevel(LOG_MEMORY, 2); + TCHAR szInfo[512]; + extern TCHAR m_ModuleName[]; // Cut down module name + + TCHAR FullName[_MAX_PATH]; // Load the full path and module name + TCHAR *pName; // Searches from the end for a backslash + + GetModuleFileName(NULL,FullName,_MAX_PATH); + pName = _tcsrchr(FullName,'\\'); + if (pName == NULL) { + pName = FullName; + } else { + pName++; + } + + (void)StringCchPrintf(szInfo, NUMELMS(szInfo), TEXT("Executable: %s Pid %x Tid %x. "), + pName, GetCurrentProcessId(), GetCurrentThreadId()); + + (void)StringCchPrintf(szInfo+lstrlen(szInfo), NUMELMS(szInfo) - lstrlen(szInfo), TEXT("Module %s, %d objects left active!"), + m_ModuleName, CBaseObject::ObjectsActive()); + DbgAssert(szInfo, TEXT(__FILE__),__LINE__); + + // If running remotely wait for the Assert to be acknowledged + // before dumping out the object register + DbgDumpObjectRegister(); + } + DbgTerminate(); +#endif + break; + } + +#ifdef DEBUG + g_fDbgInDllEntryPoint = false; +#endif + return TRUE; +} + +//------------------------------------------------------------------------------ +// File: WXDebug.cpp +// +// Desc: DirectShow base classes - implements ActiveX system debugging +// facilities. +// +// Copyright (c) 1992-2001 Microsoft Corporation. All rights reserved. +//------------------------------------------------------------------------------ + +#ifdef DEBUG +static void DisplayBITMAPINFO(const BITMAPINFOHEADER* pbmi); +static void DisplayRECT(LPCTSTR szLabel, const RECT& rc); + +// The Win32 wsprintf() function writes a maximum of 1024 characters to it's output buffer. +// See the documentation for wsprintf()'s lpOut parameter for more information. +const INT iDEBUGINFO = 1024; // Used to format strings + +/* For every module and executable we store a debugging level for each of + the five categories (eg LOG_ERROR and LOG_TIMING). This makes it easy + to isolate and debug individual modules without seeing everybody elses + spurious debug output. The keys are stored in the registry under the + HKEY_LOCAL_MACHINE\SOFTWARE\Debug\\ key values + NOTE these must be in the same order as their enumeration definition */ + +const LPCTSTR pKeyNames[] = { + TEXT("TIMING"), // Timing and performance measurements + TEXT("TRACE"), // General step point call tracing + TEXT("MEMORY"), // Memory and object allocation/destruction + TEXT("LOCKING"), // Locking/unlocking of critical sections + TEXT("ERROR"), // Debug error notification + TEXT("CUSTOM1"), + TEXT("CUSTOM2"), + TEXT("CUSTOM3"), + TEXT("CUSTOM4"), + TEXT("CUSTOM5") + }; + +const TCHAR CAutoTrace::_szEntering[] = TEXT("->: %s"); +const TCHAR CAutoTrace::_szLeaving[] = TEXT("<-: %s"); + +const INT iMAXLEVELS = NUMELMS(pKeyNames); // Maximum debug categories + +HINSTANCE m_hInst; // Module instance handle +TCHAR m_ModuleName[iDEBUGINFO]; // Cut down module name +DWORD m_Levels[iMAXLEVELS]; // Debug level per category +CRITICAL_SECTION m_CSDebug; // Controls access to list +DWORD m_dwNextCookie; // Next active object ID +ObjectDesc *pListHead = NULL; // First active object +DWORD m_dwObjectCount; // Active object count +BOOL m_bInit = FALSE; // Have we been initialised +HANDLE m_hOutput = INVALID_HANDLE_VALUE; // Optional output written here +DWORD dwWaitTimeout = INFINITE; // Default timeout value +DWORD dwTimeOffset; // Time of first DbgLog call +bool g_fUseKASSERT = false; // don't create messagebox +bool g_fDbgInDllEntryPoint = false; +bool g_fAutoRefreshLevels = false; + +LPCTSTR pBaseKey = TEXT("SOFTWARE\\Microsoft\\DirectShow\\Debug"); +LPCTSTR pGlobalKey = TEXT("GLOBAL"); +static CHAR *pUnknownName = "UNKNOWN"; + +LPCTSTR TimeoutName = TEXT("TIMEOUT"); + +/* This sets the instance handle that the debug library uses to find + the module's file name from the Win32 GetModuleFileName function */ + +void WINAPI DbgInitialise(HINSTANCE hInst) +{ + InitializeCriticalSection(&m_CSDebug); + m_bInit = TRUE; + + m_hInst = hInst; + DbgInitModuleName(); + if (GetProfileInt(m_ModuleName, TEXT("BreakOnLoad"), 0)) + DebugBreak(); + DbgInitModuleSettings(false); + DbgInitGlobalSettings(true); + dwTimeOffset = timeGetTime(); +} + + +/* This is called to clear up any resources the debug library uses - at the + moment we delete our critical section and the object list. The values we + retrieve from the registry are all done during initialisation but we don't + go looking for update notifications while we are running, if the values + are changed then the application has to be restarted to pick them up */ + +void WINAPI DbgTerminate() +{ + if (m_hOutput != INVALID_HANDLE_VALUE) { + EXECUTE_ASSERT(CloseHandle(m_hOutput)); + m_hOutput = INVALID_HANDLE_VALUE; + } + DeleteCriticalSection(&m_CSDebug); + m_bInit = FALSE; +} + + +/* This is called by DbgInitLogLevels to read the debug settings + for each logging category for this module from the registry */ + +void WINAPI DbgInitKeyLevels(HKEY hKey, bool fTakeMax) +{ + LONG lReturn; // Create key return value + LONG lKeyPos; // Current key category + DWORD dwKeySize; // Size of the key value + DWORD dwKeyType; // Receives it's type + DWORD dwKeyValue; // This fields value + + /* Try and read a value for each key position in turn */ + for (lKeyPos = 0;lKeyPos < iMAXLEVELS;lKeyPos++) { + + dwKeySize = sizeof(DWORD); + lReturn = RegQueryValueEx( + hKey, // Handle to an open key + pKeyNames[lKeyPos], // Subkey name derivation + NULL, // Reserved field + &dwKeyType, // Returns the field type + (LPBYTE) &dwKeyValue, // Returns the field's value + &dwKeySize ); // Number of bytes transferred + + /* If either the key was not available or it was not a DWORD value + then we ensure only the high priority debug logging is output + but we try and update the field to a zero filled DWORD value */ + + if (lReturn != ERROR_SUCCESS || dwKeyType != REG_DWORD) { + + dwKeyValue = 0; + lReturn = RegSetValueEx( + hKey, // Handle of an open key + pKeyNames[lKeyPos], // Address of subkey name + (DWORD) 0, // Reserved field + REG_DWORD, // Type of the key field + (PBYTE) &dwKeyValue, // Value for the field + sizeof(DWORD)); // Size of the field buffer + + if (lReturn != ERROR_SUCCESS) { + DbgLog((LOG_ERROR,1,TEXT("Could not create subkey %s"),pKeyNames[lKeyPos])); + dwKeyValue = 0; + } + } + if(fTakeMax) + { + m_Levels[lKeyPos] = max(dwKeyValue,m_Levels[lKeyPos]); + } + else + { + if((m_Levels[lKeyPos] & LOG_FORCIBLY_SET) == 0) { + m_Levels[lKeyPos] = dwKeyValue; + } + } + } + + /* Read the timeout value for catching hangs */ + dwKeySize = sizeof(DWORD); + lReturn = RegQueryValueEx( + hKey, // Handle to an open key + TimeoutName, // Subkey name derivation + NULL, // Reserved field + &dwKeyType, // Returns the field type + (LPBYTE) &dwWaitTimeout, // Returns the field's value + &dwKeySize ); // Number of bytes transferred + + /* If either the key was not available or it was not a DWORD value + then we ensure only the high priority debug logging is output + but we try and update the field to a zero filled DWORD value */ + + if (lReturn != ERROR_SUCCESS || dwKeyType != REG_DWORD) { + + dwWaitTimeout = INFINITE; + lReturn = RegSetValueEx( + hKey, // Handle of an open key + TimeoutName, // Address of subkey name + (DWORD) 0, // Reserved field + REG_DWORD, // Type of the key field + (PBYTE) &dwWaitTimeout, // Value for the field + sizeof(DWORD)); // Size of the field buffer + + if (lReturn != ERROR_SUCCESS) { + DbgLog((LOG_ERROR,1,TEXT("Could not create subkey %s"),pKeyNames[lKeyPos])); + dwWaitTimeout = INFINITE; + } + } +} + +void WINAPI DbgOutString(LPCTSTR psz) +{ + if (m_hOutput != INVALID_HANDLE_VALUE) { + UINT cb = lstrlen(psz); + DWORD dw; +#ifdef UNICODE + CHAR szDest[2048]; + WideCharToMultiByte(CP_ACP, 0, psz, -1, szDest, NUMELMS(szDest), 0, 0); + WriteFile (m_hOutput, szDest, cb, &dw, NULL); +#else + WriteFile (m_hOutput, psz, cb, &dw, NULL); +#endif + } else { + OutputDebugString (psz); + } +} + + + + +HRESULT DbgUniqueProcessName(LPCTSTR inName, LPTSTR outName) +{ + HRESULT hr = S_OK; + const TCHAR *pIn = inName; + int dotPos = -1; + + //scan the input and record the last '.' position + while (*pIn && (pIn - inName) < MAX_PATH) + { + if ( TEXT('.') == *pIn ) + dotPos = (int)(pIn-inName); + ++pIn; + } + + if (*pIn) //input should be zero-terminated within MAX_PATH + return E_INVALIDARG; + + DWORD dwProcessId = GetCurrentProcessId(); + + if (dotPos < 0) + { + //no extension in the input, appending process id to the input + hr = StringCchPrintf(outName, MAX_PATH, TEXT("%s_%d"), inName, dwProcessId); + } + else + { + TCHAR pathAndBasename[MAX_PATH] = {0}; + + //there's an extension - zero-terminate the path and basename first by copying + hr = StringCchCopyN(pathAndBasename, MAX_PATH, inName, (size_t)dotPos); + + //re-combine path, basename and extension with processId appended to a basename + if (SUCCEEDED(hr)) + hr = StringCchPrintf(outName, MAX_PATH, TEXT("%s_%d%s"), pathAndBasename, dwProcessId, inName + dotPos); + } + + return hr; +} + + +/* Called by DbgInitGlobalSettings to setup alternate logging destinations + */ + +void WINAPI DbgInitLogTo ( + HKEY hKey) +{ + LONG lReturn; + DWORD dwKeyType; + DWORD dwKeySize; + TCHAR szFile[MAX_PATH] = {0}; + static const TCHAR cszKey[] = TEXT("LogToFile"); + + dwKeySize = MAX_PATH; + lReturn = RegQueryValueEx( + hKey, // Handle to an open key + cszKey, // Subkey name derivation + NULL, // Reserved field + &dwKeyType, // Returns the field type + (LPBYTE) szFile, // Returns the field's value + &dwKeySize); // Number of bytes transferred + + // create an empty key if it does not already exist + // + if (lReturn != ERROR_SUCCESS || dwKeyType != REG_SZ) + { + dwKeySize = sizeof(TCHAR); + lReturn = RegSetValueEx( + hKey, // Handle of an open key + cszKey, // Address of subkey name + (DWORD) 0, // Reserved field + REG_SZ, // Type of the key field + (PBYTE)szFile, // Value for the field + dwKeySize); // Size of the field buffer + } + + // if an output-to was specified. try to open it. + // + if (m_hOutput != INVALID_HANDLE_VALUE) { + EXECUTE_ASSERT(CloseHandle (m_hOutput)); + m_hOutput = INVALID_HANDLE_VALUE; + } + if (szFile[0] != 0) + { + if (!lstrcmpi(szFile, TEXT("Console"))) { + m_hOutput = GetStdHandle (STD_OUTPUT_HANDLE); + if (m_hOutput == INVALID_HANDLE_VALUE) { + AllocConsole (); + m_hOutput = GetStdHandle (STD_OUTPUT_HANDLE); + } + SetConsoleTitle (TEXT("ActiveX Debug Output")); + } else if (szFile[0] && + lstrcmpi(szFile, TEXT("Debug")) && + lstrcmpi(szFile, TEXT("Debugger")) && + lstrcmpi(szFile, TEXT("Deb"))) + { + m_hOutput = CreateFile(szFile, GENERIC_WRITE, + FILE_SHARE_READ, + NULL, OPEN_ALWAYS, + FILE_ATTRIBUTE_NORMAL, + NULL); + + if (INVALID_HANDLE_VALUE == m_hOutput && + GetLastError() == ERROR_SHARING_VIOLATION) + { + TCHAR uniqueName[MAX_PATH] = {0}; + if (SUCCEEDED(DbgUniqueProcessName(szFile, uniqueName))) + { + m_hOutput = CreateFile(uniqueName, GENERIC_WRITE, + FILE_SHARE_READ, + NULL, OPEN_ALWAYS, + FILE_ATTRIBUTE_NORMAL, + NULL); + } + } + + if (INVALID_HANDLE_VALUE != m_hOutput) + { + static const TCHAR cszBar[] = TEXT("\r\n\r\n=====DbgInitialize()=====\r\n\r\n"); + SetFilePointer (m_hOutput, 0, NULL, FILE_END); + DbgOutString (cszBar); + } + } + } +} + + + +/* This is called by DbgInitLogLevels to read the global debug settings for + each logging category for this module from the registry. Normally each + module has it's own values set for it's different debug categories but + setting the global SOFTWARE\Debug\Global applies them to ALL modules */ + +void WINAPI DbgInitGlobalSettings(bool fTakeMax) +{ + LONG lReturn; // Create key return value + TCHAR szInfo[iDEBUGINFO]; // Constructs key names + HKEY hGlobalKey; // Global override key + + /* Construct the global base key name */ + (void)StringCchPrintf(szInfo,NUMELMS(szInfo),TEXT("%s\\%s"),pBaseKey,pGlobalKey); + + /* Create or open the key for this module */ + lReturn = RegCreateKeyEx(HKEY_LOCAL_MACHINE, // Handle of an open key + szInfo, // Address of subkey name + (DWORD) 0, // Reserved value + NULL, // Address of class name + (DWORD) 0, // Special options flags + GENERIC_READ | GENERIC_WRITE, // Desired security access + NULL, // Key security descriptor + &hGlobalKey, // Opened handle buffer + NULL); // What really happened + + if (lReturn != ERROR_SUCCESS) { + lReturn = RegCreateKeyEx(HKEY_LOCAL_MACHINE, // Handle of an open key + szInfo, // Address of subkey name + (DWORD) 0, // Reserved value + NULL, // Address of class name + (DWORD) 0, // Special options flags + GENERIC_READ, // Desired security access + NULL, // Key security descriptor + &hGlobalKey, // Opened handle buffer + NULL); // What really happened + if (lReturn != ERROR_SUCCESS) { + DbgLog((LOG_ERROR,1,TEXT("Could not access GLOBAL module key"))); + // CPlusSharp: in the original file, this "return" was after this if statement + // => because HKEY_LOCAL_MACHINE is readonly since Vista, if we start without admin-rights + // the Log-Levels would not be loaded! + // I don't know if this was on purpose, but then the line above make no seens! + return; + } + } + + DbgInitKeyLevels(hGlobalKey, fTakeMax); + RegCloseKey(hGlobalKey); +} + + +/* This sets the debugging log levels for the different categories. We start + by opening (or creating if not already available) the SOFTWARE\Debug key + that all these settings live under. We then look at the global values + set under SOFTWARE\Debug\Global which apply on top of the individual + module settings. We then load the individual module registry settings */ + +void WINAPI DbgInitModuleSettings(bool fTakeMax) +{ + LONG lReturn; // Create key return value + TCHAR szInfo[iDEBUGINFO]; // Constructs key names + HKEY hModuleKey; // Module key handle + + /* Construct the base key name */ + (void)StringCchPrintf(szInfo,NUMELMS(szInfo),TEXT("%s\\%s"),pBaseKey,m_ModuleName); + + /* Create or open the key for this module */ + lReturn = RegCreateKeyEx(HKEY_LOCAL_MACHINE, // Handle of an open key + szInfo, // Address of subkey name + (DWORD) 0, // Reserved value + NULL, // Address of class name + (DWORD) 0, // Special options flags + GENERIC_READ | GENERIC_WRITE, // Desired security access + NULL, // Key security descriptor + &hModuleKey, // Opened handle buffer + NULL); // What really happened + + if (lReturn != ERROR_SUCCESS) { + lReturn = RegCreateKeyEx(HKEY_LOCAL_MACHINE, // Handle of an open key + szInfo, // Address of subkey name + (DWORD) 0, // Reserved value + NULL, // Address of class name + (DWORD) 0, // Special options flags + GENERIC_READ, // Desired security access + NULL, // Key security descriptor + &hModuleKey, // Opened handle buffer + NULL); // What really happened + if (lReturn != ERROR_SUCCESS) { + DbgLog((LOG_ERROR,1,TEXT("Could not access module key"))); + // CPlusSharp: in the original file, this "return" was after this if statement + // => because HKEY_LOCAL_MACHINE is readonly since Vista, if we start without admin-rights + // the Log-Levels would not be loaded! + // I don't know if this was on purpose, but then the line above make no seens! + return; + } + } + + DbgInitLogTo(hModuleKey); + DbgInitKeyLevels(hModuleKey, fTakeMax); + RegCloseKey(hModuleKey); +} + + +/* Initialise the module file name */ + +void WINAPI DbgInitModuleName() +{ + TCHAR FullName[iDEBUGINFO]; // Load the full path and module name + LPTSTR pName; // Searches from the end for a backslash + + GetModuleFileName(m_hInst,FullName,iDEBUGINFO); + pName = _tcsrchr(FullName,'\\'); + if (pName == NULL) { + pName = FullName; + } else { + pName++; + } + (void)StringCchCopy(m_ModuleName,NUMELMS(m_ModuleName), pName); +} + +struct MsgBoxMsg +{ + HWND hwnd; + LPCTSTR szTitle; + LPCTSTR szMessage; + DWORD dwFlags; + INT iResult; +}; + +// +// create a thread to call MessageBox(). calling MessageBox() on +// random threads at bad times can confuse the host (eg IE). +// +DWORD WINAPI MsgBoxThread( + __inout LPVOID lpParameter // thread data + ) +{ + MsgBoxMsg *pmsg = (MsgBoxMsg *)lpParameter; + pmsg->iResult = MessageBox( + pmsg->hwnd, + pmsg->szTitle, + pmsg->szMessage, + pmsg->dwFlags); + + return 0; +} + +INT MessageBoxOtherThread( + HWND hwnd, + LPCTSTR szTitle, + LPCTSTR szMessage, + DWORD dwFlags) +{ + if(g_fDbgInDllEntryPoint) + { + // can't wait on another thread because we have the loader + // lock held in the dll entry point. + // This can crash sometimes so just skip it + // return MessageBox(hwnd, szTitle, szMessage, dwFlags); + return IDCANCEL; + } + else + { + MsgBoxMsg msg = {hwnd, szTitle, szMessage, dwFlags, 0}; + DWORD dwid; + HANDLE hThread = CreateThread( + 0, // security + 0, // stack size + MsgBoxThread, + (void *)&msg, // arg + 0, // flags + &dwid); + if(hThread) + { + WaitForSingleObject(hThread, INFINITE); + CloseHandle(hThread); + return msg.iResult; + } + + // break into debugger on failure. + return IDCANCEL; + } +} + +/* Displays a message box if the condition evaluated to FALSE */ + +void WINAPI DbgAssert(LPCTSTR pCondition,LPCTSTR pFileName,INT iLine) +{ + if(g_fUseKASSERT) + { + DbgKernelAssert(pCondition, pFileName, iLine); + } + else + { + + TCHAR szInfo[iDEBUGINFO]; + + (void)StringCchPrintf(szInfo, NUMELMS(szInfo),TEXT("%s \nAt line %d of %s\nContinue? (Cancel to debug)"), + pCondition, iLine, pFileName); + + INT MsgId = MessageBoxOtherThread(NULL,szInfo,TEXT("ASSERT Failed"), + MB_SYSTEMMODAL | + MB_ICONHAND | + MB_YESNOCANCEL | + MB_SETFOREGROUND); + switch (MsgId) + { + case IDNO: /* Kill the application */ + + FatalAppExit(FALSE, TEXT("Application terminated")); + break; + + case IDCANCEL: /* Break into the debugger */ + + DebugBreak(); + break; + + case IDYES: /* Ignore assertion continue execution */ + break; + } + } +} + +/* Displays a message box at a break point */ + +void WINAPI DbgBreakPoint(LPCTSTR pCondition,LPCTSTR pFileName,INT iLine) +{ + if(g_fUseKASSERT) + { + DbgKernelAssert(pCondition, pFileName, iLine); + } + else + { + TCHAR szInfo[iDEBUGINFO]; + + (void)StringCchPrintf(szInfo, NUMELMS(szInfo),TEXT("%s \nAt line %d of %s\nContinue? (Cancel to debug)"), + pCondition, iLine, pFileName); + + INT MsgId = MessageBoxOtherThread(NULL,szInfo,TEXT("Hard coded break point"), + MB_SYSTEMMODAL | + MB_ICONHAND | + MB_YESNOCANCEL | + MB_SETFOREGROUND); + switch (MsgId) + { + case IDNO: /* Kill the application */ + + FatalAppExit(FALSE, TEXT("Application terminated")); + break; + + case IDCANCEL: /* Break into the debugger */ + + DebugBreak(); + break; + + case IDYES: /* Ignore break point continue execution */ + break; + } + } +} + +void WINAPI DbgBreakPoint(LPCTSTR pFileName,INT iLine,__format_string LPCTSTR szFormatString,...) +{ + // A debug break point message can have at most 2000 characters if + // ANSI or UNICODE characters are being used. A debug break point message + // can have between 1000 and 2000 double byte characters in it. If a + // particular message needs more characters, then the value of this constant + // should be increased. + const DWORD MAX_BREAK_POINT_MESSAGE_SIZE = 2000; + + TCHAR szBreakPointMessage[MAX_BREAK_POINT_MESSAGE_SIZE]; + + va_list va; + va_start( va, szFormatString ); + + HRESULT hr = StringCchVPrintf( szBreakPointMessage, NUMELMS(szBreakPointMessage), szFormatString, va ); + + va_end(va); + + if( FAILED(hr) ) { + DbgBreak( "ERROR in DbgBreakPoint(). The variable length debug message could not be displayed because StringCchVPrintf() failed." ); + return; + } + + ::DbgBreakPoint( szBreakPointMessage, pFileName, iLine ); +} + + +/* When we initialised the library we stored in the m_Levels array the current + debug output level for this module for each of the five categories. When + some debug logging is sent to us it can be sent with a combination of the + categories (if it is applicable to many for example) in which case we map + the type's categories into their current debug levels and see if any of + them can be accepted. The function looks at each bit position in turn from + the input type field and then compares it's debug level with the modules. + + A level of 0 means that output is always sent to the debugger. This is + due to producing output if the input level is <= m_Levels. +*/ + + +BOOL WINAPI DbgCheckModuleLevel(DWORD Type,DWORD Level) +{ + if(g_fAutoRefreshLevels) + { + // re-read the registry every second. We cannot use RegNotify() to + // notice registry changes because it's not available on win9x. + static DWORD g_dwLastRefresh = 0; + DWORD dwTime = timeGetTime(); + if(dwTime - g_dwLastRefresh > 1000) { + g_dwLastRefresh = dwTime; + + // there's a race condition: multiple threads could update the + // values. plus read and write not synchronized. no harm + // though. + DbgInitModuleSettings(false); + } + } + + + DWORD Mask = 0x01; + + // If no valid bits are set return FALSE + if ((Type & ((1<m_szName = szObjectName; + pObject->m_wszName = wszObjectName; + pObject->m_dwCookie = ++m_dwNextCookie; + pObject->m_pNext = pListHead; + + pListHead = pObject; + m_dwObjectCount++; + + DWORD ObjectCookie = pObject->m_dwCookie; + ASSERT(ObjectCookie); + + if(wszObjectName) { + DbgLog((LOG_MEMORY,2,TEXT("Object created %d (%ls) %d Active"), + pObject->m_dwCookie, wszObjectName, m_dwObjectCount)); + } else { + DbgLog((LOG_MEMORY,2,TEXT("Object created %d (%hs) %d Active"), + pObject->m_dwCookie, szObjectName, m_dwObjectCount)); + } + + LeaveCriticalSection(&m_CSDebug); + return ObjectCookie; +} + + +/* This is called by the CBaseObject destructor when an object is about to be + destroyed, we are passed the cookie we returned during construction that + identifies this object. We scan the object list for a matching cookie and + remove the object if successful. We also update the active object count */ + +BOOL WINAPI DbgRegisterObjectDestruction(DWORD dwCookie) +{ + /* Grab the list critical section */ + EnterCriticalSection(&m_CSDebug); + + ObjectDesc *pObject = pListHead; + ObjectDesc *pPrevious = NULL; + + /* Scan the object list looking for a cookie match */ + + while (pObject) { + if (pObject->m_dwCookie == dwCookie) { + break; + } + pPrevious = pObject; + pObject = pObject->m_pNext; + } + + if (pObject == NULL) { + DbgBreak("Apparently destroying a bogus object"); + LeaveCriticalSection(&m_CSDebug); + return FALSE; + } + + /* Is the object at the head of the list */ + + if (pPrevious == NULL) { + pListHead = pObject->m_pNext; + } else { + pPrevious->m_pNext = pObject->m_pNext; + } + + /* Delete the object and update the housekeeping information */ + + m_dwObjectCount--; + + if(pObject->m_wszName) { + DbgLog((LOG_MEMORY,2,TEXT("Object destroyed %d (%ls) %d Active"), + pObject->m_dwCookie, pObject->m_wszName, m_dwObjectCount)); + } else { + DbgLog((LOG_MEMORY,2,TEXT("Object destroyed %d (%hs) %d Active"), + pObject->m_dwCookie, pObject->m_szName, m_dwObjectCount)); + } + + delete pObject; + LeaveCriticalSection(&m_CSDebug); + return TRUE; +} + + +/* This runs through the active object list displaying their details */ + +void WINAPI DbgDumpObjectRegister() +{ + TCHAR szInfo[iDEBUGINFO]; + + /* Grab the list critical section */ + + EnterCriticalSection(&m_CSDebug); + ObjectDesc *pObject = pListHead; + + /* Scan the object list displaying the name and cookie */ + + DbgLog((LOG_MEMORY,2,TEXT(""))); + DbgLog((LOG_MEMORY,2,TEXT(" ID Object Description"))); + DbgLog((LOG_MEMORY,2,TEXT(""))); + + while (pObject) { + if(pObject->m_wszName) { + (void)StringCchPrintf(szInfo,NUMELMS(szInfo),TEXT("%5d (%p) %30ls"),pObject->m_dwCookie, &pObject, pObject->m_wszName); + } else { + (void)StringCchPrintf(szInfo,NUMELMS(szInfo),TEXT("%5d (%p) %30hs"),pObject->m_dwCookie, &pObject, pObject->m_szName); + } + DbgLog((LOG_MEMORY,2,szInfo)); + pObject = pObject->m_pNext; + } + + (void)StringCchPrintf(szInfo,NUMELMS(szInfo),TEXT("Total object count %5d"),m_dwObjectCount); + DbgLog((LOG_MEMORY,2,TEXT(""))); + DbgLog((LOG_MEMORY,1,szInfo)); + LeaveCriticalSection(&m_CSDebug); +} + +/* Debug infinite wait stuff */ +DWORD WINAPI DbgWaitForSingleObject(HANDLE h) +{ + DWORD dwWaitResult; + do { + dwWaitResult = WaitForSingleObject(h, dwWaitTimeout); + ASSERT(dwWaitResult == WAIT_OBJECT_0); + } while (dwWaitResult == WAIT_TIMEOUT); + return dwWaitResult; +} +DWORD WINAPI DbgWaitForMultipleObjects(DWORD nCount, + __in_ecount(nCount) CONST HANDLE *lpHandles, + BOOL bWaitAll) +{ + DWORD dwWaitResult; + do { + dwWaitResult = WaitForMultipleObjects(nCount, + lpHandles, + bWaitAll, + dwWaitTimeout); + ASSERT((DWORD)(dwWaitResult - WAIT_OBJECT_0) < MAXIMUM_WAIT_OBJECTS); + } while (dwWaitResult == WAIT_TIMEOUT); + return dwWaitResult; +} + +void WINAPI DbgSetWaitTimeout(DWORD dwTimeout) +{ + dwWaitTimeout = dwTimeout; +} + +#endif /* DEBUG */ + +#ifdef _OBJBASE_H_ + + /* Stuff for printing out our GUID names */ + + GUID_STRING_ENTRY g_GuidNames[] = { + #define OUR_GUID_ENTRY(name, l, w1, w2, b1, b2, b3, b4, b5, b6, b7, b8) \ + { #name, { l, w1, w2, { b1, b2, b3, b4, b5, b6, b7, b8 } } }, + #include + }; + + CGuidNameList GuidNames; + int g_cGuidNames = sizeof(g_GuidNames) / sizeof(g_GuidNames[0]); + + char *CGuidNameList::operator [] (const GUID &guid) + { + for (int i = 0; i < g_cGuidNames; i++) { + if (g_GuidNames[i].guid == guid) { + return g_GuidNames[i].szName; + } + } + if (guid == GUID_NULL) { + return "GUID_NULL"; + } + + // !!! add something to print FOURCC guids? + + // shouldn't this print the hex CLSID? + return "Unknown GUID Name"; + } + +#endif /* _OBJBASE_H_ */ + +/* CDisp class - display our data types */ + +// clashes with REFERENCE_TIME +CDisp::CDisp(LONGLONG ll, int Format) +{ + // note: this could be combined with CDisp(LONGLONG) by + // introducing a default format of CDISP_REFTIME + LARGE_INTEGER li; + li.QuadPart = ll; + switch (Format) { + case CDISP_DEC: + { + TCHAR temp[20]; + int pos=20; + temp[--pos] = 0; + int digit; + // always output at least one digit + do { + // Get the rightmost digit - we only need the low word + digit = li.LowPart % 10; + li.QuadPart /= 10; + temp[--pos] = (TCHAR) digit+L'0'; + } while (li.QuadPart); + (void)StringCchCopy(m_String, NUMELMS(m_String), temp+pos); + break; + } + case CDISP_HEX: + default: + (void)StringCchPrintf(m_String, NUMELMS(m_String), TEXT("0x%X%8.8X"), li.HighPart, li.LowPart); + } +}; + +CDisp::CDisp(REFCLSID clsid) +{ +#ifdef UNICODE + (void)StringFromGUID2(clsid, m_String, NUMELMS(m_String)); +#else + WCHAR wszTemp[50]; + (void)StringFromGUID2(clsid, wszTemp, NUMELMS(wszTemp)); + (void)StringCchPrintf(m_String, NUMELMS(m_String), TEXT("%S"), wszTemp); +#endif +}; + +#ifdef __STREAMS__ +/* Display stuff */ +CDisp::CDisp(CRefTime llTime) +{ + LONGLONG llDiv; + if (llTime < 0) { + llTime = -llTime; + (void)StringCchCopy(m_String, NUMELMS(m_String), TEXT("-")); + } + llDiv = (LONGLONG)24 * 3600 * 10000000; + if (llTime >= llDiv) { + (void)StringCchPrintf(m_String + lstrlen(m_String), NUMELMS(m_String) - lstrlen(m_String), TEXT("%d days "), (LONG)(llTime / llDiv)); + llTime = llTime % llDiv; + } + llDiv = (LONGLONG)3600 * 10000000; + if (llTime >= llDiv) { + (void)StringCchPrintf(m_String + lstrlen(m_String), NUMELMS(m_String) - lstrlen(m_String), TEXT("%d hrs "), (LONG)(llTime / llDiv)); + llTime = llTime % llDiv; + } + llDiv = (LONGLONG)60 * 10000000; + if (llTime >= llDiv) { + (void)StringCchPrintf(m_String + lstrlen(m_String), NUMELMS(m_String) - lstrlen(m_String), TEXT("%d mins "), (LONG)(llTime / llDiv)); + llTime = llTime % llDiv; + } + (void)StringCchPrintf(m_String + lstrlen(m_String), NUMELMS(m_String) - lstrlen(m_String), TEXT("%d.%3.3d sec"), + (LONG)llTime / 10000000, + (LONG)((llTime % 10000000) / 10000)); +}; + +#endif // __STREAMS__ + + +/* Display pin */ +CDisp::CDisp(IPin *pPin) +{ + PIN_INFO pi; + TCHAR str[MAX_PIN_NAME]; + CLSID clsid; + + if (pPin) { + pPin->QueryPinInfo(&pi); + pi.pFilter->GetClassID(&clsid); + QueryPinInfoReleaseFilter(pi); + #ifndef UNICODE + WideCharToMultiByte(GetACP(), 0, pi.achName, lstrlenW(pi.achName) + 1, + str, MAX_PIN_NAME, NULL, NULL); + #else + (void)StringCchCopy(str, NUMELMS(str), pi.achName); + #endif + } else { + (void)StringCchCopy(str, NUMELMS(str), TEXT("NULL IPin")); + } + + m_pString = (PTCHAR) new TCHAR[lstrlen(str)+64]; + if (!m_pString) { + return; + } + + (void)StringCchPrintf(m_pString, lstrlen(str) + 64, TEXT("%hs(%s)"), GuidNames[clsid], str); +} + +/* Display filter or pin */ +CDisp::CDisp(IUnknown *pUnk) +{ + IBaseFilter *pf; + HRESULT hr = pUnk->QueryInterface(IID_IBaseFilter, (void **)&pf); + if(SUCCEEDED(hr)) + { + FILTER_INFO fi; + hr = pf->QueryFilterInfo(&fi); + if(SUCCEEDED(hr)) + { + QueryFilterInfoReleaseGraph(fi); + + size_t len = lstrlenW(fi.achName) + 1; + + m_pString = new TCHAR[len]; + if(m_pString) + { +#ifdef UNICODE + (void)StringCchCopy(m_pString, len, fi.achName); +#else + (void)StringCchPrintf(m_pString, len, "%S", fi.achName); +#endif + } + } + + pf->Release(); + + return; + } + + IPin *pp; + hr = pUnk->QueryInterface(IID_IPin, (void **)&pp); + if(SUCCEEDED(hr)) + { + CDisp::CDisp(pp); + pp->Release(); + return; + } +} + + +CDisp::~CDisp() +{ +} + +CDispBasic::~CDispBasic() +{ + if (m_pString != m_String) { + delete [] m_pString; + } +} + +CDisp::CDisp(double d) +{ + (void)StringCchPrintf(m_String, NUMELMS(m_String), TEXT("%d.%03d"), (int) d, (int) ((d - (int) d) * 1000)); +} + + +/* If built for debug this will display the media type details. We convert the + major and subtypes into strings and also ask the base classes for a string + description of the subtype, so MEDIASUBTYPE_RGB565 becomes RGB 565 16 bit + We also display the fields in the BITMAPINFOHEADER structure, this should + succeed as we do not accept input types unless the format is big enough */ + +#ifdef DEBUG +void WINAPI DisplayType(LPCTSTR label, const AM_MEDIA_TYPE *pmtIn) +{ + + /* Dump the GUID types and a short description */ + + DbgLog((LOG_TRACE,5,TEXT(""))); + DbgLog((LOG_TRACE,2,TEXT("%s M type %hs S type %hs"), label, + GuidNames[pmtIn->majortype], + GuidNames[pmtIn->subtype])); + DbgLog((LOG_TRACE,5,TEXT("Subtype description %s"),GetSubtypeName(&pmtIn->subtype))); + + /* Dump the generic media types */ + + if (pmtIn->bTemporalCompression) { + DbgLog((LOG_TRACE,5,TEXT("Temporally compressed"))); + } else { + DbgLog((LOG_TRACE,5,TEXT("Not temporally compressed"))); + } + + if (pmtIn->bFixedSizeSamples) { + DbgLog((LOG_TRACE,5,TEXT("Sample size %d"),pmtIn->lSampleSize)); + } else { + DbgLog((LOG_TRACE,5,TEXT("Variable size samples"))); + } + + if (pmtIn->formattype == FORMAT_VideoInfo) { + + VIDEOINFOHEADER *pVideoInfo = (VIDEOINFOHEADER *)pmtIn->pbFormat; + + DisplayRECT(TEXT("Source rectangle"),pVideoInfo->rcSource); + DisplayRECT(TEXT("Target rectangle"),pVideoInfo->rcTarget); + DisplayBITMAPINFO(HEADER(pmtIn->pbFormat)); + + } if (pmtIn->formattype == FORMAT_VideoInfo2) { + + VIDEOINFOHEADER2 *pVideoInfo2 = (VIDEOINFOHEADER2 *)pmtIn->pbFormat; + + DisplayRECT(TEXT("Source rectangle"),pVideoInfo2->rcSource); + DisplayRECT(TEXT("Target rectangle"),pVideoInfo2->rcTarget); + DbgLog((LOG_TRACE, 5, TEXT("Aspect Ratio: %d:%d"), + pVideoInfo2->dwPictAspectRatioX, + pVideoInfo2->dwPictAspectRatioY)); + DisplayBITMAPINFO(&pVideoInfo2->bmiHeader); + + } else if (pmtIn->majortype == MEDIATYPE_Audio) { + DbgLog((LOG_TRACE,2,TEXT(" Format type %hs"), + GuidNames[pmtIn->formattype])); + DbgLog((LOG_TRACE,2,TEXT(" Subtype %hs"), + GuidNames[pmtIn->subtype])); + + if ((pmtIn->subtype != MEDIASUBTYPE_MPEG1Packet) + && (pmtIn->cbFormat >= sizeof(PCMWAVEFORMAT))) + { + /* Dump the contents of the WAVEFORMATEX type-specific format structure */ + + WAVEFORMATEX *pwfx = (WAVEFORMATEX *) pmtIn->pbFormat; + DbgLog((LOG_TRACE,2,TEXT("wFormatTag %u"), pwfx->wFormatTag)); + DbgLog((LOG_TRACE,2,TEXT("nChannels %u"), pwfx->nChannels)); + DbgLog((LOG_TRACE,2,TEXT("nSamplesPerSec %lu"), pwfx->nSamplesPerSec)); + DbgLog((LOG_TRACE,2,TEXT("nAvgBytesPerSec %lu"), pwfx->nAvgBytesPerSec)); + DbgLog((LOG_TRACE,2,TEXT("nBlockAlign %u"), pwfx->nBlockAlign)); + DbgLog((LOG_TRACE,2,TEXT("wBitsPerSample %u"), pwfx->wBitsPerSample)); + + /* PCM uses a WAVEFORMAT and does not have the extra size field */ + + if (pmtIn->cbFormat >= sizeof(WAVEFORMATEX)) { + DbgLog((LOG_TRACE,2,TEXT("cbSize %u"), pwfx->cbSize)); + } + } else { + } + + } else { + DbgLog((LOG_TRACE,2,TEXT(" Format type %hs"), + GuidNames[pmtIn->formattype])); + } +} + + +void DisplayBITMAPINFO(const BITMAPINFOHEADER* pbmi) +{ + DbgLog((LOG_TRACE,5,TEXT("Size of BITMAPINFO structure %d"),pbmi->biSize)); + if (pbmi->biCompression < 256) { + DbgLog((LOG_TRACE,2,TEXT("%dx%dx%d bit (%d)"), + pbmi->biWidth, pbmi->biHeight, + pbmi->biBitCount, pbmi->biCompression)); + } else { + DbgLog((LOG_TRACE,2,TEXT("%dx%dx%d bit '%4.4hs'"), + pbmi->biWidth, pbmi->biHeight, + pbmi->biBitCount, &pbmi->biCompression)); + } + + DbgLog((LOG_TRACE,2,TEXT("Image size %d"),pbmi->biSizeImage)); + DbgLog((LOG_TRACE,5,TEXT("Planes %d"),pbmi->biPlanes)); + DbgLog((LOG_TRACE,5,TEXT("X Pels per metre %d"),pbmi->biXPelsPerMeter)); + DbgLog((LOG_TRACE,5,TEXT("Y Pels per metre %d"),pbmi->biYPelsPerMeter)); + DbgLog((LOG_TRACE,5,TEXT("Colours used %d"),pbmi->biClrUsed)); +} + + +void DisplayRECT(LPCTSTR szLabel, const RECT& rc) +{ + DbgLog((LOG_TRACE,5,TEXT("%s (Left %d Top %d Right %d Bottom %d)"), + szLabel, + rc.left, + rc.top, + rc.right, + rc.bottom)); +} + + +void WINAPI DumpGraph(IFilterGraph *pGraph, DWORD dwLevel) +{ + if( !pGraph ) + { + return; + } + + IEnumFilters *pFilters; + + DbgLog((LOG_TRACE,dwLevel,TEXT("DumpGraph [%x]"), pGraph)); + + if (FAILED(pGraph->EnumFilters(&pFilters))) { + DbgLog((LOG_TRACE,dwLevel,TEXT("EnumFilters failed!"))); + } + + IBaseFilter *pFilter; + ULONG n; + while (pFilters->Next(1, &pFilter, &n) == S_OK) { + FILTER_INFO info; + + if (FAILED(pFilter->QueryFilterInfo(&info))) { + DbgLog((LOG_TRACE,dwLevel,TEXT(" Filter [%p] -- failed QueryFilterInfo"), pFilter)); + } else { + QueryFilterInfoReleaseGraph(info); + + // !!! should QueryVendorInfo here! + + DbgLog((LOG_TRACE,dwLevel,TEXT(" Filter [%p] '%ls'"), pFilter, info.achName)); + + IEnumPins *pins; + + if (FAILED(pFilter->EnumPins(&pins))) { + DbgLog((LOG_TRACE,dwLevel,TEXT("EnumPins failed!"))); + } else { + + IPin *pPin; + while (pins->Next(1, &pPin, &n) == S_OK) { + PIN_INFO pinInfo; + + if (FAILED(pPin->QueryPinInfo(&pinInfo))) { + DbgLog((LOG_TRACE,dwLevel,TEXT(" Pin [%x] -- failed QueryPinInfo"), pPin)); + } else { + QueryPinInfoReleaseFilter(pinInfo); + + IPin *pPinConnected = NULL; + + HRESULT hr = pPin->ConnectedTo(&pPinConnected); + + if (pPinConnected) { + DbgLog((LOG_TRACE,dwLevel,TEXT(" Pin [%p] '%ls' [%sput]") + TEXT(" Connected to pin [%p]"), + pPin, pinInfo.achName, + pinInfo.dir == PINDIR_INPUT ? TEXT("In") : TEXT("Out"), + pPinConnected)); + + pPinConnected->Release(); + + // perhaps we should really dump the type both ways as a sanity + // check? + if (pinInfo.dir == PINDIR_OUTPUT) { + AM_MEDIA_TYPE mt; + + hr = pPin->ConnectionMediaType(&mt); + + if (SUCCEEDED(hr)) { + DisplayType(TEXT("Connection type"), &mt); + + FreeMediaType(mt); + } + } + } else { + DbgLog((LOG_TRACE,dwLevel, + TEXT(" Pin [%x] '%ls' [%sput]"), + pPin, pinInfo.achName, + pinInfo.dir == PINDIR_INPUT ? TEXT("In") : TEXT("Out"))); + + } + } + + pPin->Release(); + + } + + pins->Release(); + } + + } + + pFilter->Release(); + } + + pFilters->Release(); + +} + +#endif + +//------------------------------------------------------------------------------ +// File: AMVideo.cpp +// +// Desc: DirectShow base classes - implements helper functions for +// bitmap formats. +// +// Copyright (c) 1992-2001 Microsoft Corporation. All rights reserved. +//------------------------------------------------------------------------------ + +// These are bit field masks for true colour devices + +const DWORD bits555[] = {0x007C00,0x0003E0,0x00001F}; +const DWORD bits565[] = {0x00F800,0x0007E0,0x00001F}; +const DWORD bits888[] = {0xFF0000,0x00FF00,0x0000FF}; + +// This maps bitmap subtypes into a bits per pixel value and also a +// name. unicode and ansi versions are stored because we have to +// return a pointer to a static string. +const struct { + const GUID *pSubtype; + WORD BitCount; + CHAR *pName; + WCHAR *wszName; +} BitCountMap[] = { &MEDIASUBTYPE_RGB1, 1, "RGB Monochrome", L"RGB Monochrome", + &MEDIASUBTYPE_RGB4, 4, "RGB VGA", L"RGB VGA", + &MEDIASUBTYPE_RGB8, 8, "RGB 8", L"RGB 8", + &MEDIASUBTYPE_RGB565, 16, "RGB 565 (16 bit)", L"RGB 565 (16 bit)", + &MEDIASUBTYPE_RGB555, 16, "RGB 555 (16 bit)", L"RGB 555 (16 bit)", + &MEDIASUBTYPE_RGB24, 24, "RGB 24", L"RGB 24", + &MEDIASUBTYPE_RGB32, 32, "RGB 32", L"RGB 32", + &MEDIASUBTYPE_ARGB32, 32, "ARGB 32", L"ARGB 32", + &MEDIASUBTYPE_Overlay, 0, "Overlay", L"Overlay", + &GUID_NULL, 0, "UNKNOWN", L"UNKNOWN" +}; + +// Return the size of the bitmap as defined by this header + +STDAPI_(DWORD) GetBitmapSize(const BITMAPINFOHEADER *pHeader) +{ + return DIBSIZE(*pHeader); +} + + +// This is called if the header has a 16 bit colour depth and needs to work +// out the detailed type from the bit fields (either RGB 565 or RGB 555) + +STDAPI_(const GUID) GetTrueColorType(const BITMAPINFOHEADER *pbmiHeader) +{ + BITMAPINFO *pbmInfo = (BITMAPINFO *) pbmiHeader; + ASSERT(pbmiHeader->biBitCount == 16); + + // If its BI_RGB then it's RGB 555 by default + + if (pbmiHeader->biCompression == BI_RGB) { + return MEDIASUBTYPE_RGB555; + } + + // Compare the bit fields with RGB 555 + + DWORD *pMask = (DWORD *) pbmInfo->bmiColors; + if (pMask[0] == bits555[0]) { + if (pMask[1] == bits555[1]) { + if (pMask[2] == bits555[2]) { + return MEDIASUBTYPE_RGB555; + } + } + } + + // Compare the bit fields with RGB 565 + + pMask = (DWORD *) pbmInfo->bmiColors; + if (pMask[0] == bits565[0]) { + if (pMask[1] == bits565[1]) { + if (pMask[2] == bits565[2]) { + return MEDIASUBTYPE_RGB565; + } + } + } + return GUID_NULL; +} + + +// Given a BITMAPINFOHEADER structure this returns the GUID sub type that is +// used to describe it in format negotiations. For example a video codec fills +// in the format block with a VIDEOINFO structure, it also fills in the major +// type with MEDIATYPE_VIDEO and the subtype with a GUID that matches the bit +// count, for example if it is an eight bit image then MEDIASUBTYPE_RGB8 + +STDAPI_(const GUID) GetBitmapSubtype(const BITMAPINFOHEADER *pbmiHeader) +{ + ASSERT(pbmiHeader); + + // If it's not RGB then create a GUID from the compression type + + if (pbmiHeader->biCompression != BI_RGB) { + if (pbmiHeader->biCompression != BI_BITFIELDS) { + FOURCCMap FourCCMap(pbmiHeader->biCompression); + return (const GUID) FourCCMap; + } + } + + // Map the RGB DIB bit depth to a image GUID + + switch(pbmiHeader->biBitCount) { + case 1 : return MEDIASUBTYPE_RGB1; + case 4 : return MEDIASUBTYPE_RGB4; + case 8 : return MEDIASUBTYPE_RGB8; + case 16 : return GetTrueColorType(pbmiHeader); + case 24 : return MEDIASUBTYPE_RGB24; + case 32 : return MEDIASUBTYPE_RGB32; + } + return GUID_NULL; +} + + +// Given a video bitmap subtype we return the number of bits per pixel it uses +// We return a WORD bit count as thats what the BITMAPINFOHEADER uses. If the +// GUID subtype is not found in the table we return an invalid USHRT_MAX + +STDAPI_(WORD) GetBitCount(const GUID *pSubtype) +{ + ASSERT(pSubtype); + const GUID *pMediaSubtype; + INT iPosition = 0; + + // Scan the mapping list seeing if the source GUID matches any known + // bitmap subtypes, the list is terminated by a GUID_NULL entry + + while (TRUE) { + pMediaSubtype = BitCountMap[iPosition].pSubtype; + if (IsEqualGUID(*pMediaSubtype,GUID_NULL)) { + return USHRT_MAX; + } + if (IsEqualGUID(*pMediaSubtype,*pSubtype)) { + return BitCountMap[iPosition].BitCount; + } + iPosition++; + } +} + + +// Given a bitmap subtype we return a description name that can be used for +// debug purposes. In a retail build this function still returns the names +// If the subtype isn't found in the lookup table we return string UNKNOWN + +int LocateSubtype(const GUID *pSubtype) +{ + ASSERT(pSubtype); + const GUID *pMediaSubtype; + INT iPosition = 0; + + // Scan the mapping list seeing if the source GUID matches any known + // bitmap subtypes, the list is terminated by a GUID_NULL entry + + while (TRUE) { + pMediaSubtype = BitCountMap[iPosition].pSubtype; + if (IsEqualGUID(*pMediaSubtype,*pSubtype) || + IsEqualGUID(*pMediaSubtype,GUID_NULL) + ) + { + break; + } + + iPosition++; + } + + return iPosition; +} + + + +STDAPI_(WCHAR *) GetSubtypeNameW(const GUID *pSubtype) +{ + return BitCountMap[LocateSubtype(pSubtype)].wszName; +} + +STDAPI_(CHAR *) GetSubtypeNameA(const GUID *pSubtype) +{ + return BitCountMap[LocateSubtype(pSubtype)].pName; +} + +#ifndef GetSubtypeName +#error wxutil.h should have defined GetSubtypeName +#endif +#undef GetSubtypeName + +// this is here for people that linked to it directly; most people +// would use the header file that picks the A or W version. +STDAPI_(CHAR *) GetSubtypeName(const GUID *pSubtype) +{ + return GetSubtypeNameA(pSubtype); +} + + +// The mechanism for describing a bitmap format is with the BITMAPINFOHEADER +// This is really messy to deal with because it invariably has fields that +// follow it holding bit fields, palettes and the rest. This function gives +// the number of bytes required to hold a VIDEOINFO that represents it. This +// count includes the prefix information (like the rcSource rectangle) the +// BITMAPINFOHEADER field, and any other colour information on the end. +// +// WARNING If you want to copy a BITMAPINFOHEADER into a VIDEOINFO always make +// sure that you use the HEADER macro because the BITMAPINFOHEADER field isn't +// right at the start of the VIDEOINFO (there are a number of other fields), +// +// CopyMemory(HEADER(pVideoInfo),pbmi,sizeof(BITMAPINFOHEADER)); +// + +STDAPI_(LONG) GetBitmapFormatSize(const BITMAPINFOHEADER *pHeader) +{ + // Everyone has this to start with this + LONG Size = SIZE_PREHEADER + pHeader->biSize; + + ASSERT(pHeader->biSize >= sizeof(BITMAPINFOHEADER)); + + // Does this format use a palette, if the number of colours actually used + // is zero then it is set to the maximum that are allowed for that colour + // depth (an example is 256 for eight bits). Truecolour formats may also + // pass a palette with them in which case the used count is non zero + + // This would scare me. + ASSERT(pHeader->biBitCount <= iPALETTE || pHeader->biClrUsed == 0); + + if (pHeader->biBitCount <= iPALETTE || pHeader->biClrUsed) { + LONG Entries = (DWORD) 1 << pHeader->biBitCount; + if (pHeader->biClrUsed) { + Entries = pHeader->biClrUsed; + } + Size += Entries * sizeof(RGBQUAD); + } + + // Truecolour formats may have a BI_BITFIELDS specifier for compression + // type which means that room for three DWORDs should be allocated that + // specify where in each pixel the RGB colour components may be found + + if (pHeader->biCompression == BI_BITFIELDS) { + Size += SIZE_MASKS; + } + + // A BITMAPINFO for a palettised image may also contain a palette map that + // provides the information to map from a source palette to a destination + // palette during a BitBlt for example, because this information is only + // ever processed during drawing you don't normally store the palette map + // nor have any way of knowing if it is present in the data structure + + return Size; +} + + +// Returns TRUE if the VIDEOINFO contains a palette + +STDAPI_(BOOL) ContainsPalette(const VIDEOINFOHEADER *pVideoInfo) +{ + if (PALETTISED(pVideoInfo) == FALSE) { + if (pVideoInfo->bmiHeader.biClrUsed == 0) { + return FALSE; + } + } + return TRUE; +} + + +// Return a pointer to the first entry in a palette + +STDAPI_(const RGBQUAD *) GetBitmapPalette(const VIDEOINFOHEADER *pVideoInfo) +{ + if (pVideoInfo->bmiHeader.biCompression == BI_BITFIELDS) { + return TRUECOLOR(pVideoInfo)->bmiColors; + } + return COLORS(pVideoInfo); +} + +//------------------------------------------------------------------------------ +// File: ComBase.cpp +// +// Desc: DirectShow base classes - implements class hierarchy for creating +// COM objects. +// +// Copyright (c) 1992-2001 Microsoft Corporation. All rights reserved. +//------------------------------------------------------------------------------ + +/* Define the static member variable */ + +LONG CBaseObject::m_cObjects = 0; + + +/* Constructor */ + +CBaseObject::CBaseObject(__in_opt LPCTSTR pName) +{ + /* Increment the number of active objects */ + InterlockedIncrement(&m_cObjects); + +#ifdef DEBUG + +#ifdef UNICODE + m_dwCookie = DbgRegisterObjectCreation(0, pName); +#else + m_dwCookie = DbgRegisterObjectCreation(pName, 0); +#endif + +#endif +} + +#ifdef UNICODE +CBaseObject::CBaseObject(const char *pName) +{ + /* Increment the number of active objects */ + InterlockedIncrement(&m_cObjects); + +#ifdef DEBUG + m_dwCookie = DbgRegisterObjectCreation(pName, 0); +#endif +} +#endif + +HINSTANCE hlibOLEAut32; + +/* Destructor */ + +CBaseObject::~CBaseObject() +{ + /* Decrement the number of objects active */ + if (InterlockedDecrement(&m_cObjects) == 0) { + if (hlibOLEAut32) { + FreeLibrary(hlibOLEAut32); + + hlibOLEAut32 = 0; + } + }; + + +#ifdef DEBUG + DbgRegisterObjectDestruction(m_dwCookie); +#endif +} + +static const TCHAR szOle32Aut[] = TEXT("OleAut32.dll"); + +HINSTANCE LoadOLEAut32() +{ + if (hlibOLEAut32 == 0) { + + hlibOLEAut32 = LoadLibrary(szOle32Aut); + } + + return hlibOLEAut32; +} + + +/* Constructor */ + +// We know we use "this" in the initialization list, we also know we don't modify *phr. +CUnknown::CUnknown(__in_opt LPCTSTR pName, __in_opt LPUNKNOWN pUnk) +: CBaseObject(pName) +/* Start the object with a reference count of zero - when the */ +/* object is queried for it's first interface this may be */ +/* incremented depending on whether or not this object is */ +/* currently being aggregated upon */ +, m_cRef(0) +/* Set our pointer to our IUnknown interface. */ +/* If we have an outer, use its, otherwise use ours. */ +/* This pointer effectivly points to the owner of */ +/* this object and can be accessed by the GetOwner() method. */ +, m_pUnknown( pUnk != 0 ? pUnk : reinterpret_cast( static_cast(this) ) ) + /* Why the double cast? Well, the inner cast is a type-safe cast */ + /* to pointer to a type from which we inherit. The second is */ + /* type-unsafe but works because INonDelegatingUnknown "behaves */ + /* like" IUnknown. (Only the names on the methods change.) */ +{ + // Everything we need to do has been done in the initializer list +} + +// This does the same as above except it has a useless HRESULT argument +// use the previous constructor, this is just left for compatibility... +CUnknown::CUnknown(__in_opt LPCTSTR pName, __in_opt LPUNKNOWN pUnk, __inout_opt HRESULT *phr) : + CBaseObject(pName), + m_cRef(0), + m_pUnknown( pUnk != 0 ? pUnk : reinterpret_cast( static_cast(this) ) ) +{ +} + +#ifdef UNICODE +CUnknown::CUnknown(__in_opt LPCSTR pName, __in_opt LPUNKNOWN pUnk) +: CBaseObject(pName), m_cRef(0), + m_pUnknown( pUnk != 0 ? pUnk : reinterpret_cast( static_cast(this) ) ) +{ } + +CUnknown::CUnknown(__in_opt LPCSTR pName, __in_opt LPUNKNOWN pUnk, __inout_opt HRESULT *phr) : + CBaseObject(pName), m_cRef(0), + m_pUnknown( pUnk != 0 ? pUnk : reinterpret_cast( static_cast(this) ) ) +{ } + +#endif + +/* QueryInterface */ + +STDMETHODIMP CUnknown::NonDelegatingQueryInterface(REFIID riid, __deref_out void ** ppv) +{ + CheckPointer(ppv,E_POINTER); + ValidateReadWritePtr(ppv,sizeof(PVOID)); + + /* We know only about IUnknown */ + + if (riid == IID_IUnknown) { + GetInterface((LPUNKNOWN) (PNDUNKNOWN) this, ppv); + return NOERROR; + } else { + *ppv = NULL; + return E_NOINTERFACE; + } +} + +/* We have to ensure that we DON'T use a max macro, since these will typically */ +/* lead to one of the parameters being evaluated twice. Since we are worried */ +/* about concurrency, we can't afford to access the m_cRef twice since we can't */ +/* afford to run the risk that its value having changed between accesses. */ + +template inline static T ourmax( const T & a, const T & b ) +{ + return a > b ? a : b; +} + +/* AddRef */ + +STDMETHODIMP_(ULONG) CUnknown::NonDelegatingAddRef() +{ + LONG lRef = InterlockedIncrement( &m_cRef ); + ASSERT(lRef > 0); + DbgLog((LOG_MEMORY,3,TEXT(" Obj %d ref++ = %d"), + m_dwCookie, m_cRef)); + return ourmax(ULONG(m_cRef), 1ul); +} + + +/* Release */ + +STDMETHODIMP_(ULONG) CUnknown::NonDelegatingRelease() +{ + /* If the reference count drops to zero delete ourselves */ + + LONG lRef = InterlockedDecrement( &m_cRef ); + ASSERT(lRef >= 0); + + DbgLog((LOG_MEMORY,3,TEXT(" Object %d ref-- = %d"), + m_dwCookie, m_cRef)); + if (lRef == 0) { + + // COM rules say we must protect against re-entrancy. + // If we are an aggregator and we hold our own interfaces + // on the aggregatee, the QI for these interfaces will + // addref ourselves. So after doing the QI we must release + // a ref count on ourselves. Then, before releasing the + // private interface, we must addref ourselves. When we do + // this from the destructor here it will result in the ref + // count going to 1 and then back to 0 causing us to + // re-enter the destructor. Hence we add an extra refcount here + // once we know we will delete the object. + // for an example aggregator see filgraph\distrib.cpp. + + m_cRef++; + + delete this; + return ULONG(0); + } else { + // Don't touch m_cRef again even in this leg as the object + // may have just been released on another thread too + return ourmax(ULONG(lRef), 1ul); + } +} + + +/* Return an interface pointer to a requesting client + performing a thread safe AddRef as necessary */ + +STDAPI GetInterface(LPUNKNOWN pUnk, __out void **ppv) +{ + CheckPointer(ppv, E_POINTER); + *ppv = pUnk; + pUnk->AddRef(); + return NOERROR; +} + + +/* Compares two interfaces and returns TRUE if they are on the same object */ + +BOOL WINAPI IsEqualObject(IUnknown *pFirst, IUnknown *pSecond) +{ + /* Different objects can't have the same interface pointer for + any interface + */ + if (pFirst == pSecond) { + return TRUE; + } + /* OK - do it the hard way - check if they have the same + IUnknown pointers - a single object can only have one of these + */ + LPUNKNOWN pUnknown1; // Retrieve the IUnknown interface + LPUNKNOWN pUnknown2; // Retrieve the other IUnknown interface + HRESULT hr; // General OLE return code + + ASSERT(pFirst); + ASSERT(pSecond); + + /* See if the IUnknown pointers match */ + + hr = pFirst->QueryInterface(IID_IUnknown,(void **) &pUnknown1); + if (FAILED(hr)) { + return FALSE; + } + ASSERT(pUnknown1); + + /* Release the extra interface we hold */ + + pUnknown1->Release(); + + hr = pSecond->QueryInterface(IID_IUnknown,(void **) &pUnknown2); + if (FAILED(hr)) { + return FALSE; + } + ASSERT(pUnknown2); + + /* Release the extra interface we hold */ + + pUnknown2->Release(); + return (pUnknown1 == pUnknown2); +} + +//------------------------------------------------------------------------------ +// File: WXUtil.cpp +// +// Desc: DirectShow base classes - implements helper classes for building +// multimedia filters. +// +// Copyright (c) 1992-2001 Microsoft Corporation. All rights reserved. +//------------------------------------------------------------------------------ + +// --- CAMEvent ----------------------- +CAMEvent::CAMEvent(BOOL fManualReset, __inout_opt HRESULT *phr) +{ + m_hEvent = CreateEvent(NULL, fManualReset, FALSE, NULL); + if (NULL == m_hEvent) { + if (NULL != phr && SUCCEEDED(*phr)) { + *phr = E_OUTOFMEMORY; + } + } +} + +CAMEvent::CAMEvent(__inout_opt HRESULT *phr) +{ + m_hEvent = CreateEvent(NULL, FALSE, FALSE, NULL); + if (NULL == m_hEvent) { + if (NULL != phr && SUCCEEDED(*phr)) { + *phr = E_OUTOFMEMORY; + } + } +} + +CAMEvent::~CAMEvent() +{ + if (m_hEvent) { + EXECUTE_ASSERT(CloseHandle(m_hEvent)); + } +} + + +// --- CAMMsgEvent ----------------------- +// One routine. The rest is handled in CAMEvent + +CAMMsgEvent::CAMMsgEvent(__inout_opt HRESULT *phr) : CAMEvent(FALSE, phr) +{ +} + +BOOL CAMMsgEvent::WaitMsg(DWORD dwTimeout) +{ + // wait for the event to be signalled, or for the + // timeout (in MS) to expire. allow SENT messages + // to be processed while we wait + DWORD dwWait; + DWORD dwStartTime; + + // set the waiting period. + DWORD dwWaitTime = dwTimeout; + + // the timeout will eventually run down as we iterate + // processing messages. grab the start time so that + // we can calculate elapsed times. + if (dwWaitTime != INFINITE) { + dwStartTime = timeGetTime(); + } + + do { + dwWait = MsgWaitForMultipleObjects(1,&m_hEvent,FALSE, dwWaitTime, QS_SENDMESSAGE); + if (dwWait == WAIT_OBJECT_0 + 1) { + MSG Message; + PeekMessage(&Message,NULL,0,0,PM_NOREMOVE); + + // If we have an explicit length of time to wait calculate + // the next wake up point - which might be now. + // If dwTimeout is INFINITE, it stays INFINITE + if (dwWaitTime != INFINITE) { + + DWORD dwElapsed = timeGetTime()-dwStartTime; + + dwWaitTime = + (dwElapsed >= dwTimeout) + ? 0 // wake up with WAIT_TIMEOUT + : dwTimeout-dwElapsed; + } + } + } while (dwWait == WAIT_OBJECT_0 + 1); + + // return TRUE if we woke on the event handle, + // FALSE if we timed out. + return (dwWait == WAIT_OBJECT_0); +} + +// --- CAMThread ---------------------- + + +CAMThread::CAMThread(__inout_opt HRESULT *phr) + : m_EventSend(TRUE, phr), // must be manual-reset for CheckRequest() + m_EventComplete(FALSE, phr) +{ + m_hThread = NULL; +} + +CAMThread::~CAMThread() { + Close(); +} + + +// when the thread starts, it calls this function. We unwrap the 'this' +//pointer and call ThreadProc. +DWORD WINAPI +CAMThread::InitialThreadProc(__inout LPVOID pv) +{ + HRESULT hrCoInit = CAMThread::CoInitializeHelper(); + if(FAILED(hrCoInit)) { + DbgLog((LOG_ERROR, 1, TEXT("CoInitializeEx failed."))); + } + + CAMThread * pThread = (CAMThread *) pv; + + HRESULT hr = pThread->ThreadProc(); + + if(SUCCEEDED(hrCoInit)) { + CoUninitialize(); + } + + return hr; +} + +BOOL +CAMThread::Create() +{ + DWORD threadid; + + CAutoLock lock(&m_AccessLock); + + if (ThreadExists()) { + return FALSE; + } + + m_hThread = CreateThread( + NULL, + 0, + CAMThread::InitialThreadProc, + this, + 0, + &threadid); + + if (!m_hThread) { + return FALSE; + } + + return TRUE; +} + +DWORD +CAMThread::CallWorker(DWORD dwParam) +{ + // lock access to the worker thread for scope of this object + CAutoLock lock(&m_AccessLock); + + if (!ThreadExists()) { + return (DWORD) E_FAIL; + } + + // set the parameter + m_dwParam = dwParam; + + // signal the worker thread + m_EventSend.Set(); + + // wait for the completion to be signalled + m_EventComplete.Wait(); + + // done - this is the thread's return value + return m_dwReturnVal; +} + +// Wait for a request from the client +DWORD +CAMThread::GetRequest() +{ + m_EventSend.Wait(); + return m_dwParam; +} + +// is there a request? +BOOL +CAMThread::CheckRequest(__out_opt DWORD * pParam) +{ + if (!m_EventSend.Check()) { + return FALSE; + } else { + if (pParam) { + *pParam = m_dwParam; + } + return TRUE; + } +} + +// reply to the request +void +CAMThread::Reply(DWORD dw) +{ + m_dwReturnVal = dw; + + // The request is now complete so CheckRequest should fail from + // now on + // + // This event should be reset BEFORE we signal the client or + // the client may Set it before we reset it and we'll then + // reset it (!) + + m_EventSend.Reset(); + + // Tell the client we're finished + + m_EventComplete.Set(); +} + +HRESULT CAMThread::CoInitializeHelper() +{ + // call CoInitializeEx and tell OLE not to create a window (this + // thread probably won't dispatch messages and will hang on + // broadcast msgs o/w). + // + // If CoInitEx is not available, threads that don't call CoCreate + // aren't affected. Threads that do will have to handle the + // failure. Perhaps we should fall back to CoInitialize and risk + // hanging? + // + + // older versions of ole32.dll don't have CoInitializeEx + + HRESULT hr = E_FAIL; + HINSTANCE hOle = GetModuleHandle(TEXT("ole32.dll")); + if(hOle) + { + typedef HRESULT (STDAPICALLTYPE *PCoInitializeEx)( + LPVOID pvReserved, DWORD dwCoInit); + PCoInitializeEx pCoInitializeEx = + (PCoInitializeEx)(GetProcAddress(hOle, "CoInitializeEx")); + if(pCoInitializeEx) + { + hr = (*pCoInitializeEx)(0, COINIT_DISABLE_OLE1DDE ); + } + } + else + { + // caller must load ole32.dll + DbgBreak("couldn't locate ole32.dll"); + } + + return hr; +} + + +// destructor for CMsgThread - cleans up any messages left in the +// queue when the thread exited +CMsgThread::~CMsgThread() +{ + if (m_hThread != NULL) { + WaitForSingleObject(m_hThread, INFINITE); + EXECUTE_ASSERT(CloseHandle(m_hThread)); + } + + POSITION pos = m_ThreadQueue.GetHeadPosition(); + while (pos) { + CMsg * pMsg = m_ThreadQueue.GetNext(pos); + delete pMsg; + } + m_ThreadQueue.RemoveAll(); + + if (m_hSem != NULL) { + EXECUTE_ASSERT(CloseHandle(m_hSem)); + } +} + +BOOL +CMsgThread::CreateThread( + ) +{ + m_hSem = CreateSemaphore(NULL, 0, 0x7FFFFFFF, NULL); + if (m_hSem == NULL) { + return FALSE; + } + + m_hThread = ::CreateThread(NULL, 0, DefaultThreadProc, + (LPVOID)this, 0, &m_ThreadId); + return m_hThread != NULL; +} + + +// This is the threads message pump. Here we get and dispatch messages to +// clients thread proc until the client refuses to process a message. +// The client returns a non-zero value to stop the message pump, this +// value becomes the threads exit code. + +DWORD WINAPI +CMsgThread::DefaultThreadProc( + __inout LPVOID lpParam + ) +{ + CMsgThread *lpThis = (CMsgThread *)lpParam; + CMsg msg; + LRESULT lResult; + + // !!! + CoInitialize(NULL); + + // allow a derived class to handle thread startup + lpThis->OnThreadInit(); + + do { + lpThis->GetThreadMsg(&msg); + lResult = lpThis->ThreadMessageProc(msg.uMsg,msg.dwFlags, + msg.lpParam, msg.pEvent); + } while (lResult == 0L); + + // !!! + CoUninitialize(); + + return (DWORD)lResult; +} + + +// Block until the next message is placed on the list m_ThreadQueue. +// copies the message to the message pointed to by *pmsg +void +CMsgThread::GetThreadMsg(__out CMsg *msg) +{ + CMsg * pmsg = NULL; + + // keep trying until a message appears + while (TRUE) { + { + CAutoLock lck(&m_Lock); + pmsg = m_ThreadQueue.RemoveHead(); + if (pmsg == NULL) { + m_lWaiting++; + } else { + break; + } + } + // the semaphore will be signalled when it is non-empty + WaitForSingleObject(m_hSem, INFINITE); + } + // copy fields to caller's CMsg + *msg = *pmsg; + + // this CMsg was allocated by the 'new' in PutThreadMsg + delete pmsg; + +} + +// Helper function - convert int to WSTR +void WINAPI IntToWstr(int i, __out_ecount(12) LPWSTR wstr) +{ +#ifdef UNICODE + if (FAILED(StringCchPrintf(wstr, 12, L"%d", i))) { + wstr[0] = 0; + } +#else + TCHAR temp[12]; + if (FAILED(StringCchPrintf(temp, NUMELMS(temp), "%d", i))) { + wstr[0] = 0; + } else { + MultiByteToWideChar(CP_ACP, 0, temp, -1, wstr, 12); + } +#endif +} // IntToWstr + + +#define MEMORY_ALIGNMENT 4 +#define MEMORY_ALIGNMENT_LOG2 2 +#define MEMORY_ALIGNMENT_MASK MEMORY_ALIGNMENT - 1 + +void * __stdcall memmoveInternal(void * dst, const void * src, size_t count) +{ + void * ret = dst; + +#ifdef _X86_ + if (dst <= src || (char *)dst >= ((char *)src + count)) { + + /* + * Non-Overlapping Buffers + * copy from lower addresses to higher addresses + */ + _asm { + mov esi,src + mov edi,dst + mov ecx,count + cld + mov edx,ecx + and edx,MEMORY_ALIGNMENT_MASK + shr ecx,MEMORY_ALIGNMENT_LOG2 + rep movsd + or ecx,edx + jz memmove_done + rep movsb +memmove_done: + } + } + else { + + /* + * Overlapping Buffers + * copy from higher addresses to lower addresses + */ + _asm { + mov esi,src + mov edi,dst + mov ecx,count + std + add esi,ecx + add edi,ecx + dec esi + dec edi + rep movsb + cld + } + } +#else + MoveMemory(dst, src, count); +#endif + + return ret; +} + +HRESULT AMSafeMemMoveOffset( + __in_bcount(dst_size) void * dst, + __in size_t dst_size, + __in DWORD cb_dst_offset, + __in_bcount(src_size) const void * src, + __in size_t src_size, + __in DWORD cb_src_offset, + __in size_t count) +{ + // prevent read overruns + if( count + cb_src_offset < count || // prevent integer overflow + count + cb_src_offset > src_size) // prevent read overrun + { + return E_INVALIDARG; + } + + // prevent write overruns + if( count + cb_dst_offset < count || // prevent integer overflow + count + cb_dst_offset > dst_size) // prevent write overrun + { + return E_INVALIDARG; + } + + memmoveInternal( (BYTE *)dst+cb_dst_offset, (BYTE *)src+cb_src_offset, count); + return S_OK; +} + + +#ifdef DEBUG +/******************************Public*Routine******************************\ +* Debug CCritSec helpers +* +* We provide debug versions of the Constructor, destructor, Lock and Unlock +* routines. The debug code tracks who owns each critical section by +* maintaining a depth count. +* +* History: +* +\**************************************************************************/ + +CCritSec::CCritSec() +{ + InitializeCriticalSection(&m_CritSec); + m_currentOwner = m_lockCount = 0; + m_fTrace = FALSE; +} + +CCritSec::~CCritSec() +{ + DeleteCriticalSection(&m_CritSec); +} + +void CCritSec::Lock() +{ + UINT tracelevel=3; + DWORD us = GetCurrentThreadId(); + DWORD currentOwner = m_currentOwner; + if (currentOwner && (currentOwner != us)) { + // already owned, but not by us + if (m_fTrace) { + DbgLog((LOG_LOCKING, 2, TEXT("Thread %d about to wait for lock %x owned by %d"), + GetCurrentThreadId(), &m_CritSec, currentOwner)); + tracelevel=2; + // if we saw the message about waiting for the critical + // section we ensure we see the message when we get the + // critical section + } + } + EnterCriticalSection(&m_CritSec); + if (0 == m_lockCount++) { + // we now own it for the first time. Set owner information + m_currentOwner = us; + + if (m_fTrace) { + DbgLog((LOG_LOCKING, tracelevel, TEXT("Thread %d now owns lock %x"), m_currentOwner, &m_CritSec)); + } + } +} + +void CCritSec::Unlock() { + if (0 == --m_lockCount) { + // about to be unowned + if (m_fTrace) { + DbgLog((LOG_LOCKING, 3, TEXT("Thread %d releasing lock %x"), m_currentOwner, &m_CritSec)); + } + + m_currentOwner = 0; + } + LeaveCriticalSection(&m_CritSec); +} + +void WINAPI DbgLockTrace(CCritSec * pcCrit, BOOL fTrace) +{ + pcCrit->m_fTrace = fTrace; +} + +BOOL WINAPI CritCheckIn(CCritSec * pcCrit) +{ + return (GetCurrentThreadId() == pcCrit->m_currentOwner); +} + +BOOL WINAPI CritCheckIn(const CCritSec * pcCrit) +{ + return (GetCurrentThreadId() == pcCrit->m_currentOwner); +} + +BOOL WINAPI CritCheckOut(CCritSec * pcCrit) +{ + return (GetCurrentThreadId() != pcCrit->m_currentOwner); +} + +BOOL WINAPI CritCheckOut(const CCritSec * pcCrit) +{ + return (GetCurrentThreadId() != pcCrit->m_currentOwner); +} +#endif + + +STDAPI WriteBSTR(__deref_out BSTR *pstrDest, LPCWSTR szSrc) +{ + *pstrDest = SysAllocString( szSrc ); + if( !(*pstrDest) ) return E_OUTOFMEMORY; + return NOERROR; +} + + +STDAPI FreeBSTR(__deref_in BSTR* pstr) +{ + if( (PVOID)*pstr == NULL ) return S_FALSE; + SysFreeString( *pstr ); + return NOERROR; +} + + +// Return a wide string - allocating memory for it +// Returns: +// S_OK - no error +// E_POINTER - ppszReturn == NULL +// E_OUTOFMEMORY - can't allocate memory for returned string +STDAPI AMGetWideString(LPCWSTR psz, __deref_out LPWSTR *ppszReturn) +{ + CheckPointer(ppszReturn, E_POINTER); + ValidateReadWritePtr(ppszReturn, sizeof(LPWSTR)); + *ppszReturn = NULL; + size_t nameLen; + HRESULT hr = StringCbLengthW(psz, 100000, &nameLen); + if (FAILED(hr)) { + return hr; + } + *ppszReturn = (LPWSTR)CoTaskMemAlloc(nameLen + sizeof(WCHAR)); + if (*ppszReturn == NULL) { + return E_OUTOFMEMORY; + } + CopyMemory(*ppszReturn, psz, nameLen + sizeof(WCHAR)); + return NOERROR; +} + +// Waits for the HANDLE hObject. While waiting messages sent +// to windows on our thread by SendMessage will be processed. +// Using this function to do waits and mutual exclusion +// avoids some deadlocks in objects with windows. +// Return codes are the same as for WaitForSingleObject +DWORD WINAPI WaitDispatchingMessages( + HANDLE hObject, + DWORD dwWait, + HWND hwnd, + UINT uMsg, + HANDLE hEvent) +{ + BOOL bPeeked = FALSE; + DWORD dwResult; + DWORD dwStart; + DWORD dwThreadPriority; + + static UINT uMsgId = 0; + + HANDLE hObjects[2] = { hObject, hEvent }; + if (dwWait != INFINITE && dwWait != 0) { + dwStart = GetTickCount(); + } + for (; ; ) { + DWORD nCount = NULL != hEvent ? 2 : 1; + + // Minimize the chance of actually dispatching any messages + // by seeing if we can lock immediately. + dwResult = WaitForMultipleObjects(nCount, hObjects, FALSE, 0); + if (dwResult < WAIT_OBJECT_0 + nCount) { + break; + } + + DWORD dwTimeOut = dwWait; + if (dwTimeOut > 10) { + dwTimeOut = 10; + } + dwResult = MsgWaitForMultipleObjects( + nCount, + hObjects, + FALSE, + dwTimeOut, + hwnd == NULL ? QS_SENDMESSAGE : + QS_SENDMESSAGE + QS_POSTMESSAGE); + if (dwResult == WAIT_OBJECT_0 + nCount || + dwResult == WAIT_TIMEOUT && dwTimeOut != dwWait) { + MSG msg; + if (hwnd != NULL) { + while (PeekMessage(&msg, hwnd, uMsg, uMsg, PM_REMOVE)) { + DispatchMessage(&msg); + } + } + // Do this anyway - the previous peek doesn't flush out the + // messages + PeekMessage(&msg, NULL, 0, 0, PM_NOREMOVE); + + if (dwWait != INFINITE && dwWait != 0) { + DWORD dwNow = GetTickCount(); + + // Working with differences handles wrap-around + DWORD dwDiff = dwNow - dwStart; + if (dwDiff > dwWait) { + dwWait = 0; + } else { + dwWait -= dwDiff; + } + dwStart = dwNow; + } + if (!bPeeked) { + // Raise our priority to prevent our message queue + // building up + dwThreadPriority = GetThreadPriority(GetCurrentThread()); + if (dwThreadPriority < THREAD_PRIORITY_HIGHEST) { + SetThreadPriority(GetCurrentThread(), THREAD_PRIORITY_HIGHEST); + } + bPeeked = TRUE; + } + } else { + break; + } + } + if (bPeeked) { + SetThreadPriority(GetCurrentThread(), dwThreadPriority); + if (HIWORD(GetQueueStatus(QS_POSTMESSAGE)) & QS_POSTMESSAGE) { + if (uMsgId == 0) { + uMsgId = RegisterWindowMessage(TEXT("AMUnblock")); + } + if (uMsgId != 0) { + MSG msg; + // Remove old ones + while (PeekMessage(&msg, (HWND)-1, uMsgId, uMsgId, PM_REMOVE)) { + } + } + PostThreadMessage(GetCurrentThreadId(), uMsgId, 0, 0); + } + } + return dwResult; +} + +HRESULT AmGetLastErrorToHResult() +{ + DWORD dwLastError = GetLastError(); + if(dwLastError != 0) + { + return HRESULT_FROM_WIN32(dwLastError); + } + else + { + return E_FAIL; + } +} + +IUnknown* QzAtlComPtrAssign(__deref_inout_opt IUnknown** pp, __in_opt IUnknown* lp) +{ + if (lp != NULL) + lp->AddRef(); + if (*pp) + (*pp)->Release(); + *pp = lp; + return lp; +} + +/****************************************************************************** + +CompatibleTimeSetEvent + + CompatibleTimeSetEvent() sets the TIME_KILL_SYNCHRONOUS flag before calling +timeSetEvent() if the current operating system supports it. TIME_KILL_SYNCHRONOUS +is supported on Windows XP and later operating systems. + +Parameters: +- The same parameters as timeSetEvent(). See timeSetEvent()'s documentation in +the Platform SDK for more information. + +Return Value: +- The same return value as timeSetEvent(). See timeSetEvent()'s documentation in +the Platform SDK for more information. + +******************************************************************************/ +MMRESULT CompatibleTimeSetEvent( UINT uDelay, UINT uResolution, __in LPTIMECALLBACK lpTimeProc, DWORD_PTR dwUser, UINT fuEvent ) +{ + #if WINVER >= 0x0501 + { + static bool fCheckedVersion = false; + static bool fTimeKillSynchronousFlagAvailable = false; + + if( !fCheckedVersion ) { + fTimeKillSynchronousFlagAvailable = TimeKillSynchronousFlagAvailable(); + fCheckedVersion = true; + } + + if( fTimeKillSynchronousFlagAvailable ) { + fuEvent = fuEvent | TIME_KILL_SYNCHRONOUS; + } + } + #endif // WINVER >= 0x0501 + + return timeSetEvent( uDelay, uResolution, lpTimeProc, dwUser, fuEvent ); +} + +bool TimeKillSynchronousFlagAvailable( void ) +{ + OSVERSIONINFO osverinfo; + + osverinfo.dwOSVersionInfoSize = sizeof(osverinfo); + +#pragma warning(push) +#pragma warning(disable: 4996) //warning C4996: 'GetVersionExA': was declared deprecated + if( GetVersionEx( &osverinfo ) ) { +#pragma warning(pop) + + // Windows XP's major version is 5 and its' minor version is 1. + // timeSetEvent() started supporting the TIME_KILL_SYNCHRONOUS flag + // in Windows XP. + if( (osverinfo.dwMajorVersion > 5) || + ( (osverinfo.dwMajorVersion == 5) && (osverinfo.dwMinorVersion >= 1) ) ) { + return true; + } + } + + return false; +} + +//------------------------------------------------------------------------------ +// File: MType.cpp +// +// Desc: DirectShow base classes - implements a class that holds and +// manages media type information. +// +// Copyright (c) 1992-2001 Microsoft Corporation. All rights reserved. +//------------------------------------------------------------------------------ + +// helper class that derived pin objects can use to compare media +// types etc. Has same data members as the struct AM_MEDIA_TYPE defined +// in the streams IDL file, but also has (non-virtual) functions + +CMediaType::~CMediaType(){ + FreeMediaType(*this); +} + + +CMediaType::CMediaType() +{ + InitMediaType(); +} + + +CMediaType::CMediaType(const GUID * type) +{ + InitMediaType(); + majortype = *type; +} + + +// copy constructor does a deep copy of the format block + +CMediaType::CMediaType(const AM_MEDIA_TYPE& rt, __out_opt HRESULT* phr) +{ + HRESULT hr = CopyMediaType(this, &rt); + if (FAILED(hr) && (NULL != phr)) { + *phr = hr; + } +} + + +CMediaType::CMediaType(const CMediaType& rt, __out_opt HRESULT* phr) +{ + HRESULT hr = CopyMediaType(this, &rt); + if (FAILED(hr) && (NULL != phr)) { + *phr = hr; + } +} + + +// this class inherits publicly from AM_MEDIA_TYPE so the compiler could generate +// the following assignment operator itself, however it could introduce some +// memory conflicts and leaks in the process because the structure contains +// a dynamically allocated block (pbFormat) which it will not copy correctly + +CMediaType& +CMediaType::operator=(const AM_MEDIA_TYPE& rt) +{ + Set(rt); + return *this; +} + +CMediaType& +CMediaType::operator=(const CMediaType& rt) +{ + *this = (AM_MEDIA_TYPE &) rt; + return *this; +} + +BOOL +CMediaType::operator == (const CMediaType& rt) const +{ + // I don't believe we need to check sample size or + // temporal compression flags, since I think these must + // be represented in the type, subtype and format somehow. They + // are pulled out as separate flags so that people who don't understand + // the particular format representation can still see them, but + // they should duplicate information in the format block. + + return ((IsEqualGUID(majortype,rt.majortype) == TRUE) && + (IsEqualGUID(subtype,rt.subtype) == TRUE) && + (IsEqualGUID(formattype,rt.formattype) == TRUE) && + (cbFormat == rt.cbFormat) && + ( (cbFormat == 0) || + pbFormat != NULL && rt.pbFormat != NULL && + (memcmp(pbFormat, rt.pbFormat, cbFormat) == 0))); +} + + +BOOL +CMediaType::operator != (const CMediaType& rt) const +{ + /* Check to see if they are equal */ + + if (*this == rt) { + return FALSE; + } + return TRUE; +} + + +HRESULT +CMediaType::Set(const CMediaType& rt) +{ + return Set((AM_MEDIA_TYPE &) rt); +} + + +HRESULT +CMediaType::Set(const AM_MEDIA_TYPE& rt) +{ + if (&rt != this) { + FreeMediaType(*this); + HRESULT hr = CopyMediaType(this, &rt); + if (FAILED(hr)) { + return E_OUTOFMEMORY; + } + } + + return S_OK; +} + + +BOOL +CMediaType::IsValid() const +{ + return (!IsEqualGUID(majortype,GUID_NULL)); +} + + +void +CMediaType::SetType(const GUID* ptype) +{ + majortype = *ptype; +} + + +void +CMediaType::SetSubtype(const GUID* ptype) +{ + subtype = *ptype; +} + + +ULONG +CMediaType::GetSampleSize() const { + if (IsFixedSize()) { + return lSampleSize; + } else { + return 0; + } +} + + +void +CMediaType::SetSampleSize(ULONG sz) { + if (sz == 0) { + SetVariableSize(); + } else { + bFixedSizeSamples = TRUE; + lSampleSize = sz; + } +} + + +void +CMediaType::SetVariableSize() { + bFixedSizeSamples = FALSE; +} + + +void +CMediaType::SetTemporalCompression(BOOL bCompressed) { + bTemporalCompression = bCompressed; +} + +BOOL +CMediaType::SetFormat(__in_bcount(cb) BYTE * pformat, ULONG cb) +{ + if (NULL == AllocFormatBuffer(cb)) + return(FALSE); + + ASSERT(pbFormat); + memcpy(pbFormat, pformat, cb); + return(TRUE); +} + + +// set the type of the media type format block, this type defines what you +// will actually find in the format pointer. For example FORMAT_VideoInfo or +// FORMAT_WaveFormatEx. In the future this may be an interface pointer to a +// property set. Before sending out media types this should be filled in. + +void +CMediaType::SetFormatType(const GUID *pformattype) +{ + formattype = *pformattype; +} + + +// reset the format buffer + +void CMediaType::ResetFormatBuffer() +{ + if (cbFormat) { + CoTaskMemFree((PVOID)pbFormat); + } + cbFormat = 0; + pbFormat = NULL; +} + + +// allocate length bytes for the format and return a read/write pointer +// If we cannot allocate the new block of memory we return NULL leaving +// the original block of memory untouched (as does ReallocFormatBuffer) + +BYTE* +CMediaType::AllocFormatBuffer(ULONG length) +{ + ASSERT(length); + + // do the types have the same buffer size + + if (cbFormat == length) { + return pbFormat; + } + + // allocate the new format buffer + + BYTE *pNewFormat = (PBYTE)CoTaskMemAlloc(length); + if (pNewFormat == NULL) { + if (length <= cbFormat) return pbFormat; //reuse the old block anyway. + return NULL; + } + + // delete the old format + + if (cbFormat != 0) { + ASSERT(pbFormat); + CoTaskMemFree((PVOID)pbFormat); + } + + cbFormat = length; + pbFormat = pNewFormat; + return pbFormat; +} + + +// reallocate length bytes for the format and return a read/write pointer +// to it. We keep as much information as we can given the new buffer size +// if this fails the original format buffer is left untouched. The caller +// is responsible for ensuring the size of memory required is non zero + +BYTE* +CMediaType::ReallocFormatBuffer(ULONG length) +{ + ASSERT(length); + + // do the types have the same buffer size + + if (cbFormat == length) { + return pbFormat; + } + + // allocate the new format buffer + + BYTE *pNewFormat = (PBYTE)CoTaskMemAlloc(length); + if (pNewFormat == NULL) { + if (length <= cbFormat) return pbFormat; //reuse the old block anyway. + return NULL; + } + + // copy any previous format (or part of if new is smaller) + // delete the old format and replace with the new one + + if (cbFormat != 0) { + ASSERT(pbFormat); + memcpy(pNewFormat,pbFormat,min(length,cbFormat)); + CoTaskMemFree((PVOID)pbFormat); + } + + cbFormat = length; + pbFormat = pNewFormat; + return pNewFormat; +} + +// initialise a media type structure + +void CMediaType::InitMediaType() +{ + ZeroMemory((PVOID)this, sizeof(*this)); + lSampleSize = 1; + bFixedSizeSamples = TRUE; +} + + +// a partially specified media type can be passed to IPin::Connect +// as a constraint on the media type used in the connection. +// the type, subtype or format type can be null. +BOOL +CMediaType::IsPartiallySpecified(void) const +{ + if ((majortype == GUID_NULL) || + (formattype == GUID_NULL)) { + return TRUE; + } else { + return FALSE; + } +} + +BOOL +CMediaType::MatchesPartial(const CMediaType* ppartial) const +{ + if ((ppartial->majortype != GUID_NULL) && + (majortype != ppartial->majortype)) { + return FALSE; + } + if ((ppartial->subtype != GUID_NULL) && + (subtype != ppartial->subtype)) { + return FALSE; + } + + if (ppartial->formattype != GUID_NULL) { + // if the format block is specified then it must match exactly + if (formattype != ppartial->formattype) { + return FALSE; + } + if (cbFormat != ppartial->cbFormat) { + return FALSE; + } + if ((cbFormat != 0) && + (memcmp(pbFormat, ppartial->pbFormat, cbFormat) != 0)) { + return FALSE; + } + } + + return TRUE; + +} + + + +// general purpose function to delete a heap allocated AM_MEDIA_TYPE structure +// which is useful when calling IEnumMediaTypes::Next as the interface +// implementation allocates the structures which you must later delete +// the format block may also be a pointer to an interface to release + +void WINAPI DeleteMediaType(__inout_opt AM_MEDIA_TYPE *pmt) +{ + // allow NULL pointers for coding simplicity + + if (pmt == NULL) { + return; + } + + FreeMediaType(*pmt); + CoTaskMemFree((PVOID)pmt); +} + + +// this also comes in useful when using the IEnumMediaTypes interface so +// that you can copy a media type, you can do nearly the same by creating +// a CMediaType object but as soon as it goes out of scope the destructor +// will delete the memory it allocated (this takes a copy of the memory) + +AM_MEDIA_TYPE * WINAPI CreateMediaType(AM_MEDIA_TYPE const *pSrc) +{ + ASSERT(pSrc); + + // Allocate a block of memory for the media type + + AM_MEDIA_TYPE *pMediaType = + (AM_MEDIA_TYPE *)CoTaskMemAlloc(sizeof(AM_MEDIA_TYPE)); + + if (pMediaType == NULL) { + return NULL; + } + // Copy the variable length format block + + HRESULT hr = CopyMediaType(pMediaType,pSrc); + if (FAILED(hr)) { + CoTaskMemFree((PVOID)pMediaType); + return NULL; + } + + return pMediaType; +} + + +// Copy 1 media type to another + +HRESULT WINAPI CopyMediaType(__out AM_MEDIA_TYPE *pmtTarget, const AM_MEDIA_TYPE *pmtSource) +{ + // We'll leak if we copy onto one that already exists - there's one + // case we can check like that - copying to itself. + ASSERT(pmtSource != pmtTarget); + *pmtTarget = *pmtSource; + if (pmtSource->cbFormat != 0) { + ASSERT(pmtSource->pbFormat != NULL); + pmtTarget->pbFormat = (PBYTE)CoTaskMemAlloc(pmtSource->cbFormat); + if (pmtTarget->pbFormat == NULL) { + pmtTarget->cbFormat = 0; + return E_OUTOFMEMORY; + } else { + CopyMemory((PVOID)pmtTarget->pbFormat, (PVOID)pmtSource->pbFormat, + pmtTarget->cbFormat); + } + } + if (pmtTarget->pUnk != NULL) { + pmtTarget->pUnk->AddRef(); + } + + return S_OK; +} + +// Free an existing media type (ie free resources it holds) + +void WINAPI FreeMediaType(__inout AM_MEDIA_TYPE& mt) +{ + if (mt.cbFormat != 0) { + CoTaskMemFree((PVOID)mt.pbFormat); + + // Strictly unnecessary but tidier + mt.cbFormat = 0; + mt.pbFormat = NULL; + } + if (mt.pUnk != NULL) { + mt.pUnk->Release(); + mt.pUnk = NULL; + } +} + +// Initialize a media type from a WAVEFORMATEX + +STDAPI CreateAudioMediaType( + const WAVEFORMATEX *pwfx, + __out AM_MEDIA_TYPE *pmt, + BOOL bSetFormat +) +{ + pmt->majortype = MEDIATYPE_Audio; + if (pwfx->wFormatTag == WAVE_FORMAT_EXTENSIBLE) { + pmt->subtype = ((PWAVEFORMATEXTENSIBLE)pwfx)->SubFormat; + } else { + pmt->subtype = FOURCCMap(pwfx->wFormatTag); + } + pmt->formattype = FORMAT_WaveFormatEx; + pmt->bFixedSizeSamples = TRUE; + pmt->bTemporalCompression = FALSE; + pmt->lSampleSize = pwfx->nBlockAlign; + pmt->pUnk = NULL; + if (bSetFormat) { + if (pwfx->wFormatTag == WAVE_FORMAT_PCM) { + pmt->cbFormat = sizeof(WAVEFORMATEX); + } else { + pmt->cbFormat = sizeof(WAVEFORMATEX) + pwfx->cbSize; + } + pmt->pbFormat = (PBYTE)CoTaskMemAlloc(pmt->cbFormat); + if (pmt->pbFormat == NULL) { + return E_OUTOFMEMORY; + } + if (pwfx->wFormatTag == WAVE_FORMAT_PCM) { + CopyMemory(pmt->pbFormat, pwfx, sizeof(PCMWAVEFORMAT)); + ((WAVEFORMATEX *)pmt->pbFormat)->cbSize = 0; + } else { + CopyMemory(pmt->pbFormat, pwfx, pmt->cbFormat); + } + } + return S_OK; +} + +//------------------------------------------------------------------------------ +// File: WXList.cpp +// +// Desc: DirectShow base classes - implements a non-MFC based generic list +// template class. +// Copyright (c) 1992-2001 Microsoft Corporation. All rights reserved. +//------------------------------------------------------------------------------ + +/* A generic list of pointers to objects. + Objectives: avoid using MFC libraries in ndm kernel mode and + provide a really useful list type. + + The class is thread safe in that separate threads may add and + delete items in the list concurrently although the application + must ensure that constructor and destructor access is suitably + synchronised. + + The list name must not conflict with MFC classes as an + application may use both + + The nodes form a doubly linked, NULL terminated chain with an anchor + block (the list object per se) holding pointers to the first and last + nodes and a count of the nodes. + There is a node cache to reduce the allocation and freeing overhead. + It optionally (determined at construction time) has an Event which is + set whenever the list becomes non-empty and reset whenever it becomes + empty. + It optionally (determined at construction time) has a Critical Section + which is entered during the important part of each operation. (About + all you can do outside it is some parameter checking). + + The node cache is a repository of nodes that are NOT in the list to speed + up storage allocation. Each list has its own cache to reduce locking and + serialising. The list accesses are serialised anyway for a given list - a + common cache would mean that we would have to separately serialise access + of all lists within the cache. Because the cache only stores nodes that are + not in the list, releasing the cache does not release any list nodes. This + means that list nodes can be copied or rechained from one list to another + without danger of creating a dangling reference if the original cache goes + away. + + Questionable design decisions: + 1. Retaining the warts for compatibility + 2. Keeping an element count -i.e. counting whenever we do anything + instead of only when we want the count. + 3. Making the chain pointers NULL terminated. If the list object + itself looks just like a node and the list is kept as a ring then + it reduces the number of special cases. All inserts look the same. +*/ + +/* set cursor to the position of each element of list in turn */ +#define INTERNALTRAVERSELIST(list, cursor) \ +for ( cursor = (list).GetHeadPositionI() \ + ; cursor!=NULL \ + ; cursor = (list).Next(cursor) \ + ) + + +/* set cursor to the position of each element of list in turn + in reverse order +*/ +#define INTERNALREVERSETRAVERSELIST(list, cursor) \ +for ( cursor = (list).GetTailPositionI() \ + ; cursor!=NULL \ + ; cursor = (list).Prev(cursor) \ + ) + +/* Constructor calls a separate initialisation function that + creates a node cache, optionally creates a lock object + and optionally creates a signaling object. + + By default we create a locking object, a DEFAULTCACHE sized + cache but no event object so the list cannot be used in calls + to WaitForSingleObject +*/ +CBaseList::CBaseList(__in_opt LPCTSTR pName, // Descriptive list name + INT iItems) : // Node cache size +#ifdef DEBUG + CBaseObject(pName), +#endif + m_pFirst(NULL), + m_pLast(NULL), + m_Count(0), + m_Cache(iItems) +{ +} // constructor + +CBaseList::CBaseList(__in_opt LPCTSTR pName) : // Descriptive list name +#ifdef DEBUG + CBaseObject(pName), +#endif + m_pFirst(NULL), + m_pLast(NULL), + m_Count(0), + m_Cache(DEFAULTCACHE) +{ +} // constructor + +#ifdef UNICODE +CBaseList::CBaseList(__in_opt LPCSTR pName, // Descriptive list name + INT iItems) : // Node cache size +#ifdef DEBUG + CBaseObject(pName), +#endif + m_pFirst(NULL), + m_pLast(NULL), + m_Count(0), + m_Cache(iItems) +{ +} // constructor + +CBaseList::CBaseList(__in_opt LPCSTR pName) : // Descriptive list name +#ifdef DEBUG + CBaseObject(pName), +#endif + m_pFirst(NULL), + m_pLast(NULL), + m_Count(0), + m_Cache(DEFAULTCACHE) +{ +} // constructor + +#endif + +/* The destructor enumerates all the node objects in the list and + in the cache deleting each in turn. We do not do any processing + on the objects that the list holds (i.e. points to) so if they + represent interfaces for example the creator of the list should + ensure that each of them is released before deleting us +*/ +CBaseList::~CBaseList() +{ + /* Delete all our list nodes */ + + RemoveAll(); + +} // destructor + +/* Remove all the nodes from the list but don't do anything + with the objects that each node looks after (this is the + responsibility of the creator). + Aa a last act we reset the signalling event + (if available) to indicate to clients that the list + does not have any entries in it. +*/ +void CBaseList::RemoveAll() +{ + /* Free up all the CNode objects NOTE we don't bother putting the + deleted nodes into the cache as this method is only really called + in serious times of change such as when we are being deleted at + which point the cache will be deleted anway */ + + CNode *pn = m_pFirst; + while (pn) { + CNode *op = pn; + pn = pn->Next(); + delete op; + } + + /* Reset the object count and the list pointers */ + + m_Count = 0; + m_pFirst = m_pLast = NULL; + +} // RemoveAll + + + +/* Return a position enumerator for the entire list. + A position enumerator is a pointer to a node object cast to a + transparent type so all we do is return the head/tail node + pointer in the list. + WARNING because the position is a pointer to a node there is + an implicit assumption for users a the list class that after + deleting an object from the list that any other position + enumerators that you have may be invalid (since the node + may be gone). +*/ +__out_opt POSITION CBaseList::GetHeadPositionI() const +{ + return (POSITION) m_pFirst; +} // GetHeadPosition + + + +__out_opt POSITION CBaseList::GetTailPositionI() const +{ + return (POSITION) m_pLast; +} // GetTailPosition + + + +/* Get the number of objects in the list, + Get the lock before accessing the count. + Locking may not be entirely necessary but it has the side effect + of making sure that all operations are complete before we get it. + So for example if a list is being added to this list then that + will have completed in full before we continue rather than seeing + an intermediate albeit valid state +*/ +int CBaseList::GetCountI() const +{ + return m_Count; +} // GetCount + + + +/* Return the object at rp, update rp to the next object from + the list or NULL if you have moved over the last object. + You may still call this function once we return NULL but + we will continue to return a NULL position value +*/ +__out void *CBaseList::GetNextI(__inout POSITION& rp) const +{ + /* have we reached the end of the list */ + + if (rp == NULL) { + return NULL; + } + + /* Lock the object before continuing */ + + void *pObject; + + /* Copy the original position then step on */ + + CNode *pn = (CNode *) rp; + ASSERT(pn != NULL); + rp = (POSITION) pn->Next(); + + /* Get the object at the original position from the list */ + + pObject = pn->GetData(); + // ASSERT(pObject != NULL); // NULL pointers in the list are allowed. + return pObject; +} //GetNext + + + +/* Return the object at p. + Asking for the object at NULL ASSERTs then returns NULL + The object is NOT locked. The list is not being changed + in any way. If another thread is busy deleting the object + then locking would only result in a change from one bad + behaviour to another. +*/ +__out_opt void *CBaseList::GetI(__in_opt POSITION p) const +{ + if (p == NULL) { + return NULL; + } + + CNode * pn = (CNode *) p; + void *pObject = pn->GetData(); + // ASSERT(pObject != NULL); // NULL pointers in the list are allowed. + return pObject; +} //Get + +__out void *CBaseList::GetValidI(__in POSITION p) const +{ + CNode * pn = (CNode *) p; + void *pObject = pn->GetData(); + // ASSERT(pObject != NULL); // NULL pointers in the list are allowed. + return pObject; +} //Get + + +/* Return the first position in the list which holds the given pointer. + Return NULL if it's not found. +*/ +__out_opt POSITION CBaseList::FindI( __in void * pObj) const +{ + POSITION pn; + INTERNALTRAVERSELIST(*this, pn){ + if (GetI(pn)==pObj) { + return pn; + } + } + return NULL; +} // Find + + + +/* Remove the first node in the list (deletes the pointer to its object + from the list, does not free the object itself). + Return the pointer to its object or NULL if empty +*/ +__out_opt void *CBaseList::RemoveHeadI() +{ + /* All we do is get the head position and ask for that to be deleted. + We could special case this since some of the code path checking + in Remove() is redundant as we know there is no previous + node for example but it seems to gain little over the + added complexity + */ + + return RemoveI((POSITION)m_pFirst); +} // RemoveHead + + + +/* Remove the last node in the list (deletes the pointer to its object + from the list, does not free the object itself). + Return the pointer to its object or NULL if empty +*/ +__out_opt void *CBaseList::RemoveTailI() +{ + /* All we do is get the tail position and ask for that to be deleted. + We could special case this since some of the code path checking + in Remove() is redundant as we know there is no previous + node for example but it seems to gain little over the + added complexity + */ + + return RemoveI((POSITION)m_pLast); +} // RemoveTail + + + +/* Remove the pointer to the object in this position from the list. + Deal with all the chain pointers + Return a pointer to the object removed from the list. + The node object that is freed as a result + of this operation is added to the node cache where + it can be used again. + Remove(NULL) is a harmless no-op - but probably is a wart. +*/ +__out_opt void *CBaseList::RemoveI(__in_opt POSITION pos) +{ + /* Lock the critical section before continuing */ + + // ASSERT (pos!=NULL); // Removing NULL is to be harmless! + if (pos==NULL) return NULL; + + + CNode *pCurrent = (CNode *) pos; + ASSERT(pCurrent != NULL); + + /* Update the previous node */ + + CNode *pNode = pCurrent->Prev(); + if (pNode == NULL) { + m_pFirst = pCurrent->Next(); + } else { + pNode->SetNext(pCurrent->Next()); + } + + /* Update the following node */ + + pNode = pCurrent->Next(); + if (pNode == NULL) { + m_pLast = pCurrent->Prev(); + } else { + pNode->SetPrev(pCurrent->Prev()); + } + + /* Get the object this node was looking after */ + + void *pObject = pCurrent->GetData(); + + // ASSERT(pObject != NULL); // NULL pointers in the list are allowed. + + /* Try and add the node object to the cache - + a NULL return code from the cache means we ran out of room. + The cache size is fixed by a constructor argument when the + list is created and defaults to DEFAULTCACHE. + This means that the cache will have room for this many + node objects. So if you have a list of media samples + and you know there will never be more than five active at + any given time of them for example then override the default + constructor + */ + + m_Cache.AddToCache(pCurrent); + + /* If the list is empty then reset the list event */ + + --m_Count; + ASSERT(m_Count >= 0); + return pObject; +} // Remove + + + +/* Add this object to the tail end of our list + Return the new tail position. +*/ + +__out_opt POSITION CBaseList::AddTailI(__in void *pObject) +{ + /* Lock the critical section before continuing */ + + CNode *pNode; + // ASSERT(pObject); // NULL pointers in the list are allowed. + + /* If there is a node objects in the cache then use + that otherwise we will have to create a new one */ + + pNode = (CNode *) m_Cache.RemoveFromCache(); + if (pNode == NULL) { + pNode = new CNode; + } + + /* Check we have a valid object */ + + if (pNode == NULL) { + return NULL; + } + + /* Initialise all the CNode object + just in case it came from the cache + */ + + pNode->SetData(pObject); + pNode->SetNext(NULL); + pNode->SetPrev(m_pLast); + + if (m_pLast == NULL) { + m_pFirst = pNode; + } else { + m_pLast->SetNext(pNode); + } + + /* Set the new last node pointer and also increment the number + of list entries, the critical section is unlocked when we + exit the function + */ + + m_pLast = pNode; + ++m_Count; + + return (POSITION) pNode; +} // AddTail(object) + + + +/* Add this object to the head end of our list + Return the new head position. +*/ +__out_opt POSITION CBaseList::AddHeadI(__in void *pObject) +{ + CNode *pNode; + // ASSERT(pObject); // NULL pointers in the list are allowed. + + /* If there is a node objects in the cache then use + that otherwise we will have to create a new one */ + + pNode = (CNode *) m_Cache.RemoveFromCache(); + if (pNode == NULL) { + pNode = new CNode; + } + + /* Check we have a valid object */ + + if (pNode == NULL) { + return NULL; + } + + /* Initialise all the CNode object + just in case it came from the cache + */ + + pNode->SetData(pObject); + + /* chain it in (set four pointers) */ + pNode->SetPrev(NULL); + pNode->SetNext(m_pFirst); + + if (m_pFirst == NULL) { + m_pLast = pNode; + } else { + m_pFirst->SetPrev(pNode); + } + m_pFirst = pNode; + + ++m_Count; + + return (POSITION) pNode; +} // AddHead(object) + + + +/* Add all the elements in *pList to the tail of this list. + Return TRUE if it all worked, FALSE if it didn't. + If it fails some elements may have been added. +*/ +BOOL CBaseList::AddTail(__in CBaseList *pList) +{ + /* lock the object before starting then enumerate + each entry in the source list and add them one by one to + our list (while still holding the object lock) + Lock the other list too. + */ + POSITION pos = pList->GetHeadPositionI(); + + while (pos) { + if (NULL == AddTailI(pList->GetNextI(pos))) { + return FALSE; + } + } + return TRUE; +} // AddTail(list) + + + +/* Add all the elements in *pList to the head of this list. + Return TRUE if it all worked, FALSE if it didn't. + If it fails some elements may have been added. +*/ +BOOL CBaseList::AddHead(__in CBaseList *pList) +{ + /* lock the object before starting then enumerate + each entry in the source list and add them one by one to + our list (while still holding the object lock) + Lock the other list too. + + To avoid reversing the list, traverse it backwards. + */ + + POSITION pos; + + INTERNALREVERSETRAVERSELIST(*pList, pos) { + if (NULL== AddHeadI(pList->GetValidI(pos))){ + return FALSE; + } + } + return TRUE; +} // AddHead(list) + + + +/* Add the object after position p + p is still valid after the operation. + AddAfter(NULL,x) adds x to the start - same as AddHead + Return the position of the new object, NULL if it failed +*/ +__out_opt POSITION CBaseList::AddAfterI(__in_opt POSITION pos, __in void * pObj) +{ + if (pos==NULL) + return AddHeadI(pObj); + + /* As someone else might be furkling with the list - + Lock the critical section before continuing + */ + CNode *pAfter = (CNode *) pos; + ASSERT(pAfter != NULL); + if (pAfter==m_pLast) + return AddTailI(pObj); + + /* set pnode to point to a new node, preferably from the cache */ + + CNode *pNode = (CNode *) m_Cache.RemoveFromCache(); + if (pNode == NULL) { + pNode = new CNode; + } + + /* Check we have a valid object */ + + if (pNode == NULL) { + return NULL; + } + + /* Initialise all the CNode object + just in case it came from the cache + */ + + pNode->SetData(pObj); + + /* It is to be added to the middle of the list - there is a before + and after node. Chain it after pAfter, before pBefore. + */ + CNode * pBefore = pAfter->Next(); + ASSERT(pBefore != NULL); + + /* chain it in (set four pointers) */ + pNode->SetPrev(pAfter); + pNode->SetNext(pBefore); + pBefore->SetPrev(pNode); + pAfter->SetNext(pNode); + + ++m_Count; + + return (POSITION) pNode; + +} // AddAfter(object) + + + +BOOL CBaseList::AddAfter(__in_opt POSITION p, __in CBaseList *pList) +{ + POSITION pos; + INTERNALTRAVERSELIST(*pList, pos) { + /* p follows along the elements being added */ + p = AddAfterI(p, pList->GetValidI(pos)); + if (p==NULL) return FALSE; + } + return TRUE; +} // AddAfter(list) + + + +/* Mirror images: + Add the element or list after position p. + p is still valid after the operation. + AddBefore(NULL,x) adds x to the end - same as AddTail +*/ +__out_opt POSITION CBaseList::AddBeforeI(__in_opt POSITION pos, __in void * pObj) +{ + if (pos==NULL) + return AddTailI(pObj); + + /* set pnode to point to a new node, preferably from the cache */ + + CNode *pBefore = (CNode *) pos; + ASSERT(pBefore != NULL); + if (pBefore==m_pFirst) + return AddHeadI(pObj); + + CNode * pNode = (CNode *) m_Cache.RemoveFromCache(); + if (pNode == NULL) { + pNode = new CNode; + } + + /* Check we have a valid object */ + + if (pNode == NULL) { + return NULL; + } + + /* Initialise all the CNode object + just in case it came from the cache + */ + + pNode->SetData(pObj); + + /* It is to be added to the middle of the list - there is a before + and after node. Chain it after pAfter, before pBefore. + */ + + CNode * pAfter = pBefore->Prev(); + ASSERT(pAfter != NULL); + + /* chain it in (set four pointers) */ + pNode->SetPrev(pAfter); + pNode->SetNext(pBefore); + pBefore->SetPrev(pNode); + pAfter->SetNext(pNode); + + ++m_Count; + + return (POSITION) pNode; + +} // Addbefore(object) + + + +BOOL CBaseList::AddBefore(__in_opt POSITION p, __in CBaseList *pList) +{ + POSITION pos; + INTERNALREVERSETRAVERSELIST(*pList, pos) { + /* p follows along the elements being added */ + p = AddBeforeI(p, pList->GetValidI(pos)); + if (p==NULL) return FALSE; + } + return TRUE; +} // AddBefore(list) + + + +/* Split *this after position p in *this + Retain as *this the tail portion of the original *this + Add the head portion to the tail end of *pList + Return TRUE if it all worked, FALSE if it didn't. + + e.g. + foo->MoveToTail(foo->GetHeadPosition(), bar); + moves one element from the head of foo to the tail of bar + foo->MoveToTail(NULL, bar); + is a no-op + foo->MoveToTail(foo->GetTailPosition, bar); + concatenates foo onto the end of bar and empties foo. + + A better, except excessively long name might be + MoveElementsFromHeadThroughPositionToOtherTail +*/ +BOOL CBaseList::MoveToTail + (__in_opt POSITION pos, __in CBaseList *pList) +{ + /* Algorithm: + Note that the elements (including their order) in the concatenation + of *pList to the head of *this is invariant. + 1. Count elements to be moved + 2. Join *pList onto the head of this to make one long chain + 3. Set first/Last pointers in *this and *pList + 4. Break the chain at the new place + 5. Adjust counts + 6. Set/Reset any events + */ + + if (pos==NULL) return TRUE; // no-op. Eliminates special cases later. + + + /* Make cMove the number of nodes to move */ + CNode * p = (CNode *)pos; + int cMove = 0; // number of nodes to move + while(p!=NULL) { + p = p->Prev(); + ++cMove; + } + + + /* Join the two chains together */ + if (pList->m_pLast!=NULL) + pList->m_pLast->SetNext(m_pFirst); + if (m_pFirst!=NULL) + m_pFirst->SetPrev(pList->m_pLast); + + + /* set first and last pointers */ + p = (CNode *)pos; + + if (pList->m_pFirst==NULL) + pList->m_pFirst = m_pFirst; + m_pFirst = p->Next(); + if (m_pFirst==NULL) + m_pLast = NULL; + pList->m_pLast = p; + + + /* Break the chain after p to create the new pieces */ + if (m_pFirst!=NULL) + m_pFirst->SetPrev(NULL); + p->SetNext(NULL); + + + /* Adjust the counts */ + m_Count -= cMove; + pList->m_Count += cMove; + + return TRUE; + +} // MoveToTail + + + +/* Mirror image of MoveToTail: + Split *this before position p in *this. + Retain in *this the head portion of the original *this + Add the tail portion to the start (i.e. head) of *pList + Return TRUE if it all worked, FALSE if it didn't. + + e.g. + foo->MoveToHead(foo->GetTailPosition(), bar); + moves one element from the tail of foo to the head of bar + foo->MoveToHead(NULL, bar); + is a no-op + foo->MoveToHead(foo->GetHeadPosition, bar); + concatenates foo onto the start of bar and empties foo. +*/ +BOOL CBaseList::MoveToHead + (__in_opt POSITION pos, __in CBaseList *pList) +{ + + /* See the comments on the algorithm in MoveToTail */ + + if (pos==NULL) return TRUE; // no-op. Eliminates special cases later. + + /* Make cMove the number of nodes to move */ + CNode * p = (CNode *)pos; + int cMove = 0; // number of nodes to move + while(p!=NULL) { + p = p->Next(); + ++cMove; + } + + + /* Join the two chains together */ + if (pList->m_pFirst!=NULL) + pList->m_pFirst->SetPrev(m_pLast); + if (m_pLast!=NULL) + m_pLast->SetNext(pList->m_pFirst); + + + /* set first and last pointers */ + p = (CNode *)pos; + + + if (pList->m_pLast==NULL) + pList->m_pLast = m_pLast; + + m_pLast = p->Prev(); + if (m_pLast==NULL) + m_pFirst = NULL; + pList->m_pFirst = p; + + + /* Break the chain after p to create the new pieces */ + if (m_pLast!=NULL) + m_pLast->SetNext(NULL); + p->SetPrev(NULL); + + + /* Adjust the counts */ + m_Count -= cMove; + pList->m_Count += cMove; + + return TRUE; + +} // MoveToHead + + + +/* Reverse the order of the [pointers to] objects in *this +*/ +void CBaseList::Reverse() +{ + /* algorithm: + The obvious booby trap is that you flip pointers around and lose + addressability to the node that you are going to process next. + The easy way to avoid this is do do one chain at a time. + + Run along the forward chain, + For each node, set the reverse pointer to the one ahead of us. + The reverse chain is now a copy of the old forward chain, including + the NULL termination. + + Run along the reverse chain (i.e. old forward chain again) + For each node set the forward pointer of the node ahead to point back + to the one we're standing on. + The first node needs special treatment, + it's new forward pointer is NULL. + Finally set the First/Last pointers + + */ + CNode * p; + + // Yes we COULD use a traverse, but it would look funny! + p = m_pFirst; + while (p!=NULL) { + CNode * q; + q = p->Next(); + p->SetNext(p->Prev()); + p->SetPrev(q); + p = q; + } + + p = m_pFirst; + m_pFirst = m_pLast; + m_pLast = p; + + +#if 0 // old version + + if (m_pFirst==NULL) return; // empty list + if (m_pFirst->Next()==NULL) return; // single node list + + + /* run along forward chain */ + for ( p = m_pFirst + ; p!=NULL + ; p = p->Next() + ){ + p->SetPrev(p->Next()); + } + + + /* special case first element */ + m_pFirst->SetNext(NULL); // fix the old first element + + + /* run along new reverse chain i.e. old forward chain again */ + for ( p = m_pFirst // start at the old first element + ; p->Prev()!=NULL // while there's a node still to be set + ; p = p->Prev() // work in the same direction as before + ){ + p->Prev()->SetNext(p); + } + + + /* fix forward and reverse pointers + - the triple XOR swap would work but all the casts look hideous */ + p = m_pFirst; + m_pFirst = m_pLast; + m_pLast = p; +#endif + +} // Reverse + +//------------------------------------------------------------------------------ +// File: AMFilter.cpp +// +// Desc: DirectShow base classes - implements class hierarchy for streams +// architecture. +// +// Copyright (c) 1992-2001 Microsoft Corporation. All rights reserved. +//------------------------------------------------------------------------------ + +#ifdef DXMPERF +#include "dxmperf.h" +#endif // DXMPERF + +//===================================================================== +//===================================================================== +// The following classes are declared in this header: +// +// +// CBaseMediaFilter Basic IMediaFilter support (abstract class) +// CBaseFilter Support for IBaseFilter (incl. IMediaFilter) +// CEnumPins Enumerate input and output pins +// CEnumMediaTypes Enumerate the preferred pin formats +// CBasePin Abstract base class for IPin interface +// CBaseOutputPin Adds data provider member functions +// CBaseInputPin Implements IMemInputPin interface +// CMediaSample Basic transport unit for IMemInputPin +// CBaseAllocator General list guff for most allocators +// CMemAllocator Implements memory buffer allocation +// +//===================================================================== +//===================================================================== + +//===================================================================== +// Helpers +//===================================================================== +STDAPI CreateMemoryAllocator(__deref_out IMemAllocator **ppAllocator) +{ + return CoCreateInstance(CLSID_MemoryAllocator, + 0, + CLSCTX_INPROC_SERVER, + IID_IMemAllocator, + (void **)ppAllocator); +} + +// Put this one here rather than in ctlutil.cpp to avoid linking +// anything brought in by ctlutil.cpp +STDAPI CreatePosPassThru( + __in_opt LPUNKNOWN pAgg, + BOOL bRenderer, + IPin *pPin, + __deref_out IUnknown **ppPassThru +) +{ + *ppPassThru = NULL; + IUnknown *pUnkSeek; + HRESULT hr = CoCreateInstance(CLSID_SeekingPassThru, + pAgg, + CLSCTX_INPROC_SERVER, + IID_IUnknown, + (void **)&pUnkSeek + ); + if (FAILED(hr)) { + return hr; + } + + ISeekingPassThru *pPassThru; + hr = pUnkSeek->QueryInterface(IID_ISeekingPassThru, (void**)&pPassThru); + if (FAILED(hr)) { + pUnkSeek->Release(); + return hr; + } + hr = pPassThru->Init(bRenderer, pPin); + pPassThru->Release(); + if (FAILED(hr)) { + pUnkSeek->Release(); + return hr; + } + *ppPassThru = pUnkSeek; + return S_OK; +} + + + +#define CONNECT_TRACE_LEVEL 3 + +//===================================================================== +//===================================================================== +// Implements CBaseMediaFilter +//===================================================================== +//===================================================================== + + +/* Constructor */ + +CBaseMediaFilter::CBaseMediaFilter(__in_opt LPCTSTR pName, + __inout_opt LPUNKNOWN pUnk, + __in CCritSec *pLock, + REFCLSID clsid) : + CUnknown(pName, pUnk), + m_pLock(pLock), + m_clsid(clsid), + m_State(State_Stopped), + m_pClock(NULL) +{ +} + + +/* Destructor */ + +CBaseMediaFilter::~CBaseMediaFilter() +{ + // must be stopped, but can't call Stop here since + // our critsec has been destroyed. + + /* Release any clock we were using */ + + if (m_pClock) { + m_pClock->Release(); + m_pClock = NULL; + } +} + + +/* Override this to say what interfaces we support and where */ + +STDMETHODIMP +CBaseMediaFilter::NonDelegatingQueryInterface( + REFIID riid, + __deref_out void ** ppv) +{ + if (riid == IID_IMediaFilter) { + return GetInterface((IMediaFilter *) this, ppv); + } else if (riid == IID_IPersist) { + return GetInterface((IPersist *) this, ppv); + } else { + return CUnknown::NonDelegatingQueryInterface(riid, ppv); + } +} + +/* Return the filter's clsid */ +STDMETHODIMP +CBaseMediaFilter::GetClassID(__out CLSID *pClsID) +{ + CheckPointer(pClsID,E_POINTER); + ValidateReadWritePtr(pClsID,sizeof(CLSID)); + *pClsID = m_clsid; + return NOERROR; +} + +/* Override this if your state changes are not done synchronously */ + +STDMETHODIMP +CBaseMediaFilter::GetState(DWORD dwMSecs, __out FILTER_STATE *State) +{ + UNREFERENCED_PARAMETER(dwMSecs); + CheckPointer(State,E_POINTER); + ValidateReadWritePtr(State,sizeof(FILTER_STATE)); + + *State = m_State; + return S_OK; +} + + +/* Set the clock we will use for synchronisation */ + +STDMETHODIMP +CBaseMediaFilter::SetSyncSource(__inout_opt IReferenceClock *pClock) +{ + CAutoLock cObjectLock(m_pLock); + + // Ensure the new one does not go away - even if the same as the old + if (pClock) { + pClock->AddRef(); + } + + // if we have a clock, release it + if (m_pClock) { + m_pClock->Release(); + } + + // Set the new reference clock (might be NULL) + // Should we query it to ensure it is a clock? Consider for a debug build. + m_pClock = pClock; + + return NOERROR; +} + +/* Return the clock we are using for synchronisation */ +STDMETHODIMP +CBaseMediaFilter::GetSyncSource(__deref_out_opt IReferenceClock **pClock) +{ + CheckPointer(pClock,E_POINTER); + ValidateReadWritePtr(pClock,sizeof(IReferenceClock *)); + CAutoLock cObjectLock(m_pLock); + + if (m_pClock) { + // returning an interface... addref it... + m_pClock->AddRef(); + } + *pClock = (IReferenceClock*)m_pClock; + return NOERROR; +} + + +/* Put the filter into a stopped state */ + +STDMETHODIMP +CBaseMediaFilter::Stop() +{ + CAutoLock cObjectLock(m_pLock); + + m_State = State_Stopped; + return S_OK; +} + + +/* Put the filter into a paused state */ + +STDMETHODIMP +CBaseMediaFilter::Pause() +{ + CAutoLock cObjectLock(m_pLock); + + m_State = State_Paused; + return S_OK; +} + + +// Put the filter into a running state. + +// The time parameter is the offset to be added to the samples' +// stream time to get the reference time at which they should be presented. +// +// you can either add these two and compare it against the reference clock, +// or you can call CBaseMediaFilter::StreamTime and compare that against +// the sample timestamp. + +STDMETHODIMP +CBaseMediaFilter::Run(REFERENCE_TIME tStart) +{ + CAutoLock cObjectLock(m_pLock); + + // remember the stream time offset + m_tStart = tStart; + + if (m_State == State_Stopped){ + HRESULT hr = Pause(); + + if (FAILED(hr)) { + return hr; + } + } + m_State = State_Running; + return S_OK; +} + + +// +// return the current stream time - samples with start timestamps of this +// time or before should be rendered by now +HRESULT +CBaseMediaFilter::StreamTime(CRefTime& rtStream) +{ + // Caller must lock for synchronization + // We can't grab the filter lock because we want to be able to call + // this from worker threads without deadlocking + + if (m_pClock == NULL) { + return VFW_E_NO_CLOCK; + } + + // get the current reference time + HRESULT hr = m_pClock->GetTime((REFERENCE_TIME*)&rtStream); + if (FAILED(hr)) { + return hr; + } + + // subtract the stream offset to get stream time + rtStream -= m_tStart; + + return S_OK; +} + + +//===================================================================== +//===================================================================== +// Implements CBaseFilter +//===================================================================== +//===================================================================== + + +/* Override this to say what interfaces we support and where */ + +STDMETHODIMP CBaseFilter::NonDelegatingQueryInterface(REFIID riid, + __deref_out void **ppv) +{ + /* Do we have this interface */ + + if (riid == IID_IBaseFilter) { + return GetInterface((IBaseFilter *) this, ppv); + } else if (riid == IID_IMediaFilter) { + return GetInterface((IMediaFilter *) this, ppv); + } else if (riid == IID_IPersist) { + return GetInterface((IPersist *) this, ppv); + } else if (riid == IID_IAMovieSetup) { + return GetInterface((IAMovieSetup *) this, ppv); + } else { + return CUnknown::NonDelegatingQueryInterface(riid, ppv); + } +} + +#ifdef DEBUG +STDMETHODIMP_(ULONG) CBaseFilter::NonDelegatingRelease() +{ + if (m_cRef == 1) { + KASSERT(m_pGraph == NULL); + } + return CUnknown::NonDelegatingRelease(); +} +#endif + + +/* Constructor */ + +CBaseFilter::CBaseFilter(__in_opt LPCTSTR pName, + __inout_opt LPUNKNOWN pUnk, + __in CCritSec *pLock, + REFCLSID clsid) : + CUnknown( pName, pUnk ), + m_pLock(pLock), + m_clsid(clsid), + m_State(State_Stopped), + m_pClock(NULL), + m_pGraph(NULL), + m_pSink(NULL), + m_pName(NULL), + m_PinVersion(1) +{ +#ifdef DXMPERF + PERFLOG_CTOR( pName ? pName : L"CBaseFilter", (IBaseFilter *) this ); +#endif // DXMPERF + + ASSERT(pLock != NULL); +} + +/* Passes in a redundant HRESULT argument */ + +CBaseFilter::CBaseFilter(__in_opt LPCTSTR pName, + __in_opt LPUNKNOWN pUnk, + __in CCritSec *pLock, + REFCLSID clsid, + __inout HRESULT *phr) : + CUnknown( pName, pUnk ), + m_pLock(pLock), + m_clsid(clsid), + m_State(State_Stopped), + m_pClock(NULL), + m_pGraph(NULL), + m_pSink(NULL), + m_pName(NULL), + m_PinVersion(1) +{ +#ifdef DXMPERF + PERFLOG_CTOR( pName ? pName : L"CBaseFilter", (IBaseFilter *) this ); +#endif // DXMPERF + + ASSERT(pLock != NULL); + UNREFERENCED_PARAMETER(phr); +} + +#ifdef UNICODE +CBaseFilter::CBaseFilter(__in_opt LPCSTR pName, + __in_opt LPUNKNOWN pUnk, + __in CCritSec *pLock, + REFCLSID clsid) : + CUnknown( pName, pUnk ), + m_pLock(pLock), + m_clsid(clsid), + m_State(State_Stopped), + m_pClock(NULL), + m_pGraph(NULL), + m_pSink(NULL), + m_pName(NULL), + m_PinVersion(1) +{ +#ifdef DXMPERF + PERFLOG_CTOR( L"CBaseFilter", (IBaseFilter *) this ); +#endif // DXMPERF + + ASSERT(pLock != NULL); +} +CBaseFilter::CBaseFilter(__in_opt LPCSTR pName, + __in_opt LPUNKNOWN pUnk, + __in CCritSec *pLock, + REFCLSID clsid, + __inout HRESULT *phr) : + CUnknown( pName, pUnk ), + m_pLock(pLock), + m_clsid(clsid), + m_State(State_Stopped), + m_pClock(NULL), + m_pGraph(NULL), + m_pSink(NULL), + m_pName(NULL), + m_PinVersion(1) +{ +#ifdef DXMPERF + PERFLOG_CTOR( L"CBaseFilter", (IBaseFilter *) this ); +#endif // DXMPERF + + ASSERT(pLock != NULL); + UNREFERENCED_PARAMETER(phr); +} +#endif + +/* Destructor */ + +CBaseFilter::~CBaseFilter() +{ +#ifdef DXMPERF + PERFLOG_DTOR( L"CBaseFilter", (IBaseFilter *) this ); +#endif // DXMPERF + + // NOTE we do NOT hold references on the filtergraph for m_pGraph or m_pSink + // When we did we had the circular reference problem. Nothing would go away. + + delete[] m_pName; + + // must be stopped, but can't call Stop here since + // our critsec has been destroyed. + + /* Release any clock we were using */ + if (m_pClock) { + m_pClock->Release(); + m_pClock = NULL; + } +} + +/* Return the filter's clsid */ +STDMETHODIMP +CBaseFilter::GetClassID(__out CLSID *pClsID) +{ + CheckPointer(pClsID,E_POINTER); + ValidateReadWritePtr(pClsID,sizeof(CLSID)); + *pClsID = m_clsid; + return NOERROR; +} + +/* Override this if your state changes are not done synchronously */ +STDMETHODIMP +CBaseFilter::GetState(DWORD dwMSecs, __out FILTER_STATE *State) +{ + UNREFERENCED_PARAMETER(dwMSecs); + CheckPointer(State,E_POINTER); + ValidateReadWritePtr(State,sizeof(FILTER_STATE)); + + *State = m_State; + return S_OK; +} + + +/* Set the clock we will use for synchronisation */ + +STDMETHODIMP +CBaseFilter::SetSyncSource(__in_opt IReferenceClock *pClock) +{ + CAutoLock cObjectLock(m_pLock); + + // Ensure the new one does not go away - even if the same as the old + if (pClock) { + pClock->AddRef(); + } + + // if we have a clock, release it + if (m_pClock) { + m_pClock->Release(); + } + + // Set the new reference clock (might be NULL) + // Should we query it to ensure it is a clock? Consider for a debug build. + m_pClock = pClock; + + return NOERROR; +} + +/* Return the clock we are using for synchronisation */ +STDMETHODIMP +CBaseFilter::GetSyncSource(__deref_out_opt IReferenceClock **pClock) +{ + CheckPointer(pClock,E_POINTER); + ValidateReadWritePtr(pClock,sizeof(IReferenceClock *)); + CAutoLock cObjectLock(m_pLock); + + if (m_pClock) { + // returning an interface... addref it... + m_pClock->AddRef(); + } + *pClock = (IReferenceClock*)m_pClock; + return NOERROR; +} + + + +// override CBaseMediaFilter Stop method, to deactivate any pins this +// filter has. +STDMETHODIMP +CBaseFilter::Stop() +{ + CAutoLock cObjectLock(m_pLock); + HRESULT hr = NOERROR; + + // notify all pins of the state change + if (m_State != State_Stopped) { + int cPins = GetPinCount(); + for (int c = 0; c < cPins; c++) { + + CBasePin *pPin = GetPin(c); + if (NULL == pPin) { + break; + } + + // Disconnected pins are not activated - this saves pins worrying + // about this state themselves. We ignore the return code to make + // sure everyone is inactivated regardless. The base input pin + // class can return an error if it has no allocator but Stop can + // be used to resync the graph state after something has gone bad + + if (pPin->IsConnected()) { + HRESULT hrTmp = pPin->Inactive(); + if (FAILED(hrTmp) && SUCCEEDED(hr)) { + hr = hrTmp; + } + } + } + } + +#ifdef DXMPERF + PERFLOG_STOP( m_pName ? m_pName : L"CBaseFilter", (IBaseFilter *) this, m_State ); +#endif // DXMPERF + + m_State = State_Stopped; + return hr; +} + + +// override CBaseMediaFilter Pause method to activate any pins +// this filter has (also called from Run) + +STDMETHODIMP +CBaseFilter::Pause() +{ + CAutoLock cObjectLock(m_pLock); + + // notify all pins of the change to active state + if (m_State == State_Stopped) { + int cPins = GetPinCount(); + for (int c = 0; c < cPins; c++) { + + CBasePin *pPin = GetPin(c); + if (NULL == pPin) { + break; + } + + // Disconnected pins are not activated - this saves pins + // worrying about this state themselves + + if (pPin->IsConnected()) { + HRESULT hr = pPin->Active(); + if (FAILED(hr)) { + return hr; + } + } + } + } + + +#ifdef DXMPERF + PERFLOG_PAUSE( m_pName ? m_pName : L"CBaseFilter", (IBaseFilter *) this, m_State ); +#endif // DXMPERF + + m_State = State_Paused; + return S_OK; +} + +// Put the filter into a running state. + +// The time parameter is the offset to be added to the samples' +// stream time to get the reference time at which they should be presented. +// +// you can either add these two and compare it against the reference clock, +// or you can call CBaseFilter::StreamTime and compare that against +// the sample timestamp. + +STDMETHODIMP +CBaseFilter::Run(REFERENCE_TIME tStart) +{ + CAutoLock cObjectLock(m_pLock); + + // remember the stream time offset + m_tStart = tStart; + + if (m_State == State_Stopped){ + HRESULT hr = Pause(); + + if (FAILED(hr)) { + return hr; + } + } + // notify all pins of the change to active state + if (m_State != State_Running) { + int cPins = GetPinCount(); + for (int c = 0; c < cPins; c++) { + + CBasePin *pPin = GetPin(c); + if (NULL == pPin) { + break; + } + + // Disconnected pins are not activated - this saves pins + // worrying about this state themselves + + if (pPin->IsConnected()) { + HRESULT hr = pPin->Run(tStart); + if (FAILED(hr)) { + return hr; + } + } + } + } + +#ifdef DXMPERF + PERFLOG_RUN( m_pName ? m_pName : L"CBaseFilter", (IBaseFilter *) this, tStart, m_State ); +#endif // DXMPERF + + m_State = State_Running; + return S_OK; +} + +// +// return the current stream time - samples with start timestamps of this +// time or before should be rendered by now +HRESULT +CBaseFilter::StreamTime(CRefTime& rtStream) +{ + // Caller must lock for synchronization + // We can't grab the filter lock because we want to be able to call + // this from worker threads without deadlocking + + if (m_pClock == NULL) { + return VFW_E_NO_CLOCK; + } + + // get the current reference time + HRESULT hr = m_pClock->GetTime((REFERENCE_TIME*)&rtStream); + if (FAILED(hr)) { + return hr; + } + + // subtract the stream offset to get stream time + rtStream -= m_tStart; + + return S_OK; +} + + +/* Create an enumerator for the pins attached to this filter */ + +STDMETHODIMP +CBaseFilter::EnumPins(__deref_out IEnumPins **ppEnum) +{ + CheckPointer(ppEnum,E_POINTER); + ValidateReadWritePtr(ppEnum,sizeof(IEnumPins *)); + + /* Create a new ref counted enumerator */ + + *ppEnum = new CEnumPins(this, + NULL); + + return *ppEnum == NULL ? E_OUTOFMEMORY : NOERROR; +} + + +// default behaviour of FindPin is to assume pins are named +// by their pin names +STDMETHODIMP +CBaseFilter::FindPin( + LPCWSTR Id, + __deref_out IPin ** ppPin +) +{ + CheckPointer(ppPin,E_POINTER); + ValidateReadWritePtr(ppPin,sizeof(IPin *)); + + // We're going to search the pin list so maintain integrity + CAutoLock lck(m_pLock); + int iCount = GetPinCount(); + for (int i = 0; i < iCount; i++) { + CBasePin *pPin = GetPin(i); + if (NULL == pPin) { + break; + } + + if (0 == lstrcmpW(pPin->Name(), Id)) { + // Found one that matches + // + // AddRef() and return it + *ppPin = pPin; + pPin->AddRef(); + return S_OK; + } + } + *ppPin = NULL; + return VFW_E_NOT_FOUND; +} + +/* Return information about this filter */ + +STDMETHODIMP +CBaseFilter::QueryFilterInfo(__out FILTER_INFO * pInfo) +{ + CheckPointer(pInfo,E_POINTER); + ValidateReadWritePtr(pInfo,sizeof(FILTER_INFO)); + + if (m_pName) { + (void)StringCchCopyW(pInfo->achName, NUMELMS(pInfo->achName), m_pName); + } else { + pInfo->achName[0] = L'\0'; + } + pInfo->pGraph = m_pGraph; + if (m_pGraph) + m_pGraph->AddRef(); + return NOERROR; +} + + +/* Provide the filter with a filter graph */ + +STDMETHODIMP +CBaseFilter::JoinFilterGraph( + __inout_opt IFilterGraph * pGraph, + __in_opt LPCWSTR pName) +{ + CAutoLock cObjectLock(m_pLock); + + // NOTE: we no longer hold references on the graph (m_pGraph, m_pSink) + + m_pGraph = pGraph; + if (m_pGraph) { + HRESULT hr = m_pGraph->QueryInterface(IID_IMediaEventSink, + (void**) &m_pSink); + if (FAILED(hr)) { + ASSERT(m_pSink == NULL); + } + else m_pSink->Release(); // we do NOT keep a reference on it. + } else { + // if graph pointer is null, then we should + // also release the IMediaEventSink on the same object - we don't + // refcount it, so just set it to null + m_pSink = NULL; + } + + + if (m_pName) { + delete[] m_pName; + m_pName = NULL; + } + + if (pName) { + size_t namelen; + HRESULT hr = StringCchLengthW(pName, STRSAFE_MAX_CCH, &namelen); + if (FAILED(hr)) { + return hr; + } + m_pName = new WCHAR[namelen + 1]; + if (m_pName) { + (void)StringCchCopyW(m_pName, namelen + 1, pName); + } else { + return E_OUTOFMEMORY; + } + } + +#ifdef DXMPERF + PERFLOG_JOINGRAPH( m_pName ? m_pName : L"CBaseFilter",(IBaseFilter *) this, pGraph ); +#endif // DXMPERF + + return NOERROR; +} + + +// return a Vendor information string. Optional - may return E_NOTIMPL. +// memory returned should be freed using CoTaskMemFree +// default implementation returns E_NOTIMPL +STDMETHODIMP +CBaseFilter::QueryVendorInfo( + __deref_out LPWSTR* pVendorInfo) +{ + UNREFERENCED_PARAMETER(pVendorInfo); + return E_NOTIMPL; +} + + +// send an event notification to the filter graph if we know about it. +// returns S_OK if delivered, S_FALSE if the filter graph does not sink +// events, or an error otherwise. +HRESULT +CBaseFilter::NotifyEvent( + long EventCode, + LONG_PTR EventParam1, + LONG_PTR EventParam2) +{ + // Snapshot so we don't have to lock up + IMediaEventSink *pSink = m_pSink; + if (pSink) { + if (EC_COMPLETE == EventCode) { + EventParam2 = (LONG_PTR)(IBaseFilter*)this; + } + + return pSink->Notify(EventCode, EventParam1, EventParam2); + } else { + return E_NOTIMPL; + } +} + +// Request reconnect +// pPin is the pin to reconnect +// pmt is the type to reconnect with - can be NULL +// Calls ReconnectEx on the filter graph +HRESULT +CBaseFilter::ReconnectPin( + IPin *pPin, + __in_opt AM_MEDIA_TYPE const *pmt +) +{ + IFilterGraph2 *pGraph2; + if (m_pGraph != NULL) { + HRESULT hr = m_pGraph->QueryInterface(IID_IFilterGraph2, (void **)&pGraph2); + if (SUCCEEDED(hr)) { + hr = pGraph2->ReconnectEx(pPin, pmt); + pGraph2->Release(); + return hr; + } else { + return m_pGraph->Reconnect(pPin); + } + } else { + return E_NOINTERFACE; + } +} + + + +/* This is the same idea as the media type version does for type enumeration + on pins but for the list of pins available. So if the list of pins you + provide changes dynamically then either override this virtual function + to provide the version number, or more simply call IncrementPinVersion */ + +LONG CBaseFilter::GetPinVersion() +{ + return m_PinVersion; +} + + +/* Increment the current pin version cookie */ + +void CBaseFilter::IncrementPinVersion() +{ + InterlockedIncrement(&m_PinVersion); +} + +/* register filter */ + +STDMETHODIMP CBaseFilter::Register() +{ + // get setup data, if it exists + // + LPAMOVIESETUP_FILTER psetupdata = GetSetupData(); + + // check we've got data + // + if( NULL == psetupdata ) return S_FALSE; + + // init is ref counted so call just in case + // we're being called cold. + // + HRESULT hr = CoInitialize( (LPVOID)NULL ); + ASSERT( SUCCEEDED(hr) ); + + // get hold of IFilterMapper + // + IFilterMapper *pIFM; + hr = CoCreateInstance( CLSID_FilterMapper + , NULL + , CLSCTX_INPROC_SERVER + , IID_IFilterMapper + , (void **)&pIFM ); + if( SUCCEEDED(hr) ) + { + hr = AMovieSetupRegisterFilter( psetupdata, pIFM, TRUE ); + pIFM->Release(); + } + + // and clear up + // + CoFreeUnusedLibraries(); + CoUninitialize(); + + return NOERROR; +} + + +/* unregister filter */ + +STDMETHODIMP CBaseFilter::Unregister() +{ + // get setup data, if it exists + // + LPAMOVIESETUP_FILTER psetupdata = GetSetupData(); + + // check we've got data + // + if( NULL == psetupdata ) return S_FALSE; + + // OLE init is ref counted so call + // just in case we're being called cold. + // + HRESULT hr = CoInitialize( (LPVOID)NULL ); + ASSERT( SUCCEEDED(hr) ); + + // get hold of IFilterMapper + // + IFilterMapper *pIFM; + hr = CoCreateInstance( CLSID_FilterMapper + , NULL + , CLSCTX_INPROC_SERVER + , IID_IFilterMapper + , (void **)&pIFM ); + if( SUCCEEDED(hr) ) + { + hr = AMovieSetupRegisterFilter( psetupdata, pIFM, FALSE ); + + // release interface + // + pIFM->Release(); + } + + // clear up + // + CoFreeUnusedLibraries(); + CoUninitialize(); + + // handle one acceptable "error" - that + // of filter not being registered! + // (couldn't find a suitable #define'd + // name for the error!) + // + if( 0x80070002 == hr) + return NOERROR; + else + return hr; +} + + +//===================================================================== +//===================================================================== +// Implements CEnumPins +//===================================================================== +//===================================================================== + + +CEnumPins::CEnumPins(__in CBaseFilter *pFilter, + __in_opt CEnumPins *pEnumPins) : + m_Position(0), + m_PinCount(0), + m_pFilter(pFilter), + m_cRef(1), // Already ref counted + m_PinCache(NAME("Pin Cache")) +{ + +#ifdef DEBUG + m_dwCookie = DbgRegisterObjectCreation("CEnumPins", 0); +#endif + + /* We must be owned by a filter derived from CBaseFilter */ + + ASSERT(pFilter != NULL); + + /* Hold a reference count on our filter */ + m_pFilter->AddRef(); + + /* Are we creating a new enumerator */ + + if (pEnumPins == NULL) { + m_Version = m_pFilter->GetPinVersion(); + m_PinCount = m_pFilter->GetPinCount(); + } else { + ASSERT(m_Position <= m_PinCount); + m_Position = pEnumPins->m_Position; + m_PinCount = pEnumPins->m_PinCount; + m_Version = pEnumPins->m_Version; + m_PinCache.AddTail(&(pEnumPins->m_PinCache)); + } +} + + +/* Destructor releases the reference count on our filter NOTE since we hold + a reference count on the filter who created us we know it is safe to + release it, no access can be made to it afterwards though as we have just + caused the last reference count to go and the object to be deleted */ + +CEnumPins::~CEnumPins() +{ + m_pFilter->Release(); + +#ifdef DEBUG + DbgRegisterObjectDestruction(m_dwCookie); +#endif +} + + +/* Override this to say what interfaces we support where */ + +STDMETHODIMP +CEnumPins::QueryInterface(REFIID riid, __deref_out void **ppv) +{ + CheckPointer(ppv, E_POINTER); + + /* Do we have this interface */ + + if (riid == IID_IEnumPins || riid == IID_IUnknown) { + return GetInterface((IEnumPins *) this, ppv); + } else { + *ppv = NULL; + return E_NOINTERFACE; + } +} + +STDMETHODIMP_(ULONG) +CEnumPins::AddRef() +{ + return InterlockedIncrement(&m_cRef); +} + +STDMETHODIMP_(ULONG) +CEnumPins::Release() +{ + ULONG cRef = InterlockedDecrement(&m_cRef); + if (cRef == 0) { + delete this; + } + return cRef; +} + +/* One of an enumerator's basic member functions allows us to create a cloned + interface that initially has the same state. Since we are taking a snapshot + of an object (current position and all) we must lock access at the start */ + +STDMETHODIMP +CEnumPins::Clone(__deref_out IEnumPins **ppEnum) +{ + CheckPointer(ppEnum,E_POINTER); + ValidateReadWritePtr(ppEnum,sizeof(IEnumPins *)); + HRESULT hr = NOERROR; + + /* Check we are still in sync with the filter */ + if (AreWeOutOfSync() == TRUE) { + *ppEnum = NULL; + hr = VFW_E_ENUM_OUT_OF_SYNC; + } else { + *ppEnum = new CEnumPins(m_pFilter, + this); + if (*ppEnum == NULL) { + hr = E_OUTOFMEMORY; + } + } + return hr; +} + + +/* Return the next pin after the current position */ + +STDMETHODIMP +CEnumPins::Next(ULONG cPins, // place this many pins... + __out_ecount(cPins) IPin **ppPins, // ...in this array + __out_opt ULONG *pcFetched) // actual count passed returned here +{ + CheckPointer(ppPins,E_POINTER); + ValidateReadWritePtr(ppPins,cPins * sizeof(IPin *)); + + ASSERT(ppPins); + + if (pcFetched!=NULL) { + ValidateWritePtr(pcFetched, sizeof(ULONG)); + *pcFetched = 0; // default unless we succeed + } + // now check that the parameter is valid + else if (cPins>1) { // pcFetched == NULL + return E_INVALIDARG; + } + ULONG cFetched = 0; // increment as we get each one. + + /* Check we are still in sync with the filter */ + if (AreWeOutOfSync() == TRUE) { + // If we are out of sync, we should refresh the enumerator. + // This will reset the position and update the other members, but + // will not clear cache of pins we have already returned. + Refresh(); + } + + /* Return each pin interface NOTE GetPin returns CBasePin * not addrefed + so we must QI for the IPin (which increments its reference count) + If while we are retrieving a pin from the filter an error occurs we + assume that our internal state is stale with respect to the filter + (for example someone has deleted a pin) so we + return VFW_E_ENUM_OUT_OF_SYNC */ + + while (cFetched < cPins && m_PinCount > m_Position) { + + /* Get the next pin object from the filter */ + + CBasePin *pPin = m_pFilter->GetPin(m_Position++); + if (pPin == NULL) { + // If this happend, and it's not the first time through, then we've got a problem, + // since we should really go back and release the iPins, which we have previously + // AddRef'ed. + ASSERT( cFetched==0 ); + return VFW_E_ENUM_OUT_OF_SYNC; + } + + /* We only want to return this pin, if it is not in our cache */ + if (0 == m_PinCache.Find(pPin)) + { + /* From the object get an IPin interface */ + + *ppPins = pPin; + pPin->AddRef(); + + cFetched++; + ppPins++; + + m_PinCache.AddTail(pPin); + } + } + + if (pcFetched!=NULL) { + *pcFetched = cFetched; + } + + return (cPins==cFetched ? NOERROR : S_FALSE); +} + + +/* Skip over one or more entries in the enumerator */ + +STDMETHODIMP +CEnumPins::Skip(ULONG cPins) +{ + /* Check we are still in sync with the filter */ + if (AreWeOutOfSync() == TRUE) { + return VFW_E_ENUM_OUT_OF_SYNC; + } + + /* Work out how many pins are left to skip over */ + /* We could position at the end if we are asked to skip too many... */ + /* ..which would match the base implementation for CEnumMediaTypes::Skip */ + + ULONG PinsLeft = m_PinCount - m_Position; + if (cPins > PinsLeft) { + return S_FALSE; + } + m_Position += cPins; + return NOERROR; +} + + +/* Set the current position back to the start */ +/* Reset has 4 simple steps: + * + * Set position to head of list + * Sync enumerator with object being enumerated + * Clear the cache of pins already returned + * return S_OK + */ + +STDMETHODIMP +CEnumPins::Reset() +{ + m_Version = m_pFilter->GetPinVersion(); + m_PinCount = m_pFilter->GetPinCount(); + + m_Position = 0; + + // Clear the cache + m_PinCache.RemoveAll(); + + return S_OK; +} + + +/* Set the current position back to the start */ +/* Refresh has 3 simple steps: + * + * Set position to head of list + * Sync enumerator with object being enumerated + * return S_OK + */ + +STDMETHODIMP +CEnumPins::Refresh() +{ + m_Version = m_pFilter->GetPinVersion(); + m_PinCount = m_pFilter->GetPinCount(); + + m_Position = 0; + return S_OK; +} + + +//===================================================================== +//===================================================================== +// Implements CEnumMediaTypes +//===================================================================== +//===================================================================== + + +CEnumMediaTypes::CEnumMediaTypes(__in CBasePin *pPin, + __in_opt CEnumMediaTypes *pEnumMediaTypes) : + m_Position(0), + m_pPin(pPin), + m_cRef(1) +{ + +#ifdef DEBUG + m_dwCookie = DbgRegisterObjectCreation("CEnumMediaTypes", 0); +#endif + + /* We must be owned by a pin derived from CBasePin */ + + ASSERT(pPin != NULL); + + /* Hold a reference count on our pin */ + m_pPin->AddRef(); + + /* Are we creating a new enumerator */ + + if (pEnumMediaTypes == NULL) { + m_Version = m_pPin->GetMediaTypeVersion(); + return; + } + + m_Position = pEnumMediaTypes->m_Position; + m_Version = pEnumMediaTypes->m_Version; +} + + +/* Destructor releases the reference count on our base pin. NOTE since we hold + a reference count on the pin who created us we know it is safe to release + it, no access can be made to it afterwards though as we might have just + caused the last reference count to go and the object to be deleted */ + +CEnumMediaTypes::~CEnumMediaTypes() +{ +#ifdef DEBUG + DbgRegisterObjectDestruction(m_dwCookie); +#endif + m_pPin->Release(); +} + + +/* Override this to say what interfaces we support where */ + +STDMETHODIMP +CEnumMediaTypes::QueryInterface(REFIID riid, __deref_out void **ppv) +{ + CheckPointer(ppv, E_POINTER); + + /* Do we have this interface */ + + if (riid == IID_IEnumMediaTypes || riid == IID_IUnknown) { + return GetInterface((IEnumMediaTypes *) this, ppv); + } else { + *ppv = NULL; + return E_NOINTERFACE; + } +} + +STDMETHODIMP_(ULONG) +CEnumMediaTypes::AddRef() +{ + return InterlockedIncrement(&m_cRef); +} + +STDMETHODIMP_(ULONG) +CEnumMediaTypes::Release() +{ + ULONG cRef = InterlockedDecrement(&m_cRef); + if (cRef == 0) { + delete this; + } + return cRef; +} + +/* One of an enumerator's basic member functions allows us to create a cloned + interface that initially has the same state. Since we are taking a snapshot + of an object (current position and all) we must lock access at the start */ + +STDMETHODIMP +CEnumMediaTypes::Clone(__deref_out IEnumMediaTypes **ppEnum) +{ + CheckPointer(ppEnum,E_POINTER); + ValidateReadWritePtr(ppEnum,sizeof(IEnumMediaTypes *)); + HRESULT hr = NOERROR; + + /* Check we are still in sync with the pin */ + if (AreWeOutOfSync() == TRUE) { + *ppEnum = NULL; + hr = VFW_E_ENUM_OUT_OF_SYNC; + } else { + + *ppEnum = new CEnumMediaTypes(m_pPin, + this); + + if (*ppEnum == NULL) { + hr = E_OUTOFMEMORY; + } + } + return hr; +} + + +/* Enumerate the next pin(s) after the current position. The client using this + interface passes in a pointer to an array of pointers each of which will + be filled in with a pointer to a fully initialised media type format + Return NOERROR if it all works, + S_FALSE if fewer than cMediaTypes were enumerated. + VFW_E_ENUM_OUT_OF_SYNC if the enumerator has been broken by + state changes in the filter + The actual count always correctly reflects the number of types in the array. +*/ + +STDMETHODIMP +CEnumMediaTypes::Next(ULONG cMediaTypes, // place this many types... + __out_ecount(cMediaTypes) AM_MEDIA_TYPE **ppMediaTypes, // ...in this array + __out ULONG *pcFetched) // actual count passed +{ + CheckPointer(ppMediaTypes,E_POINTER); + ValidateReadWritePtr(ppMediaTypes,cMediaTypes * sizeof(AM_MEDIA_TYPE *)); + /* Check we are still in sync with the pin */ + if (AreWeOutOfSync() == TRUE) { + return VFW_E_ENUM_OUT_OF_SYNC; + } + + if (pcFetched!=NULL) { + ValidateWritePtr(pcFetched, sizeof(ULONG)); + *pcFetched = 0; // default unless we succeed + } + // now check that the parameter is valid + else if (cMediaTypes>1) { // pcFetched == NULL + return E_INVALIDARG; + } + ULONG cFetched = 0; // increment as we get each one. + + /* Return each media type by asking the filter for them in turn - If we + have an error code retured to us while we are retrieving a media type + we assume that our internal state is stale with respect to the filter + (for example the window size changing) so we return + VFW_E_ENUM_OUT_OF_SYNC */ + + while (cMediaTypes) { + + CMediaType cmt; + + HRESULT hr = m_pPin->GetMediaType(m_Position++, &cmt); + if (S_OK != hr) { + break; + } + + /* We now have a CMediaType object that contains the next media type + but when we assign it to the array position we CANNOT just assign + the AM_MEDIA_TYPE structure because as soon as the object goes out of + scope it will delete the memory we have just copied. The function + we use is CreateMediaType which allocates a task memory block */ + + /* Transfer across the format block manually to save an allocate + and free on the format block and generally go faster */ + + *ppMediaTypes = (AM_MEDIA_TYPE *)CoTaskMemAlloc(sizeof(AM_MEDIA_TYPE)); + if (*ppMediaTypes == NULL) { + break; + } + + /* Do a regular copy */ + **ppMediaTypes = cmt; + + /* Make sure the destructor doesn't free these */ + cmt.pbFormat = NULL; + cmt.cbFormat = NULL; + cmt.pUnk = NULL; + + + ppMediaTypes++; + cFetched++; + cMediaTypes--; + } + + if (pcFetched!=NULL) { + *pcFetched = cFetched; + } + + return ( cMediaTypes==0 ? NOERROR : S_FALSE ); +} + + +/* Skip over one or more entries in the enumerator */ + +STDMETHODIMP +CEnumMediaTypes::Skip(ULONG cMediaTypes) +{ + // If we're skipping 0 elements we're guaranteed to skip the + // correct number of elements + if (cMediaTypes == 0) { + return S_OK; + } + + /* Check we are still in sync with the pin */ + if (AreWeOutOfSync() == TRUE) { + return VFW_E_ENUM_OUT_OF_SYNC; + } + + m_Position += cMediaTypes; + + /* See if we're over the end */ + CMediaType cmt; + return S_OK == m_pPin->GetMediaType(m_Position - 1, &cmt) ? S_OK : S_FALSE; +} + + +/* Set the current position back to the start */ +/* Reset has 3 simple steps: + * + * set position to head of list + * sync enumerator with object being enumerated + * return S_OK + */ + +STDMETHODIMP +CEnumMediaTypes::Reset() + +{ + m_Position = 0; + + // Bring the enumerator back into step with the current state. This + // may be a noop but ensures that the enumerator will be valid on the + // next call. + m_Version = m_pPin->GetMediaTypeVersion(); + return NOERROR; +} + + +//===================================================================== +//===================================================================== +// Implements CBasePin +//===================================================================== +//===================================================================== + + +/* NOTE The implementation of this class calls the CUnknown constructor with + a NULL outer unknown pointer. This has the effect of making us a self + contained class, ie any QueryInterface, AddRef or Release calls will be + routed to the class's NonDelegatingUnknown methods. You will typically + find that the classes that do this then override one or more of these + virtual functions to provide more specialised behaviour. A good example + of this is where a class wants to keep the QueryInterface internal but + still wants its lifetime controlled by the external object */ + +/* Constructor */ + +CBasePin::CBasePin(__in_opt LPCTSTR pObjectName, + __in CBaseFilter *pFilter, + __in CCritSec *pLock, + __inout HRESULT *phr, + __in_opt LPCWSTR pName, + PIN_DIRECTION dir) : + CUnknown( pObjectName, NULL ), + m_pFilter(pFilter), + m_pLock(pLock), + m_pName(NULL), + m_Connected(NULL), + m_dir(dir), + m_bRunTimeError(FALSE), + m_pQSink(NULL), + m_TypeVersion(1), + m_tStart(), + m_tStop(MAX_TIME), + m_bCanReconnectWhenActive(false), + m_bTryMyTypesFirst(false), + m_dRate(1.0) +{ + /* WARNING - pFilter is often not a properly constituted object at + this state (in particular QueryInterface may not work) - this + is because its owner is often its containing object and we + have been called from the containing object's constructor so + the filter's owner has not yet had its CUnknown constructor + called + */ +#ifdef DXMPERF + PERFLOG_CTOR( pName ? pName : L"CBasePin", (IPin *) this ); +#endif // DXMPERF + + ASSERT(pFilter != NULL); + ASSERT(pLock != NULL); + + if (pName) { + size_t cchName; + HRESULT hr = StringCchLengthW(pName, STRSAFE_MAX_CCH, &cchName); + if (SUCCEEDED(hr)) { + m_pName = new WCHAR[cchName + 1]; + if (m_pName) { + (void)StringCchCopyW(m_pName, cchName + 1, pName); + } + } + } + +#ifdef DEBUG + m_cRef = 0; +#endif +} + +#ifdef UNICODE +CBasePin::CBasePin(__in_opt LPCSTR pObjectName, + __in CBaseFilter *pFilter, + __in CCritSec *pLock, + __inout HRESULT *phr, + __in_opt LPCWSTR pName, + PIN_DIRECTION dir) : + CUnknown( pObjectName, NULL ), + m_pFilter(pFilter), + m_pLock(pLock), + m_pName(NULL), + m_Connected(NULL), + m_dir(dir), + m_bRunTimeError(FALSE), + m_pQSink(NULL), + m_TypeVersion(1), + m_tStart(), + m_tStop(MAX_TIME), + m_bCanReconnectWhenActive(false), + m_bTryMyTypesFirst(false), + m_dRate(1.0) +{ + /* WARNING - pFilter is often not a properly constituted object at + this state (in particular QueryInterface may not work) - this + is because its owner is often its containing object and we + have been called from the containing object's constructor so + the filter's owner has not yet had its CUnknown constructor + called + */ +#ifdef DXMPERF + PERFLOG_CTOR( pName ? pName : L"CBasePin", (IPin *) this ); +#endif // DXMPERF + + ASSERT(pFilter != NULL); + ASSERT(pLock != NULL); + + if (pName) { + size_t cchName; + HRESULT hr = StringCchLengthW(pName, STRSAFE_MAX_CCH, &cchName); + if (SUCCEEDED(hr)) { + m_pName = new WCHAR[cchName + 1]; + if (m_pName) { + (void)StringCchCopyW(m_pName, cchName + 1, pName); + } + } + } + + +#ifdef DEBUG + m_cRef = 0; +#endif +} +#endif + +/* Destructor since a connected pin holds a reference count on us there is + no way that we can be deleted unless we are not currently connected */ + +CBasePin::~CBasePin() +{ +#ifdef DXMPERF + PERFLOG_DTOR( m_pName ? m_pName : L"CBasePin", (IPin *) this ); +#endif // DXMPERF + + // We don't call disconnect because if the filter is going away + // all the pins must have a reference count of zero so they must + // have been disconnected anyway - (but check the assumption) + ASSERT(m_Connected == FALSE); + + delete[] m_pName; + + // check the internal reference count is consistent + ASSERT(m_cRef == 0); +} + + +/* Override this to say what interfaces we support and where */ + +STDMETHODIMP +CBasePin::NonDelegatingQueryInterface(REFIID riid, __deref_out void ** ppv) +{ + /* Do we have this interface */ + + if (riid == IID_IPin) { + return GetInterface((IPin *) this, ppv); + } else if (riid == IID_IQualityControl) { + return GetInterface((IQualityControl *) this, ppv); + } else { + return CUnknown::NonDelegatingQueryInterface(riid, ppv); + } +} + + +/* Override to increment the owning filter's reference count */ + +STDMETHODIMP_(ULONG) +CBasePin::NonDelegatingAddRef() +{ + ASSERT(InterlockedIncrement(&m_cRef) > 0); + return m_pFilter->AddRef(); +} + + +/* Override to decrement the owning filter's reference count */ + +STDMETHODIMP_(ULONG) +CBasePin::NonDelegatingRelease() +{ + ASSERT(InterlockedDecrement(&m_cRef) >= 0); + return m_pFilter->Release(); +} + + +/* Displays pin connection information */ + +#ifdef DEBUG +void +CBasePin::DisplayPinInfo(IPin *pReceivePin) +{ + + if (DbgCheckModuleLevel(LOG_TRACE, CONNECT_TRACE_LEVEL)) { + PIN_INFO ConnectPinInfo; + PIN_INFO ReceivePinInfo; + + if (FAILED(QueryPinInfo(&ConnectPinInfo))) { + StringCchCopyW(ConnectPinInfo.achName, sizeof(ConnectPinInfo.achName)/sizeof(WCHAR), L"Bad Pin"); + } else { + QueryPinInfoReleaseFilter(ConnectPinInfo); + } + + if (FAILED(pReceivePin->QueryPinInfo(&ReceivePinInfo))) { + StringCchCopyW(ReceivePinInfo.achName, sizeof(ReceivePinInfo.achName)/sizeof(WCHAR), L"Bad Pin"); + } else { + QueryPinInfoReleaseFilter(ReceivePinInfo); + } + + DbgLog((LOG_TRACE, CONNECT_TRACE_LEVEL, TEXT("Trying to connect Pins :"))); + DbgLog((LOG_TRACE, CONNECT_TRACE_LEVEL, TEXT(" <%ls>"), ConnectPinInfo.achName)); + DbgLog((LOG_TRACE, CONNECT_TRACE_LEVEL, TEXT(" <%ls>"), ReceivePinInfo.achName)); + } +} +#endif + + +/* Displays general information on the pin media type */ + +#ifdef DEBUG +void CBasePin::DisplayTypeInfo(IPin *pPin, const CMediaType *pmt) +{ + UNREFERENCED_PARAMETER(pPin); + if (DbgCheckModuleLevel(LOG_TRACE, CONNECT_TRACE_LEVEL)) { + DbgLog((LOG_TRACE, CONNECT_TRACE_LEVEL, TEXT("Trying media type:"))); + DbgLog((LOG_TRACE, CONNECT_TRACE_LEVEL, TEXT(" major type: %hs"), + GuidNames[*pmt->Type()])); + DbgLog((LOG_TRACE, CONNECT_TRACE_LEVEL, TEXT(" sub type : %hs"), + GuidNames[*pmt->Subtype()])); + } +} +#endif + +/* Asked to connect to a pin. A pin is always attached to an owning filter + object so we always delegate our locking to that object. We first of all + retrieve a media type enumerator for the input pin and see if we accept + any of the formats that it would ideally like, failing that we retrieve + our enumerator and see if it will accept any of our preferred types */ + +STDMETHODIMP +CBasePin::Connect( + IPin * pReceivePin, + __in_opt const AM_MEDIA_TYPE *pmt // optional media type +) +{ + CheckPointer(pReceivePin,E_POINTER); + ValidateReadPtr(pReceivePin,sizeof(IPin)); + CAutoLock cObjectLock(m_pLock); + DisplayPinInfo(pReceivePin); + + /* See if we are already connected */ + + if (m_Connected) { + DbgLog((LOG_TRACE, CONNECT_TRACE_LEVEL, TEXT("Already connected"))); + return VFW_E_ALREADY_CONNECTED; + } + + /* See if the filter is active */ + if (!IsStopped() && !m_bCanReconnectWhenActive) { + return VFW_E_NOT_STOPPED; + } + + + // Find a mutually agreeable media type - + // Pass in the template media type. If this is partially specified, + // each of the enumerated media types will need to be checked against + // it. If it is non-null and fully specified, we will just try to connect + // with this. + + const CMediaType * ptype = (CMediaType*)pmt; + HRESULT hr = AgreeMediaType(pReceivePin, ptype); + if (FAILED(hr)) { + DbgLog((LOG_TRACE, CONNECT_TRACE_LEVEL, TEXT("Failed to agree type"))); + + // Since the procedure is already returning an error code, there + // is nothing else this function can do to report the error. + EXECUTE_ASSERT( SUCCEEDED( BreakConnect() ) ); + +#ifdef DXMPERF + PERFLOG_CONNECT( (IPin *) this, pReceivePin, hr, pmt ); +#endif // DXMPERF + + return hr; + } + + DbgLog((LOG_TRACE, CONNECT_TRACE_LEVEL, TEXT("Connection succeeded"))); + +#ifdef DXMPERF + PERFLOG_CONNECT( (IPin *) this, pReceivePin, NOERROR, pmt ); +#endif // DXMPERF + + return NOERROR; +} + +// given a specific media type, attempt a connection (includes +// checking that the type is acceptable to this pin) +HRESULT +CBasePin::AttemptConnection( + IPin* pReceivePin, // connect to this pin + const CMediaType* pmt // using this type +) +{ + // The caller should hold the filter lock becasue this function + // uses m_Connected. The caller should also hold the filter lock + // because this function calls SetMediaType(), IsStopped() and + // CompleteConnect(). + ASSERT(CritCheckIn(m_pLock)); + + // Check that the connection is valid -- need to do this for every + // connect attempt since BreakConnect will undo it. + HRESULT hr = CheckConnect(pReceivePin); + if (FAILED(hr)) { + DbgLog((LOG_TRACE, CONNECT_TRACE_LEVEL, TEXT("CheckConnect failed"))); + + // Since the procedure is already returning an error code, there + // is nothing else this function can do to report the error. + EXECUTE_ASSERT( SUCCEEDED( BreakConnect() ) ); + + return hr; + } + + DisplayTypeInfo(pReceivePin, pmt); + + /* Check we will accept this media type */ + + hr = CheckMediaType(pmt); + if (hr == NOERROR) { + + /* Make ourselves look connected otherwise ReceiveConnection + may not be able to complete the connection + */ + m_Connected = pReceivePin; + m_Connected->AddRef(); + hr = SetMediaType(pmt); + if (SUCCEEDED(hr)) { + /* See if the other pin will accept this type */ + + hr = pReceivePin->ReceiveConnection((IPin *)this, pmt); + if (SUCCEEDED(hr)) { + /* Complete the connection */ + + hr = CompleteConnect(pReceivePin); + if (SUCCEEDED(hr)) { + return hr; + } else { + DbgLog((LOG_TRACE, + CONNECT_TRACE_LEVEL, + TEXT("Failed to complete connection"))); + pReceivePin->Disconnect(); + } + } + } + } else { + // we cannot use this media type + + // return a specific media type error if there is one + // or map a general failure code to something more helpful + // (in particular S_FALSE gets changed to an error code) + if (SUCCEEDED(hr) || + (hr == E_FAIL) || + (hr == E_INVALIDARG)) { + hr = VFW_E_TYPE_NOT_ACCEPTED; + } + } + + // BreakConnect and release any connection here in case CheckMediaType + // failed, or if we set anything up during a call back during + // ReceiveConnection. + + // Since the procedure is already returning an error code, there + // is nothing else this function can do to report the error. + EXECUTE_ASSERT( SUCCEEDED( BreakConnect() ) ); + + /* If failed then undo our state */ + if (m_Connected) { + m_Connected->Release(); + m_Connected = NULL; + } + + return hr; +} + +/* Given an enumerator we cycle through all the media types it proposes and + firstly suggest them to our derived pin class and if that succeeds try + them with the pin in a ReceiveConnection call. This means that if our pin + proposes a media type we still check in here that we can support it. This + is deliberate so that in simple cases the enumerator can hold all of the + media types even if some of them are not really currently available */ + +HRESULT CBasePin::TryMediaTypes( + IPin *pReceivePin, + __in_opt const CMediaType *pmt, + IEnumMediaTypes *pEnum) +{ + /* Reset the current enumerator position */ + + HRESULT hr = pEnum->Reset(); + if (FAILED(hr)) { + return hr; + } + + CMediaType *pMediaType = NULL; + ULONG ulMediaCount = 0; + + // attempt to remember a specific error code if there is one + HRESULT hrFailure = S_OK; + + for (;;) { + + /* Retrieve the next media type NOTE each time round the loop the + enumerator interface will allocate another AM_MEDIA_TYPE structure + If we are successful then we copy it into our output object, if + not then we must delete the memory allocated before returning */ + + hr = pEnum->Next(1, (AM_MEDIA_TYPE**)&pMediaType,&ulMediaCount); + if (hr != S_OK) { + if (S_OK == hrFailure) { + hrFailure = VFW_E_NO_ACCEPTABLE_TYPES; + } + return hrFailure; + } + + + ASSERT(ulMediaCount == 1); + ASSERT(pMediaType); + + // check that this matches the partial type (if any) + + if (pMediaType && + ((pmt == NULL) || + pMediaType->MatchesPartial(pmt))) { + + hr = AttemptConnection(pReceivePin, pMediaType); + + // attempt to remember a specific error code + if (FAILED(hr) && + SUCCEEDED(hrFailure) && + (hr != E_FAIL) && + (hr != E_INVALIDARG) && + (hr != VFW_E_TYPE_NOT_ACCEPTED)) { + hrFailure = hr; + } + } else { + hr = VFW_E_NO_ACCEPTABLE_TYPES; + } + + if(pMediaType) { + DeleteMediaType(pMediaType); + pMediaType = NULL; + } + + if (S_OK == hr) { + return hr; + } + } +} + + +/* This is called to make the connection, including the taask of finding + a media type for the pin connection. pmt is the proposed media type + from the Connect call: if this is fully specified, we will try that. + Otherwise we enumerate and try all the input pin's types first and + if that fails we then enumerate and try all our preferred media types. + For each media type we check it against pmt (if non-null and partially + specified) as well as checking that both pins will accept it. + */ + +HRESULT CBasePin::AgreeMediaType( + IPin *pReceivePin, + const CMediaType *pmt) +{ + ASSERT(pReceivePin); + IEnumMediaTypes *pEnumMediaTypes = NULL; + + // if the media type is fully specified then use that + if ( (pmt != NULL) && (!pmt->IsPartiallySpecified())) { + + // if this media type fails, then we must fail the connection + // since if pmt is nonnull we are only allowed to connect + // using a type that matches it. + + return AttemptConnection(pReceivePin, pmt); + } + + + /* Try the other pin's enumerator */ + + HRESULT hrFailure = VFW_E_NO_ACCEPTABLE_TYPES; + + for (int i = 0; i < 2; i++) { + HRESULT hr; + if (i == (int)m_bTryMyTypesFirst) { + hr = pReceivePin->EnumMediaTypes(&pEnumMediaTypes); + } else { + hr = EnumMediaTypes(&pEnumMediaTypes); + } + if (SUCCEEDED(hr)) { + ASSERT(pEnumMediaTypes); + hr = TryMediaTypes(pReceivePin,pmt,pEnumMediaTypes); + pEnumMediaTypes->Release(); + if (SUCCEEDED(hr)) { + return NOERROR; + } else { + // try to remember specific error codes if there are any + if ((hr != E_FAIL) && + (hr != E_INVALIDARG) && + (hr != VFW_E_TYPE_NOT_ACCEPTED)) { + hrFailure = hr; + } + } + } + } + + return hrFailure; +} + + +/* Called when we want to complete a connection to another filter. Failing + this will also fail the connection and disconnect the other pin as well */ + +HRESULT +CBasePin::CompleteConnect(IPin *pReceivePin) +{ + UNREFERENCED_PARAMETER(pReceivePin); + return NOERROR; +} + + +/* This is called to set the format for a pin connection - CheckMediaType + will have been called to check the connection format and if it didn't + return an error code then this (virtual) function will be invoked */ + +HRESULT +CBasePin::SetMediaType(const CMediaType *pmt) +{ + HRESULT hr = m_mt.Set(*pmt); + if (FAILED(hr)) { + return hr; + } + + return NOERROR; +} + + +/* This is called during Connect() to provide a virtual method that can do + any specific check needed for connection such as QueryInterface. This + base class method just checks that the pin directions don't match */ + +HRESULT +CBasePin::CheckConnect(IPin * pPin) +{ + /* Check that pin directions DONT match */ + + PIN_DIRECTION pd; + pPin->QueryDirection(&pd); + + ASSERT((pd == PINDIR_OUTPUT) || (pd == PINDIR_INPUT)); + ASSERT((m_dir == PINDIR_OUTPUT) || (m_dir == PINDIR_INPUT)); + + // we should allow for non-input and non-output connections? + if (pd == m_dir) { + return VFW_E_INVALID_DIRECTION; + } + return NOERROR; +} + + +/* This is called when we realise we can't make a connection to the pin and + must undo anything we did in CheckConnect - override to release QIs done */ + +HRESULT +CBasePin::BreakConnect() +{ + return NOERROR; +} + + +/* Called normally by an output pin on an input pin to try and establish a + connection. +*/ + +STDMETHODIMP +CBasePin::ReceiveConnection( + IPin * pConnector, // this is the pin who we will connect to + const AM_MEDIA_TYPE *pmt // this is the media type we will exchange +) +{ + CheckPointer(pConnector,E_POINTER); + CheckPointer(pmt,E_POINTER); + ValidateReadPtr(pConnector,sizeof(IPin)); + ValidateReadPtr(pmt,sizeof(AM_MEDIA_TYPE)); + CAutoLock cObjectLock(m_pLock); + + /* Are we already connected */ + if (m_Connected) { + return VFW_E_ALREADY_CONNECTED; + } + + /* See if the filter is active */ + if (!IsStopped() && !m_bCanReconnectWhenActive) { + return VFW_E_NOT_STOPPED; + } + + HRESULT hr = CheckConnect(pConnector); + if (FAILED(hr)) { + // Since the procedure is already returning an error code, there + // is nothing else this function can do to report the error. + EXECUTE_ASSERT( SUCCEEDED( BreakConnect() ) ); + +#ifdef DXMPERF + PERFLOG_RXCONNECT( pConnector, (IPin *) this, hr, pmt ); +#endif // DXMPERF + + return hr; + } + + /* Ask derived class if this media type is ok */ + + CMediaType * pcmt = (CMediaType*) pmt; + hr = CheckMediaType(pcmt); + if (hr != NOERROR) { + // no -we don't support this media type + + // Since the procedure is already returning an error code, there + // is nothing else this function can do to report the error. + EXECUTE_ASSERT( SUCCEEDED( BreakConnect() ) ); + + // return a specific media type error if there is one + // or map a general failure code to something more helpful + // (in particular S_FALSE gets changed to an error code) + if (SUCCEEDED(hr) || + (hr == E_FAIL) || + (hr == E_INVALIDARG)) { + hr = VFW_E_TYPE_NOT_ACCEPTED; + } + +#ifdef DXMPERF + PERFLOG_RXCONNECT( pConnector, (IPin *) this, hr, pmt ); +#endif // DXMPERF + + return hr; + } + + /* Complete the connection */ + + m_Connected = pConnector; + m_Connected->AddRef(); + hr = SetMediaType(pcmt); + if (SUCCEEDED(hr)) { + hr = CompleteConnect(pConnector); + if (SUCCEEDED(hr)) { + +#ifdef DXMPERF + PERFLOG_RXCONNECT( pConnector, (IPin *) this, NOERROR, pmt ); +#endif // DXMPERF + + return NOERROR; + } + } + + DbgLog((LOG_TRACE, CONNECT_TRACE_LEVEL, TEXT("Failed to set the media type or failed to complete the connection."))); + m_Connected->Release(); + m_Connected = NULL; + + // Since the procedure is already returning an error code, there + // is nothing else this function can do to report the error. + EXECUTE_ASSERT( SUCCEEDED( BreakConnect() ) ); + +#ifdef DXMPERF + PERFLOG_RXCONNECT( pConnector, (IPin *) this, hr, pmt ); +#endif // DXMPERF + + return hr; +} + + +/* Called when we want to terminate a pin connection */ + +STDMETHODIMP +CBasePin::Disconnect() +{ + CAutoLock cObjectLock(m_pLock); + + /* See if the filter is active */ + if (!IsStopped()) { + return VFW_E_NOT_STOPPED; + } + + return DisconnectInternal(); +} + +STDMETHODIMP +CBasePin::DisconnectInternal() +{ + ASSERT(CritCheckIn(m_pLock)); + + if (m_Connected) { + HRESULT hr = BreakConnect(); + if( FAILED( hr ) ) { + +#ifdef DXMPERF + PERFLOG_DISCONNECT( (IPin *) this, m_Connected, hr ); +#endif // DXMPERF + + // There is usually a bug in the program if BreakConnect() fails. + DbgBreak( "WARNING: BreakConnect() failed in CBasePin::Disconnect()." ); + return hr; + } + + m_Connected->Release(); + m_Connected = NULL; + +#ifdef DXMPERF + PERFLOG_DISCONNECT( (IPin *) this, m_Connected, S_OK ); +#endif // DXMPERF + + return S_OK; + } else { + // no connection - not an error + +#ifdef DXMPERF + PERFLOG_DISCONNECT( (IPin *) this, m_Connected, S_FALSE ); +#endif // DXMPERF + + return S_FALSE; + } +} + + +/* Return an AddRef()'d pointer to the connected pin if there is one */ +STDMETHODIMP +CBasePin::ConnectedTo( + __deref_out IPin **ppPin +) +{ + CheckPointer(ppPin,E_POINTER); + ValidateReadWritePtr(ppPin,sizeof(IPin *)); + // + // It's pointless to lock here. + // The caller should ensure integrity. + // + + IPin *pPin = m_Connected; + *ppPin = pPin; + if (pPin != NULL) { + pPin->AddRef(); + return S_OK; + } else { + ASSERT(*ppPin == NULL); + return VFW_E_NOT_CONNECTED; + } +} + +/* Return the media type of the connection */ +STDMETHODIMP +CBasePin::ConnectionMediaType( + __out AM_MEDIA_TYPE *pmt +) +{ + CheckPointer(pmt,E_POINTER); + ValidateReadWritePtr(pmt,sizeof(AM_MEDIA_TYPE)); + CAutoLock cObjectLock(m_pLock); + + /* Copy constructor of m_mt allocates the memory */ + if (IsConnected()) { + CopyMediaType( pmt, &m_mt ); + return S_OK; + } else { + ((CMediaType *)pmt)->InitMediaType(); + return VFW_E_NOT_CONNECTED; + } +} + +/* Return information about the filter we are connect to */ + +STDMETHODIMP +CBasePin::QueryPinInfo( + __out PIN_INFO * pInfo +) +{ + CheckPointer(pInfo,E_POINTER); + ValidateReadWritePtr(pInfo,sizeof(PIN_INFO)); + + pInfo->pFilter = m_pFilter; + if (m_pFilter) { + m_pFilter->AddRef(); + } + + if (m_pName) { + (void)StringCchCopyW(pInfo->achName, NUMELMS(pInfo->achName), m_pName); + } else { + pInfo->achName[0] = L'\0'; + } + + pInfo->dir = m_dir; + + return NOERROR; +} + +STDMETHODIMP +CBasePin::QueryDirection( + __out PIN_DIRECTION * pPinDir +) +{ + CheckPointer(pPinDir,E_POINTER); + ValidateReadWritePtr(pPinDir,sizeof(PIN_DIRECTION)); + + *pPinDir = m_dir; + return NOERROR; +} + +// Default QueryId to return the pin's name +STDMETHODIMP +CBasePin::QueryId( + __deref_out LPWSTR * Id +) +{ + // We're not going away because someone's got a pointer to us + // so there's no need to lock + + return AMGetWideString(Name(), Id); +} + +/* Does this pin support this media type WARNING this interface function does + not lock the main object as it is meant to be asynchronous by nature - if + the media types you support depend on some internal state that is updated + dynamically then you will need to implement locking in a derived class */ + +STDMETHODIMP +CBasePin::QueryAccept( + const AM_MEDIA_TYPE *pmt +) +{ + CheckPointer(pmt,E_POINTER); + ValidateReadPtr(pmt,sizeof(AM_MEDIA_TYPE)); + + /* The CheckMediaType method is valid to return error codes if the media + type is horrible, an example might be E_INVALIDARG. What we do here + is map all the error codes into either S_OK or S_FALSE regardless */ + + HRESULT hr = CheckMediaType((CMediaType*)pmt); + if (FAILED(hr)) { + return S_FALSE; + } + // note that the only defined success codes should be S_OK and S_FALSE... + return hr; +} + + +/* This can be called to return an enumerator for the pin's list of preferred + media types. An input pin is not obliged to have any preferred formats + although it can do. For example, the window renderer has a preferred type + which describes a video image that matches the current window size. All + output pins should expose at least one preferred format otherwise it is + possible that neither pin has any types and so no connection is possible */ + +STDMETHODIMP +CBasePin::EnumMediaTypes( + __deref_out IEnumMediaTypes **ppEnum +) +{ + CheckPointer(ppEnum,E_POINTER); + ValidateReadWritePtr(ppEnum,sizeof(IEnumMediaTypes *)); + + /* Create a new ref counted enumerator */ + + *ppEnum = new CEnumMediaTypes(this, + NULL); + + if (*ppEnum == NULL) { + return E_OUTOFMEMORY; + } + + return NOERROR; +} + + + +/* This is a virtual function that returns a media type corresponding with + place iPosition in the list. This base class simply returns an error as + we support no media types by default but derived classes should override */ + +HRESULT CBasePin::GetMediaType(int iPosition, __inout CMediaType *pMediaType) +{ + UNREFERENCED_PARAMETER(iPosition); + UNREFERENCED_PARAMETER(pMediaType); + return E_UNEXPECTED; +} + + +/* This is a virtual function that returns the current media type version. + The base class initialises the media type enumerators with the value 1 + By default we always returns that same value. A Derived class may change + the list of media types available and after doing so it should increment + the version either in a method derived from this, or more simply by just + incrementing the m_TypeVersion base pin variable. The type enumerators + call this when they want to see if their enumerations are out of date */ + +LONG CBasePin::GetMediaTypeVersion() +{ + return m_TypeVersion; +} + + +/* Increment the cookie representing the current media type version */ + +void CBasePin::IncrementTypeVersion() +{ + InterlockedIncrement(&m_TypeVersion); +} + + +/* Called by IMediaFilter implementation when the state changes from Stopped + to either paused or running and in derived classes could do things like + commit memory and grab hardware resource (the default is to do nothing) */ + +HRESULT +CBasePin::Active(void) +{ + return NOERROR; +} + +/* Called by IMediaFilter implementation when the state changes from + to either paused to running and in derived classes could do things like + commit memory and grab hardware resource (the default is to do nothing) */ + +HRESULT +CBasePin::Run(REFERENCE_TIME tStart) +{ + UNREFERENCED_PARAMETER(tStart); + return NOERROR; +} + + +/* Also called by the IMediaFilter implementation when the state changes to + Stopped at which point you should decommit allocators and free hardware + resources you grabbed in the Active call (default is also to do nothing) */ + +HRESULT +CBasePin::Inactive(void) +{ + m_bRunTimeError = FALSE; + return NOERROR; +} + + +// Called when no more data will arrive +STDMETHODIMP +CBasePin::EndOfStream(void) +{ + return S_OK; +} + + +STDMETHODIMP +CBasePin::SetSink(IQualityControl * piqc) +{ + CAutoLock cObjectLock(m_pLock); + if (piqc) ValidateReadPtr(piqc,sizeof(IQualityControl)); + m_pQSink = piqc; + return NOERROR; +} // SetSink + + +STDMETHODIMP +CBasePin::Notify(IBaseFilter * pSender, Quality q) +{ + UNREFERENCED_PARAMETER(q); + UNREFERENCED_PARAMETER(pSender); + DbgBreak("IQualityControl::Notify not over-ridden from CBasePin. (IGNORE is OK)"); + return E_NOTIMPL; +} //Notify + + +// NewSegment notifies of the start/stop/rate applying to the data +// about to be received. Default implementation records data and +// returns S_OK. +// Override this to pass downstream. +STDMETHODIMP +CBasePin::NewSegment( + REFERENCE_TIME tStart, + REFERENCE_TIME tStop, + double dRate) +{ + m_tStart = tStart; + m_tStop = tStop; + m_dRate = dRate; + + return S_OK; +} + + +//===================================================================== +//===================================================================== +// Implements CBaseOutputPin +//===================================================================== +//===================================================================== + + +CBaseOutputPin::CBaseOutputPin(__in_opt LPCTSTR pObjectName, + __in CBaseFilter *pFilter, + __in CCritSec *pLock, + __inout HRESULT *phr, + __in_opt LPCWSTR pName) : + CBasePin(pObjectName, pFilter, pLock, phr, pName, PINDIR_OUTPUT), + m_pAllocator(NULL), + m_pInputPin(NULL) +{ + ASSERT(pFilter); +} + +#ifdef UNICODE +CBaseOutputPin::CBaseOutputPin(__in_opt LPCSTR pObjectName, + __in CBaseFilter *pFilter, + __in CCritSec *pLock, + __inout HRESULT *phr, + __in_opt LPCWSTR pName) : + CBasePin(pObjectName, pFilter, pLock, phr, pName, PINDIR_OUTPUT), + m_pAllocator(NULL), + m_pInputPin(NULL) +{ + ASSERT(pFilter); +} +#endif + +/* This is called after a media type has been proposed + + Try to complete the connection by agreeing the allocator +*/ +HRESULT +CBaseOutputPin::CompleteConnect(IPin *pReceivePin) +{ + UNREFERENCED_PARAMETER(pReceivePin); + return DecideAllocator(m_pInputPin, &m_pAllocator); +} + + +/* This method is called when the output pin is about to try and connect to + an input pin. It is at this point that you should try and grab any extra + interfaces that you need, in this case IMemInputPin. Because this is + only called if we are not currently connected we do NOT need to call + BreakConnect. This also makes it easier to derive classes from us as + BreakConnect is only called when we actually have to break a connection + (or a partly made connection) and not when we are checking a connection */ + +/* Overriden from CBasePin */ + +HRESULT +CBaseOutputPin::CheckConnect(IPin * pPin) +{ + HRESULT hr = CBasePin::CheckConnect(pPin); + if (FAILED(hr)) { + return hr; + } + + // get an input pin and an allocator interface + hr = pPin->QueryInterface(IID_IMemInputPin, (void **) &m_pInputPin); + if (FAILED(hr)) { + return hr; + } + return NOERROR; +} + + +/* Overriden from CBasePin */ + +HRESULT +CBaseOutputPin::BreakConnect() +{ + /* Release any allocator we hold */ + + if (m_pAllocator) { + // Always decommit the allocator because a downstream filter may or + // may not decommit the connection's allocator. A memory leak could + // occur if the allocator is not decommited when a connection is broken. + HRESULT hr = m_pAllocator->Decommit(); + if( FAILED( hr ) ) { + return hr; + } + + m_pAllocator->Release(); + m_pAllocator = NULL; + } + + /* Release any input pin interface we hold */ + + if (m_pInputPin) { + m_pInputPin->Release(); + m_pInputPin = NULL; + } + return NOERROR; +} + + +/* This is called when the input pin didn't give us a valid allocator */ + +HRESULT +CBaseOutputPin::InitAllocator(__deref_out IMemAllocator **ppAlloc) +{ + return CreateMemoryAllocator(ppAlloc); +} + + +/* Decide on an allocator, override this if you want to use your own allocator + Override DecideBufferSize to call SetProperties. If the input pin fails + the GetAllocator call then this will construct a CMemAllocator and call + DecideBufferSize on that, and if that fails then we are completely hosed. + If the you succeed the DecideBufferSize call, we will notify the input + pin of the selected allocator. NOTE this is called during Connect() which + therefore looks after grabbing and locking the object's critical section */ + +// We query the input pin for its requested properties and pass this to +// DecideBufferSize to allow it to fulfill requests that it is happy +// with (eg most people don't care about alignment and are thus happy to +// use the downstream pin's alignment request). + +HRESULT +CBaseOutputPin::DecideAllocator(IMemInputPin *pPin, __deref_out IMemAllocator **ppAlloc) +{ + HRESULT hr = NOERROR; + *ppAlloc = NULL; + + // get downstream prop request + // the derived class may modify this in DecideBufferSize, but + // we assume that he will consistently modify it the same way, + // so we only get it once + ALLOCATOR_PROPERTIES prop; + ZeroMemory(&prop, sizeof(prop)); + + // whatever he returns, we assume prop is either all zeros + // or he has filled it out. + pPin->GetAllocatorRequirements(&prop); + + // if he doesn't care about alignment, then set it to 1 + if (prop.cbAlign == 0) { + prop.cbAlign = 1; + } + + /* Try the allocator provided by the input pin */ + + hr = pPin->GetAllocator(ppAlloc); + if (SUCCEEDED(hr)) { + + hr = DecideBufferSize(*ppAlloc, &prop); + if (SUCCEEDED(hr)) { + hr = pPin->NotifyAllocator(*ppAlloc, FALSE); + if (SUCCEEDED(hr)) { + return NOERROR; + } + } + } + + /* If the GetAllocator failed we may not have an interface */ + + if (*ppAlloc) { + (*ppAlloc)->Release(); + *ppAlloc = NULL; + } + + /* Try the output pin's allocator by the same method */ + + hr = InitAllocator(ppAlloc); + if (SUCCEEDED(hr)) { + + // note - the properties passed here are in the same + // structure as above and may have been modified by + // the previous call to DecideBufferSize + hr = DecideBufferSize(*ppAlloc, &prop); + if (SUCCEEDED(hr)) { + hr = pPin->NotifyAllocator(*ppAlloc, FALSE); + if (SUCCEEDED(hr)) { + return NOERROR; + } + } + } + + /* Likewise we may not have an interface to release */ + + if (*ppAlloc) { + (*ppAlloc)->Release(); + *ppAlloc = NULL; + } + return hr; +} + + +/* This returns an empty sample buffer from the allocator WARNING the same + dangers and restrictions apply here as described below for Deliver() */ + +HRESULT +CBaseOutputPin::GetDeliveryBuffer(__deref_out IMediaSample ** ppSample, + __in_opt REFERENCE_TIME * pStartTime, + __in_opt REFERENCE_TIME * pEndTime, + DWORD dwFlags) +{ + if (m_pAllocator != NULL) { + return m_pAllocator->GetBuffer(ppSample,pStartTime,pEndTime,dwFlags); + } else { + return E_NOINTERFACE; + } +} + + +/* Deliver a filled-in sample to the connected input pin. NOTE the object must + have locked itself before calling us otherwise we may get halfway through + executing this method only to find the filter graph has got in and + disconnected us from the input pin. If the filter has no worker threads + then the lock is best applied on Receive(), otherwise it should be done + when the worker thread is ready to deliver. There is a wee snag to worker + threads that this shows up. The worker thread must lock the object when + it is ready to deliver a sample, but it may have to wait until a state + change has completed, but that may never complete because the state change + is waiting for the worker thread to complete. The way to handle this is for + the state change code to grab the critical section, then set an abort event + for the worker thread, then release the critical section and wait for the + worker thread to see the event we set and then signal that it has finished + (with another event). At which point the state change code can complete */ + +// note (if you've still got any breath left after reading that) that you +// need to release the sample yourself after this call. if the connected +// input pin needs to hold onto the sample beyond the call, it will addref +// the sample itself. + +// of course you must release this one and call GetDeliveryBuffer for the +// next. You cannot reuse it directly. + +HRESULT +CBaseOutputPin::Deliver(IMediaSample * pSample) +{ + if (m_pInputPin == NULL) { + return VFW_E_NOT_CONNECTED; + } + +#ifdef DXMPERF + PERFLOG_DELIVER( m_pName ? m_pName : L"CBaseOutputPin", (IPin *) this, (IPin *) m_pInputPin, pSample, &m_mt ); +#endif // DXMPERF + + return m_pInputPin->Receive(pSample); +} + + +// called from elsewhere in our filter to pass EOS downstream to +// our connected input pin +HRESULT +CBaseOutputPin::DeliverEndOfStream(void) +{ + // remember this is on IPin not IMemInputPin + if (m_Connected == NULL) { + return VFW_E_NOT_CONNECTED; + } + return m_Connected->EndOfStream(); +} + + +/* Commit the allocator's memory, this is called through IMediaFilter + which is responsible for locking the object before calling us */ + +HRESULT +CBaseOutputPin::Active(void) +{ + if (m_pAllocator == NULL) { + return VFW_E_NO_ALLOCATOR; + } + return m_pAllocator->Commit(); +} + + +/* Free up or unprepare allocator's memory, this is called through + IMediaFilter which is responsible for locking the object first */ + +HRESULT +CBaseOutputPin::Inactive(void) +{ + m_bRunTimeError = FALSE; + if (m_pAllocator == NULL) { + return VFW_E_NO_ALLOCATOR; + } + return m_pAllocator->Decommit(); +} + +// we have a default handling of EndOfStream which is to return +// an error, since this should be called on input pins only +STDMETHODIMP +CBaseOutputPin::EndOfStream(void) +{ + return E_UNEXPECTED; +} + + +// BeginFlush should be called on input pins only +STDMETHODIMP +CBaseOutputPin::BeginFlush(void) +{ + return E_UNEXPECTED; +} + +// EndFlush should be called on input pins only +STDMETHODIMP +CBaseOutputPin::EndFlush(void) +{ + return E_UNEXPECTED; +} + +// call BeginFlush on the connected input pin +HRESULT +CBaseOutputPin::DeliverBeginFlush(void) +{ + // remember this is on IPin not IMemInputPin + if (m_Connected == NULL) { + return VFW_E_NOT_CONNECTED; + } + return m_Connected->BeginFlush(); +} + +// call EndFlush on the connected input pin +HRESULT +CBaseOutputPin::DeliverEndFlush(void) +{ + // remember this is on IPin not IMemInputPin + if (m_Connected == NULL) { + return VFW_E_NOT_CONNECTED; + } + return m_Connected->EndFlush(); +} +// deliver NewSegment to connected pin +HRESULT +CBaseOutputPin::DeliverNewSegment( + REFERENCE_TIME tStart, + REFERENCE_TIME tStop, + double dRate) +{ + if (m_Connected == NULL) { + return VFW_E_NOT_CONNECTED; + } + return m_Connected->NewSegment(tStart, tStop, dRate); +} + + +//===================================================================== +//===================================================================== +// Implements CBaseInputPin +//===================================================================== +//===================================================================== + + +/* Constructor creates a default allocator object */ + +CBaseInputPin::CBaseInputPin(__in_opt LPCTSTR pObjectName, + __in CBaseFilter *pFilter, + __in CCritSec *pLock, + __inout HRESULT *phr, + __in_opt LPCWSTR pPinName) : + CBasePin(pObjectName, pFilter, pLock, phr, pPinName, PINDIR_INPUT), + m_pAllocator(NULL), + m_bReadOnly(FALSE), + m_bFlushing(FALSE) +{ + ZeroMemory(&m_SampleProps, sizeof(m_SampleProps)); +} + +#ifdef UNICODE +CBaseInputPin::CBaseInputPin(__in LPCSTR pObjectName, + __in CBaseFilter *pFilter, + __in CCritSec *pLock, + __inout HRESULT *phr, + __in_opt LPCWSTR pPinName) : + CBasePin(pObjectName, pFilter, pLock, phr, pPinName, PINDIR_INPUT), + m_pAllocator(NULL), + m_bReadOnly(FALSE), + m_bFlushing(FALSE) +{ + ZeroMemory(&m_SampleProps, sizeof(m_SampleProps)); +} +#endif + +/* Destructor releases it's reference count on the default allocator */ + +CBaseInputPin::~CBaseInputPin() +{ + if (m_pAllocator != NULL) { + m_pAllocator->Release(); + m_pAllocator = NULL; + } +} + + +// override this to publicise our interfaces +STDMETHODIMP +CBaseInputPin::NonDelegatingQueryInterface(REFIID riid, __deref_out void **ppv) +{ + /* Do we know about this interface */ + + if (riid == IID_IMemInputPin) { + return GetInterface((IMemInputPin *) this, ppv); + } else { + return CBasePin::NonDelegatingQueryInterface(riid, ppv); + } +} + + +/* Return the allocator interface that this input pin would like the output + pin to use. NOTE subsequent calls to GetAllocator should all return an + interface onto the SAME object so we create one object at the start + + Note: + The allocator is Release()'d on disconnect and replaced on + NotifyAllocator(). + + Override this to provide your own allocator. +*/ + +STDMETHODIMP +CBaseInputPin::GetAllocator( + __deref_out IMemAllocator **ppAllocator) +{ + CheckPointer(ppAllocator,E_POINTER); + ValidateReadWritePtr(ppAllocator,sizeof(IMemAllocator *)); + CAutoLock cObjectLock(m_pLock); + + if (m_pAllocator == NULL) { + HRESULT hr = CreateMemoryAllocator(&m_pAllocator); + if (FAILED(hr)) { + return hr; + } + } + ASSERT(m_pAllocator != NULL); + *ppAllocator = m_pAllocator; + m_pAllocator->AddRef(); + return NOERROR; +} + + +/* Tell the input pin which allocator the output pin is actually going to use + Override this if you care - NOTE the locking we do both here and also in + GetAllocator is unnecessary but derived classes that do something useful + will undoubtedly have to lock the object so this might help remind people */ + +STDMETHODIMP +CBaseInputPin::NotifyAllocator( + IMemAllocator * pAllocator, + BOOL bReadOnly) +{ + CheckPointer(pAllocator,E_POINTER); + ValidateReadPtr(pAllocator,sizeof(IMemAllocator)); + CAutoLock cObjectLock(m_pLock); + + IMemAllocator *pOldAllocator = m_pAllocator; + pAllocator->AddRef(); + m_pAllocator = pAllocator; + + if (pOldAllocator != NULL) { + pOldAllocator->Release(); + } + + // the readonly flag indicates whether samples from this allocator should + // be regarded as readonly - if true, then inplace transforms will not be + // allowed. + m_bReadOnly = (BYTE)bReadOnly; + return NOERROR; +} + + +HRESULT +CBaseInputPin::BreakConnect() +{ + /* We don't need our allocator any more */ + if (m_pAllocator) { + // Always decommit the allocator because a downstream filter may or + // may not decommit the connection's allocator. A memory leak could + // occur if the allocator is not decommited when a pin is disconnected. + HRESULT hr = m_pAllocator->Decommit(); + if( FAILED( hr ) ) { + return hr; + } + + m_pAllocator->Release(); + m_pAllocator = NULL; + } + + return S_OK; +} + + +/* Do something with this media sample - this base class checks to see if the + format has changed with this media sample and if so checks that the filter + will accept it, generating a run time error if not. Once we have raised a + run time error we set a flag so that no more samples will be accepted + + It is important that any filter should override this method and implement + synchronization so that samples are not processed when the pin is + disconnected etc +*/ + +STDMETHODIMP +CBaseInputPin::Receive(IMediaSample *pSample) +{ + CheckPointer(pSample,E_POINTER); + ValidateReadPtr(pSample,sizeof(IMediaSample)); + ASSERT(pSample); + + HRESULT hr = CheckStreaming(); + if (S_OK != hr) { + return hr; + } + +#ifdef DXMPERF + PERFLOG_RECEIVE( m_pName ? m_pName : L"CBaseInputPin", (IPin *) m_Connected, (IPin *) this, pSample, &m_mt ); +#endif // DXMPERF + + + /* Check for IMediaSample2 */ + IMediaSample2 *pSample2; + if (SUCCEEDED(pSample->QueryInterface(IID_IMediaSample2, (void **)&pSample2))) { + hr = pSample2->GetProperties(sizeof(m_SampleProps), (PBYTE)&m_SampleProps); + pSample2->Release(); + if (FAILED(hr)) { + return hr; + } + } else { + /* Get the properties the hard way */ + m_SampleProps.cbData = sizeof(m_SampleProps); + m_SampleProps.dwTypeSpecificFlags = 0; + m_SampleProps.dwStreamId = AM_STREAM_MEDIA; + m_SampleProps.dwSampleFlags = 0; + if (S_OK == pSample->IsDiscontinuity()) { + m_SampleProps.dwSampleFlags |= AM_SAMPLE_DATADISCONTINUITY; + } + if (S_OK == pSample->IsPreroll()) { + m_SampleProps.dwSampleFlags |= AM_SAMPLE_PREROLL; + } + if (S_OK == pSample->IsSyncPoint()) { + m_SampleProps.dwSampleFlags |= AM_SAMPLE_SPLICEPOINT; + } + if (SUCCEEDED(pSample->GetTime(&m_SampleProps.tStart, + &m_SampleProps.tStop))) { + m_SampleProps.dwSampleFlags |= AM_SAMPLE_TIMEVALID | + AM_SAMPLE_STOPVALID; + } + if (S_OK == pSample->GetMediaType(&m_SampleProps.pMediaType)) { + m_SampleProps.dwSampleFlags |= AM_SAMPLE_TYPECHANGED; + } + pSample->GetPointer(&m_SampleProps.pbBuffer); + m_SampleProps.lActual = pSample->GetActualDataLength(); + m_SampleProps.cbBuffer = pSample->GetSize(); + } + + /* Has the format changed in this sample */ + + if (!(m_SampleProps.dwSampleFlags & AM_SAMPLE_TYPECHANGED)) { + return NOERROR; + } + + /* Check the derived class accepts this format */ + /* This shouldn't fail as the source must call QueryAccept first */ + + hr = CheckMediaType((CMediaType *)m_SampleProps.pMediaType); + + if (hr == NOERROR) { + return NOERROR; + } + + /* Raise a runtime error if we fail the media type */ + + m_bRunTimeError = TRUE; + EndOfStream(); + m_pFilter->NotifyEvent(EC_ERRORABORT,VFW_E_TYPE_NOT_ACCEPTED,0); + return VFW_E_INVALIDMEDIATYPE; +} + + +/* Receive multiple samples */ +STDMETHODIMP +CBaseInputPin::ReceiveMultiple ( + __in_ecount(nSamples) IMediaSample **pSamples, + long nSamples, + __out long *nSamplesProcessed) +{ + CheckPointer(pSamples,E_POINTER); + ValidateReadPtr(pSamples,nSamples * sizeof(IMediaSample *)); + + HRESULT hr = S_OK; + *nSamplesProcessed = 0; + while (nSamples-- > 0) { + hr = Receive(pSamples[*nSamplesProcessed]); + + /* S_FALSE means don't send any more */ + if (hr != S_OK) { + break; + } + (*nSamplesProcessed)++; + } + return hr; +} + +/* See if Receive() might block */ +STDMETHODIMP +CBaseInputPin::ReceiveCanBlock() +{ + /* Ask all the output pins if they block + If there are no output pin assume we do block + */ + int cPins = m_pFilter->GetPinCount(); + int cOutputPins = 0; + for (int c = 0; c < cPins; c++) { + CBasePin *pPin = m_pFilter->GetPin(c); + if (NULL == pPin) { + break; + } + PIN_DIRECTION pd; + HRESULT hr = pPin->QueryDirection(&pd); + if (FAILED(hr)) { + return hr; + } + + if (pd == PINDIR_OUTPUT) { + + IPin *pConnected; + hr = pPin->ConnectedTo(&pConnected); + if (SUCCEEDED(hr)) { + ASSERT(pConnected != NULL); + cOutputPins++; + IMemInputPin *pInputPin; + hr = pConnected->QueryInterface( + IID_IMemInputPin, + (void **)&pInputPin); + pConnected->Release(); + if (SUCCEEDED(hr)) { + hr = pInputPin->ReceiveCanBlock(); + pInputPin->Release(); + if (hr != S_FALSE) { + return S_OK; + } + } else { + /* There's a transport we don't understand here */ + return S_OK; + } + } + } + } + return cOutputPins == 0 ? S_OK : S_FALSE; +} + +// Default handling for BeginFlush - call at the beginning +// of your implementation (makes sure that all Receive calls +// fail). After calling this, you need to free any queued data +// and then call downstream. +STDMETHODIMP +CBaseInputPin::BeginFlush(void) +{ + // BeginFlush is NOT synchronized with streaming but is part of + // a control action - hence we synchronize with the filter + CAutoLock lck(m_pLock); + + // if we are already in mid-flush, this is probably a mistake + // though not harmful - try to pick it up for now so I can think about it + ASSERT(!m_bFlushing); + + // first thing to do is ensure that no further Receive calls succeed + m_bFlushing = TRUE; + + // now discard any data and call downstream - must do that + // in derived classes + return S_OK; +} + +// default handling for EndFlush - call at end of your implementation +// - before calling this, ensure that there is no queued data and no thread +// pushing any more without a further receive, then call downstream, +// then call this method to clear the m_bFlushing flag and re-enable +// receives +STDMETHODIMP +CBaseInputPin::EndFlush(void) +{ + // Endlush is NOT synchronized with streaming but is part of + // a control action - hence we synchronize with the filter + CAutoLock lck(m_pLock); + + // almost certainly a mistake if we are not in mid-flush + ASSERT(m_bFlushing); + + // before calling, sync with pushing thread and ensure + // no more data is going downstream, then call EndFlush on + // downstream pins. + + // now re-enable Receives + m_bFlushing = FALSE; + + // No more errors + m_bRunTimeError = FALSE; + + return S_OK; +} + + +STDMETHODIMP +CBaseInputPin::Notify(IBaseFilter * pSender, Quality q) +{ + UNREFERENCED_PARAMETER(q); + CheckPointer(pSender,E_POINTER); + ValidateReadPtr(pSender,sizeof(IBaseFilter)); + DbgBreak("IQuality::Notify called on an input pin"); + return NOERROR; +} // Notify + +/* Free up or unprepare allocator's memory, this is called through + IMediaFilter which is responsible for locking the object first */ + +HRESULT +CBaseInputPin::Inactive(void) +{ + m_bRunTimeError = FALSE; + if (m_pAllocator == NULL) { + return VFW_E_NO_ALLOCATOR; + } + + m_bFlushing = FALSE; + + return m_pAllocator->Decommit(); +} + +// what requirements do we have of the allocator - override if you want +// to support other people's allocators but need a specific alignment +// or prefix. +STDMETHODIMP +CBaseInputPin::GetAllocatorRequirements(__out ALLOCATOR_PROPERTIES*pProps) +{ + UNREFERENCED_PARAMETER(pProps); + return E_NOTIMPL; +} + +// Check if it's OK to process data +// +HRESULT +CBaseInputPin::CheckStreaming() +{ + // Shouldn't be able to get any data if we're not connected! + ASSERT(IsConnected()); + + // Don't process stuff in Stopped state + if (IsStopped()) { + return VFW_E_WRONG_STATE; + } + if (m_bFlushing) { + return S_FALSE; + } + if (m_bRunTimeError) { + return VFW_E_RUNTIME_ERROR; + } + return S_OK; +} + +// Pass on the Quality notification q to +// a. Our QualityControl sink (if we have one) or else +// b. to our upstream filter +// and if that doesn't work, throw it away with a bad return code +HRESULT +CBaseInputPin::PassNotify(Quality& q) +{ + // We pass the message on, which means that we find the quality sink + // for our input pin and send it there + + DbgLog((LOG_TRACE,3,TEXT("Passing Quality notification through transform"))); + if (m_pQSink!=NULL) { + return m_pQSink->Notify(m_pFilter, q); + } else { + // no sink set, so pass it upstream + HRESULT hr; + IQualityControl * pIQC; + + hr = VFW_E_NOT_FOUND; // default + if (m_Connected) { + m_Connected->QueryInterface(IID_IQualityControl, (void**)&pIQC); + + if (pIQC!=NULL) { + hr = pIQC->Notify(m_pFilter, q); + pIQC->Release(); + } + } + return hr; + } + +} // PassNotify + +//===================================================================== +//===================================================================== +// Memory allocation class, implements CMediaSample +//===================================================================== +//===================================================================== + + +/* NOTE The implementation of this class calls the CUnknown constructor with + a NULL outer unknown pointer. This has the effect of making us a self + contained class, ie any QueryInterface, AddRef or Release calls will be + routed to the class's NonDelegatingUnknown methods. You will typically + find that the classes that do this then override one or more of these + virtual functions to provide more specialised behaviour. A good example + of this is where a class wants to keep the QueryInterface internal but + still wants it's lifetime controlled by the external object */ + +/* The last two parameters have default values of NULL and zero */ + +CMediaSample::CMediaSample(__in_opt LPCTSTR pName, + __in_opt CBaseAllocator *pAllocator, + __inout_opt HRESULT *phr, + __in_bcount_opt(length) LPBYTE pBuffer, + LONG length) : + m_pBuffer(pBuffer), // Initialise the buffer + m_cbBuffer(length), // And it's length + m_lActual(length), // By default, actual = length + m_pMediaType(NULL), // No media type change + m_dwFlags(0), // Nothing set + m_cRef(0), // 0 ref count + m_dwTypeSpecificFlags(0), // Type specific flags + m_dwStreamId(AM_STREAM_MEDIA), // Stream id + m_pAllocator(pAllocator) // Allocator +{ +#ifdef DXMPERF + PERFLOG_CTOR( pName ? pName : L"CMediaSample", (IMediaSample *) this ); +#endif // DXMPERF + + /* We must have an owner and it must also be derived from class + CBaseAllocator BUT we do not hold a reference count on it */ + + ASSERT(pAllocator); + + if (length < 0) { + *phr = VFW_E_BUFFER_OVERFLOW; + m_cbBuffer = 0; + } +} + +#ifdef UNICODE +CMediaSample::CMediaSample(__in_opt LPCSTR pName, + __in_opt CBaseAllocator *pAllocator, + __inout_opt HRESULT *phr, + __in_bcount_opt(length) LPBYTE pBuffer, + LONG length) : + m_pBuffer(pBuffer), // Initialise the buffer + m_cbBuffer(length), // And it's length + m_lActual(length), // By default, actual = length + m_pMediaType(NULL), // No media type change + m_dwFlags(0), // Nothing set + m_cRef(0), // 0 ref count + m_dwTypeSpecificFlags(0), // Type specific flags + m_dwStreamId(AM_STREAM_MEDIA), // Stream id + m_pAllocator(pAllocator) // Allocator +{ +#ifdef DXMPERF + PERFLOG_CTOR( L"CMediaSample", (IMediaSample *) this ); +#endif // DXMPERF + + /* We must have an owner and it must also be derived from class + CBaseAllocator BUT we do not hold a reference count on it */ + + ASSERT(pAllocator); +} +#endif + +/* Destructor deletes the media type memory */ + +CMediaSample::~CMediaSample() +{ +#ifdef DXMPERF + PERFLOG_DTOR( L"CMediaSample", (IMediaSample *) this ); +#endif // DXMPERF + + if (m_pMediaType) { + DeleteMediaType(m_pMediaType); + } +} + +/* Override this to publicise our interfaces */ + +STDMETHODIMP +CMediaSample::QueryInterface(REFIID riid, __deref_out void **ppv) +{ + if (riid == IID_IMediaSample || + riid == IID_IMediaSample2 || + riid == IID_IUnknown) { + return GetInterface((IMediaSample *) this, ppv); + } else { + *ppv = NULL; + return E_NOINTERFACE; + } +} + +STDMETHODIMP_(ULONG) +CMediaSample::AddRef() +{ + return InterlockedIncrement(&m_cRef); +} + + +// -- CMediaSample lifetimes -- +// +// On final release of this sample buffer it is not deleted but +// returned to the freelist of the owning memory allocator +// +// The allocator may be waiting for the last buffer to be placed on the free +// list in order to decommit all the memory, so the ReleaseBuffer() call may +// result in this sample being deleted. We also need to hold a refcount on +// the allocator to stop that going away until we have finished with this. +// However, we cannot release the allocator before the ReleaseBuffer, as the +// release may cause us to be deleted. Similarly we can't do it afterwards. +// +// Thus we must leave it to the allocator to hold an addref on our behalf. +// When he issues us in GetBuffer, he addref's himself. When ReleaseBuffer +// is called, he releases himself, possibly causing us and him to be deleted. + + +STDMETHODIMP_(ULONG) +CMediaSample::Release() +{ + /* Decrement our own private reference count */ + LONG lRef; + if (m_cRef == 1) { + lRef = 0; + m_cRef = 0; + } else { + lRef = InterlockedDecrement(&m_cRef); + } + ASSERT(lRef >= 0); + + DbgLog((LOG_MEMORY,3,TEXT(" Unknown %X ref-- = %d"), + this, m_cRef)); + + /* Did we release our final reference count */ + if (lRef == 0) { + /* Free all resources */ + if (m_dwFlags & Sample_TypeChanged) { + SetMediaType(NULL); + } + ASSERT(m_pMediaType == NULL); + m_dwFlags = 0; + m_dwTypeSpecificFlags = 0; + m_dwStreamId = AM_STREAM_MEDIA; + + /* This may cause us to be deleted */ + // Our refcount is reliably 0 thus no-one will mess with us + m_pAllocator->ReleaseBuffer(this); + } + return (ULONG)lRef; +} + + +// set the buffer pointer and length. Used by allocators that +// want variable sized pointers or pointers into already-read data. +// This is only available through a CMediaSample* not an IMediaSample* +// and so cannot be changed by clients. +HRESULT +CMediaSample::SetPointer(__in_bcount(cBytes) BYTE * ptr, LONG cBytes) +{ + if (cBytes < 0) { + return VFW_E_BUFFER_OVERFLOW; + } + m_pBuffer = ptr; // new buffer area (could be null) + m_cbBuffer = cBytes; // length of buffer + m_lActual = cBytes; // length of data in buffer (assume full) + + return S_OK; +} + + +// get me a read/write pointer to this buffer's memory. I will actually +// want to use sizeUsed bytes. +STDMETHODIMP +CMediaSample::GetPointer(__deref_out BYTE ** ppBuffer) +{ + ValidateReadWritePtr(ppBuffer,sizeof(BYTE *)); + + // creator must have set pointer either during + // constructor or by SetPointer + ASSERT(m_pBuffer); + + *ppBuffer = m_pBuffer; + return NOERROR; +} + + +// return the size in bytes of this buffer +STDMETHODIMP_(LONG) +CMediaSample::GetSize(void) +{ + return m_cbBuffer; +} + + +// get the stream time at which this sample should start and finish. +STDMETHODIMP +CMediaSample::GetTime( + __out REFERENCE_TIME * pTimeStart, // put time here + __out REFERENCE_TIME * pTimeEnd +) +{ + ValidateReadWritePtr(pTimeStart,sizeof(REFERENCE_TIME)); + ValidateReadWritePtr(pTimeEnd,sizeof(REFERENCE_TIME)); + + if (!(m_dwFlags & Sample_StopValid)) { + if (!(m_dwFlags & Sample_TimeValid)) { + return VFW_E_SAMPLE_TIME_NOT_SET; + } else { + *pTimeStart = m_Start; + + // Make sure old stuff works + *pTimeEnd = m_Start + 1; + return VFW_S_NO_STOP_TIME; + } + } + + *pTimeStart = m_Start; + *pTimeEnd = m_End; + return NOERROR; +} + + +// Set the stream time at which this sample should start and finish. +// NULL pointers means the time is reset +STDMETHODIMP +CMediaSample::SetTime( + __in_opt REFERENCE_TIME * pTimeStart, + __in_opt REFERENCE_TIME * pTimeEnd +) +{ + if (pTimeStart == NULL) { + ASSERT(pTimeEnd == NULL); + m_dwFlags &= ~(Sample_TimeValid | Sample_StopValid); + } else { + if (pTimeEnd == NULL) { + m_Start = *pTimeStart; + m_dwFlags |= Sample_TimeValid; + m_dwFlags &= ~Sample_StopValid; + } else { + ValidateReadPtr(pTimeStart,sizeof(REFERENCE_TIME)); + ValidateReadPtr(pTimeEnd,sizeof(REFERENCE_TIME)); + ASSERT(*pTimeEnd >= *pTimeStart); + + m_Start = *pTimeStart; + m_End = *pTimeEnd; + m_dwFlags |= Sample_TimeValid | Sample_StopValid; + } + } + return NOERROR; +} + + +// get the media times (eg bytes) for this sample +STDMETHODIMP +CMediaSample::GetMediaTime( + __out LONGLONG * pTimeStart, + __out LONGLONG * pTimeEnd +) +{ + ValidateReadWritePtr(pTimeStart,sizeof(LONGLONG)); + ValidateReadWritePtr(pTimeEnd,sizeof(LONGLONG)); + + if (!(m_dwFlags & Sample_MediaTimeValid)) { + return VFW_E_MEDIA_TIME_NOT_SET; + } + + *pTimeStart = m_MediaStart; + *pTimeEnd = (m_MediaStart + m_MediaEnd); + return NOERROR; +} + + +// Set the media times for this sample +STDMETHODIMP +CMediaSample::SetMediaTime( + __in_opt LONGLONG * pTimeStart, + __in_opt LONGLONG * pTimeEnd +) +{ + if (pTimeStart == NULL) { + ASSERT(pTimeEnd == NULL); + m_dwFlags &= ~Sample_MediaTimeValid; + } else { + if (NULL == pTimeEnd) { + return E_POINTER; + } + ValidateReadPtr(pTimeStart,sizeof(LONGLONG)); + ValidateReadPtr(pTimeEnd,sizeof(LONGLONG)); + ASSERT(*pTimeEnd >= *pTimeStart); + + m_MediaStart = *pTimeStart; + m_MediaEnd = (LONG)(*pTimeEnd - *pTimeStart); + m_dwFlags |= Sample_MediaTimeValid; + } + return NOERROR; +} + + +STDMETHODIMP +CMediaSample::IsSyncPoint(void) +{ + if (m_dwFlags & Sample_SyncPoint) { + return S_OK; + } else { + return S_FALSE; + } +} + + +STDMETHODIMP +CMediaSample::SetSyncPoint(BOOL bIsSyncPoint) +{ + if (bIsSyncPoint) { + m_dwFlags |= Sample_SyncPoint; + } else { + m_dwFlags &= ~Sample_SyncPoint; + } + return NOERROR; +} + +// returns S_OK if there is a discontinuity in the data (this same is +// not a continuation of the previous stream of data +// - there has been a seek). +STDMETHODIMP +CMediaSample::IsDiscontinuity(void) +{ + if (m_dwFlags & Sample_Discontinuity) { + return S_OK; + } else { + return S_FALSE; + } +} + +// set the discontinuity property - TRUE if this sample is not a +// continuation, but a new sample after a seek. +STDMETHODIMP +CMediaSample::SetDiscontinuity(BOOL bDiscont) +{ + // should be TRUE or FALSE + if (bDiscont) { + m_dwFlags |= Sample_Discontinuity; + } else { + m_dwFlags &= ~Sample_Discontinuity; + } + return S_OK; +} + +STDMETHODIMP +CMediaSample::IsPreroll(void) +{ + if (m_dwFlags & Sample_Preroll) { + return S_OK; + } else { + return S_FALSE; + } +} + + +STDMETHODIMP +CMediaSample::SetPreroll(BOOL bIsPreroll) +{ + if (bIsPreroll) { + m_dwFlags |= Sample_Preroll; + } else { + m_dwFlags &= ~Sample_Preroll; + } + return NOERROR; +} + +STDMETHODIMP_(LONG) +CMediaSample::GetActualDataLength(void) +{ + return m_lActual; +} + + +STDMETHODIMP +CMediaSample::SetActualDataLength(LONG lActual) +{ + if (lActual > m_cbBuffer || lActual < 0) { + ASSERT(lActual <= GetSize()); + return VFW_E_BUFFER_OVERFLOW; + } + m_lActual = lActual; + return NOERROR; +} + + +/* These allow for limited format changes in band */ + +STDMETHODIMP +CMediaSample::GetMediaType(__deref_out AM_MEDIA_TYPE **ppMediaType) +{ + ValidateReadWritePtr(ppMediaType,sizeof(AM_MEDIA_TYPE *)); + ASSERT(ppMediaType); + + /* Do we have a new media type for them */ + + if (!(m_dwFlags & Sample_TypeChanged)) { + ASSERT(m_pMediaType == NULL); + *ppMediaType = NULL; + return S_FALSE; + } + + ASSERT(m_pMediaType); + + /* Create a copy of our media type */ + + *ppMediaType = CreateMediaType(m_pMediaType); + if (*ppMediaType == NULL) { + return E_OUTOFMEMORY; + } + return NOERROR; +} + + +/* Mark this sample as having a different format type */ + +STDMETHODIMP +CMediaSample::SetMediaType(__in_opt AM_MEDIA_TYPE *pMediaType) +{ + /* Delete the current media type */ + + if (m_pMediaType) { + DeleteMediaType(m_pMediaType); + m_pMediaType = NULL; + } + + /* Mechanism for resetting the format type */ + + if (pMediaType == NULL) { + m_dwFlags &= ~Sample_TypeChanged; + return NOERROR; + } + + ASSERT(pMediaType); + ValidateReadPtr(pMediaType,sizeof(AM_MEDIA_TYPE)); + + /* Take a copy of the media type */ + + m_pMediaType = CreateMediaType(pMediaType); + if (m_pMediaType == NULL) { + m_dwFlags &= ~Sample_TypeChanged; + return E_OUTOFMEMORY; + } + + m_dwFlags |= Sample_TypeChanged; + return NOERROR; +} + +// Set and get properties (IMediaSample2) +STDMETHODIMP CMediaSample::GetProperties( + DWORD cbProperties, + __out_bcount(cbProperties) BYTE * pbProperties +) +{ + if (0 != cbProperties) { + CheckPointer(pbProperties, E_POINTER); + // Return generic stuff up to the length + AM_SAMPLE2_PROPERTIES Props; + Props.cbData = min(cbProperties, sizeof(Props)); + Props.dwSampleFlags = m_dwFlags & ~Sample_MediaTimeValid; + Props.dwTypeSpecificFlags = m_dwTypeSpecificFlags; + Props.pbBuffer = m_pBuffer; + Props.cbBuffer = m_cbBuffer; + Props.lActual = m_lActual; + Props.tStart = m_Start; + Props.tStop = m_End; + Props.dwStreamId = m_dwStreamId; + if (m_dwFlags & AM_SAMPLE_TYPECHANGED) { + Props.pMediaType = m_pMediaType; + } else { + Props.pMediaType = NULL; + } + CopyMemory(pbProperties, &Props, Props.cbData); + } + return S_OK; +} + +#define CONTAINS_FIELD(type, field, offset) \ + ((FIELD_OFFSET(type, field) + sizeof(((type *)0)->field)) <= offset) + +HRESULT CMediaSample::SetProperties( + DWORD cbProperties, + __in_bcount(cbProperties) const BYTE * pbProperties +) +{ + + /* Generic properties */ + AM_MEDIA_TYPE *pMediaType = NULL; + + if (CONTAINS_FIELD(AM_SAMPLE2_PROPERTIES, cbData, cbProperties)) { + CheckPointer(pbProperties, E_POINTER); + AM_SAMPLE2_PROPERTIES *pProps = + (AM_SAMPLE2_PROPERTIES *)pbProperties; + + /* Don't use more data than is actually there */ + if (pProps->cbData < cbProperties) { + cbProperties = pProps->cbData; + } + /* We only handle IMediaSample2 */ + if (cbProperties > sizeof(*pProps) || + pProps->cbData > sizeof(*pProps)) { + return E_INVALIDARG; + } + /* Do checks first, the assignments (for backout) */ + if (CONTAINS_FIELD(AM_SAMPLE2_PROPERTIES, dwSampleFlags, cbProperties)) { + /* Check the flags */ + if (pProps->dwSampleFlags & + (~Sample_ValidFlags | Sample_MediaTimeValid)) { + return E_INVALIDARG; + } + /* Check a flag isn't being set for a property + not being provided + */ + if ((pProps->dwSampleFlags & AM_SAMPLE_TIMEVALID) && + !(m_dwFlags & AM_SAMPLE_TIMEVALID) && + !CONTAINS_FIELD(AM_SAMPLE2_PROPERTIES, tStop, cbProperties)) { + return E_INVALIDARG; + } + } + /* NB - can't SET the pointer or size */ + if (CONTAINS_FIELD(AM_SAMPLE2_PROPERTIES, pbBuffer, cbProperties)) { + + /* Check pbBuffer */ + if (pProps->pbBuffer != 0 && pProps->pbBuffer != m_pBuffer) { + return E_INVALIDARG; + } + } + if (CONTAINS_FIELD(AM_SAMPLE2_PROPERTIES, cbBuffer, cbProperties)) { + + /* Check cbBuffer */ + if (pProps->cbBuffer != 0 && pProps->cbBuffer != m_cbBuffer) { + return E_INVALIDARG; + } + } + if (CONTAINS_FIELD(AM_SAMPLE2_PROPERTIES, cbBuffer, cbProperties) && + CONTAINS_FIELD(AM_SAMPLE2_PROPERTIES, lActual, cbProperties)) { + + /* Check lActual */ + if (pProps->cbBuffer < pProps->lActual) { + return E_INVALIDARG; + } + } + + if (CONTAINS_FIELD(AM_SAMPLE2_PROPERTIES, pMediaType, cbProperties)) { + + /* Check pMediaType */ + if (pProps->dwSampleFlags & AM_SAMPLE_TYPECHANGED) { + CheckPointer(pProps->pMediaType, E_POINTER); + pMediaType = CreateMediaType(pProps->pMediaType); + if (pMediaType == NULL) { + return E_OUTOFMEMORY; + } + } + } + + /* Now do the assignments */ + if (CONTAINS_FIELD(AM_SAMPLE2_PROPERTIES, dwStreamId, cbProperties)) { + m_dwStreamId = pProps->dwStreamId; + } + if (CONTAINS_FIELD(AM_SAMPLE2_PROPERTIES, dwSampleFlags, cbProperties)) { + /* Set the flags */ + m_dwFlags = pProps->dwSampleFlags | + (m_dwFlags & Sample_MediaTimeValid); + m_dwTypeSpecificFlags = pProps->dwTypeSpecificFlags; + } else { + if (CONTAINS_FIELD(AM_SAMPLE2_PROPERTIES, dwTypeSpecificFlags, cbProperties)) { + m_dwTypeSpecificFlags = pProps->dwTypeSpecificFlags; + } + } + + if (CONTAINS_FIELD(AM_SAMPLE2_PROPERTIES, lActual, cbProperties)) { + /* Set lActual */ + m_lActual = pProps->lActual; + } + + if (CONTAINS_FIELD(AM_SAMPLE2_PROPERTIES, tStop, cbProperties)) { + + /* Set the times */ + m_End = pProps->tStop; + } + if (CONTAINS_FIELD(AM_SAMPLE2_PROPERTIES, tStart, cbProperties)) { + + /* Set the times */ + m_Start = pProps->tStart; + } + + if (CONTAINS_FIELD(AM_SAMPLE2_PROPERTIES, pMediaType, cbProperties)) { + /* Set pMediaType */ + if (pProps->dwSampleFlags & AM_SAMPLE_TYPECHANGED) { + if (m_pMediaType != NULL) { + DeleteMediaType(m_pMediaType); + } + m_pMediaType = pMediaType; + } + } + + /* Fix up the type changed flag to correctly reflect the current state + If, for instance the input contained no type change but the + output does then if we don't do this we'd lose the + output media type. + */ + if (m_pMediaType) { + m_dwFlags |= Sample_TypeChanged; + } else { + m_dwFlags &= ~Sample_TypeChanged; + } + } + + return S_OK; +} + + +// +// The streaming thread calls IPin::NewSegment(), IPin::EndOfStream(), +// IMemInputPin::Receive() and IMemInputPin::ReceiveMultiple() on the +// connected input pin. The application thread calls Block(). The +// following class members can only be called by the streaming thread. +// +// Deliver() +// DeliverNewSegment() +// StartUsingOutputPin() +// StopUsingOutputPin() +// ChangeOutputFormat() +// ChangeMediaType() +// DynamicReconnect() +// +// The following class members can only be called by the application thread. +// +// Block() +// SynchronousBlockOutputPin() +// AsynchronousBlockOutputPin() +// + +CDynamicOutputPin::CDynamicOutputPin( + __in_opt LPCTSTR pObjectName, + __in CBaseFilter *pFilter, + __in CCritSec *pLock, + __inout HRESULT *phr, + __in_opt LPCWSTR pName) : + CBaseOutputPin(pObjectName, pFilter, pLock, phr, pName), + m_hStopEvent(NULL), + m_pGraphConfig(NULL), + m_bPinUsesReadOnlyAllocator(FALSE), + m_BlockState(NOT_BLOCKED), + m_hUnblockOutputPinEvent(NULL), + m_hNotifyCallerPinBlockedEvent(NULL), + m_dwBlockCallerThreadID(0), + m_dwNumOutstandingOutputPinUsers(0) +{ + HRESULT hr = Initialize(); + if( FAILED( hr ) ) { + *phr = hr; + return; + } +} + +#ifdef UNICODE +CDynamicOutputPin::CDynamicOutputPin( + __in_opt LPCSTR pObjectName, + __in CBaseFilter *pFilter, + __in CCritSec *pLock, + __inout HRESULT *phr, + __in_opt LPCWSTR pName) : + CBaseOutputPin(pObjectName, pFilter, pLock, phr, pName), + m_hStopEvent(NULL), + m_pGraphConfig(NULL), + m_bPinUsesReadOnlyAllocator(FALSE), + m_BlockState(NOT_BLOCKED), + m_hUnblockOutputPinEvent(NULL), + m_hNotifyCallerPinBlockedEvent(NULL), + m_dwBlockCallerThreadID(0), + m_dwNumOutstandingOutputPinUsers(0) +{ + HRESULT hr = Initialize(); + if( FAILED( hr ) ) { + *phr = hr; + return; + } +} +#endif + +CDynamicOutputPin::~CDynamicOutputPin() +{ + if(NULL != m_hUnblockOutputPinEvent) { + // This call should not fail because we have access to m_hUnblockOutputPinEvent + // and m_hUnblockOutputPinEvent is a valid event. + EXECUTE_ASSERT(::CloseHandle(m_hUnblockOutputPinEvent)); + } + + if(NULL != m_hNotifyCallerPinBlockedEvent) { + // This call should not fail because we have access to m_hNotifyCallerPinBlockedEvent + // and m_hNotifyCallerPinBlockedEvent is a valid event. + EXECUTE_ASSERT(::CloseHandle(m_hNotifyCallerPinBlockedEvent)); + } +} + +HRESULT CDynamicOutputPin::Initialize(void) +{ + m_hUnblockOutputPinEvent = ::CreateEvent( NULL, // The event will have the default security descriptor. + TRUE, // This is a manual reset event. + TRUE, // The event is initially signaled. + NULL ); // The event is not named. + + // CreateEvent() returns NULL if an error occurs. + if(NULL == m_hUnblockOutputPinEvent) { + return AmGetLastErrorToHResult(); + } + + // Set flag to say we can reconnect while streaming. + SetReconnectWhenActive(true); + + return S_OK; +} + +STDMETHODIMP CDynamicOutputPin::NonDelegatingQueryInterface(REFIID riid, __deref_out void **ppv) +{ + if(riid == IID_IPinFlowControl) { + return GetInterface(static_cast(this), ppv); + } else { + return CBaseOutputPin::NonDelegatingQueryInterface(riid, ppv); + } +} + +STDMETHODIMP CDynamicOutputPin::Disconnect(void) +{ + CAutoLock cObjectLock(m_pLock); + return DisconnectInternal(); +} + +STDMETHODIMP CDynamicOutputPin::Block(DWORD dwBlockFlags, HANDLE hEvent) +{ + const DWORD VALID_FLAGS = AM_PIN_FLOW_CONTROL_BLOCK; + + // Check for illegal flags. + if(dwBlockFlags & ~VALID_FLAGS) { + return E_INVALIDARG; + } + + // Make sure the event is unsignaled. + if((dwBlockFlags & AM_PIN_FLOW_CONTROL_BLOCK) && (NULL != hEvent)) { + if( !::ResetEvent( hEvent ) ) { + return AmGetLastErrorToHResult(); + } + } + + // No flags are set if we are unblocking the output pin. + if(0 == dwBlockFlags) { + + // This parameter should be NULL because unblock operations are always synchronous. + // There is no need to notify the caller when the event is done. + if(NULL != hEvent) { + return E_INVALIDARG; + } + } + + #ifdef DEBUG + AssertValid(); + #endif // DEBUG + + HRESULT hr; + + if(dwBlockFlags & AM_PIN_FLOW_CONTROL_BLOCK) { + // IPinFlowControl::Block()'s hEvent parameter is NULL if the block is synchronous. + // If hEvent is not NULL, the block is asynchronous. + if(NULL == hEvent) { + hr = SynchronousBlockOutputPin(); + } else { + hr = AsynchronousBlockOutputPin(hEvent); + } + } else { + hr = UnblockOutputPin(); + } + + #ifdef DEBUG + AssertValid(); + #endif // DEBUG + + if(FAILED(hr)) { + return hr; + } + + return S_OK; +} + +HRESULT CDynamicOutputPin::SynchronousBlockOutputPin(void) +{ + HANDLE hNotifyCallerPinBlockedEvent = :: CreateEvent( NULL, // The event will have the default security attributes. + FALSE, // This is an automatic reset event. + FALSE, // The event is initially unsignaled. + NULL ); // The event is not named. + + // CreateEvent() returns NULL if an error occurs. + if(NULL == hNotifyCallerPinBlockedEvent) { + return AmGetLastErrorToHResult(); + } + + HRESULT hr = AsynchronousBlockOutputPin(hNotifyCallerPinBlockedEvent); + if(FAILED(hr)) { + // This call should not fail because we have access to hNotifyCallerPinBlockedEvent + // and hNotifyCallerPinBlockedEvent is a valid event. + EXECUTE_ASSERT(::CloseHandle(hNotifyCallerPinBlockedEvent)); + + return hr; + } + + hr = WaitEvent(hNotifyCallerPinBlockedEvent); + + // This call should not fail because we have access to hNotifyCallerPinBlockedEvent + // and hNotifyCallerPinBlockedEvent is a valid event. + EXECUTE_ASSERT(::CloseHandle(hNotifyCallerPinBlockedEvent)); + + if(FAILED(hr)) { + return hr; + } + + return S_OK; +} + +HRESULT CDynamicOutputPin::AsynchronousBlockOutputPin(HANDLE hNotifyCallerPinBlockedEvent) +{ + // This function holds the m_BlockStateLock because it uses + // m_dwBlockCallerThreadID, m_BlockState and + // m_hNotifyCallerPinBlockedEvent. + CAutoLock alBlockStateLock(&m_BlockStateLock); + + if(NOT_BLOCKED != m_BlockState) { + if(m_dwBlockCallerThreadID == ::GetCurrentThreadId()) { + return VFW_E_PIN_ALREADY_BLOCKED_ON_THIS_THREAD; + } else { + return VFW_E_PIN_ALREADY_BLOCKED; + } + } + + BOOL fSuccess = ::DuplicateHandle( ::GetCurrentProcess(), + hNotifyCallerPinBlockedEvent, + ::GetCurrentProcess(), + &m_hNotifyCallerPinBlockedEvent, + EVENT_MODIFY_STATE, + FALSE, + 0 ); + if( !fSuccess ) { + return AmGetLastErrorToHResult(); + } + + m_BlockState = PENDING; + m_dwBlockCallerThreadID = ::GetCurrentThreadId(); + + // The output pin cannot be blocked if the streaming thread is + // calling IPin::NewSegment(), IPin::EndOfStream(), IMemInputPin::Receive() + // or IMemInputPin::ReceiveMultiple() on the connected input pin. Also, it + // cannot be blocked if the streaming thread is calling DynamicReconnect(), + // ChangeMediaType() or ChangeOutputFormat(). + if(!StreamingThreadUsingOutputPin()) { + + // The output pin can be immediately blocked. + BlockOutputPin(); + } + + return S_OK; +} + +void CDynamicOutputPin::BlockOutputPin(void) +{ + // The caller should always hold the m_BlockStateLock because this function + // uses m_BlockState and m_hNotifyCallerPinBlockedEvent. + ASSERT(CritCheckIn(&m_BlockStateLock)); + + // This function should not be called if the streaming thread is modifying + // the connection state or it's passing data downstream. + ASSERT(!StreamingThreadUsingOutputPin()); + + // This should not fail because we successfully created the event + // and we have the security permissions to change it's state. + EXECUTE_ASSERT(::ResetEvent(m_hUnblockOutputPinEvent)); + + // This event should not fail because AsynchronousBlockOutputPin() successfully + // duplicated this handle and we have the appropriate security permissions. + EXECUTE_ASSERT(::SetEvent(m_hNotifyCallerPinBlockedEvent)); + EXECUTE_ASSERT(::CloseHandle(m_hNotifyCallerPinBlockedEvent)); + + m_BlockState = BLOCKED; + m_hNotifyCallerPinBlockedEvent = NULL; +} + +HRESULT CDynamicOutputPin::UnblockOutputPin(void) +{ + // UnblockOutputPin() holds the m_BlockStateLock because it + // uses m_BlockState, m_dwBlockCallerThreadID and + // m_hNotifyCallerPinBlockedEvent. + CAutoLock alBlockStateLock(&m_BlockStateLock); + + if(NOT_BLOCKED == m_BlockState) { + return S_FALSE; + } + + // This should not fail because we successfully created the event + // and we have the security permissions to change it's state. + EXECUTE_ASSERT(::SetEvent(m_hUnblockOutputPinEvent)); + + // Cancel the block operation if it's still pending. + if(NULL != m_hNotifyCallerPinBlockedEvent) { + // This event should not fail because AsynchronousBlockOutputPin() successfully + // duplicated this handle and we have the appropriate security permissions. + EXECUTE_ASSERT(::SetEvent(m_hNotifyCallerPinBlockedEvent)); + EXECUTE_ASSERT(::CloseHandle(m_hNotifyCallerPinBlockedEvent)); + } + + m_BlockState = NOT_BLOCKED; + m_dwBlockCallerThreadID = 0; + m_hNotifyCallerPinBlockedEvent = NULL; + + return S_OK; +} + +HRESULT CDynamicOutputPin::StartUsingOutputPin(void) +{ + // The caller should not hold m_BlockStateLock. If the caller does, + // a deadlock could occur. + ASSERT(CritCheckOut(&m_BlockStateLock)); + + CAutoLock alBlockStateLock(&m_BlockStateLock); + + #ifdef DEBUG + AssertValid(); + #endif // DEBUG + + // Are we in the middle of a block operation? + while(BLOCKED == m_BlockState) { + m_BlockStateLock.Unlock(); + + // If this ASSERT fires, a deadlock could occur. The caller should make sure + // that this thread never acquires the Block State lock more than once. + ASSERT(CritCheckOut( &m_BlockStateLock )); + + // WaitForMultipleObjects() returns WAIT_OBJECT_0 if the unblock event + // is fired. It returns WAIT_OBJECT_0 + 1 if the stop event if fired. + // See the Windows SDK documentation for more information on + // WaitForMultipleObjects(). + const DWORD UNBLOCK = WAIT_OBJECT_0; + const DWORD STOP = WAIT_OBJECT_0 + 1; + + HANDLE ahWaitEvents[] = { m_hUnblockOutputPinEvent, m_hStopEvent }; + DWORD dwNumWaitEvents = sizeof(ahWaitEvents)/sizeof(HANDLE); + + DWORD dwReturnValue = ::WaitForMultipleObjects( dwNumWaitEvents, ahWaitEvents, FALSE, INFINITE ); + + m_BlockStateLock.Lock(); + + #ifdef DEBUG + AssertValid(); + #endif // DEBUG + + switch( dwReturnValue ) { + case UNBLOCK: + break; + + case STOP: + return VFW_E_STATE_CHANGED; + + case WAIT_FAILED: + return AmGetLastErrorToHResult(); + + default: + DbgBreak( "An Unexpected case occured in CDynamicOutputPin::StartUsingOutputPin()." ); + return E_UNEXPECTED; + } + } + + m_dwNumOutstandingOutputPinUsers++; + + #ifdef DEBUG + AssertValid(); + #endif // DEBUG + + return S_OK; +} + +void CDynamicOutputPin::StopUsingOutputPin(void) +{ + CAutoLock alBlockStateLock(&m_BlockStateLock); + + #ifdef DEBUG + AssertValid(); + #endif // DEBUG + + m_dwNumOutstandingOutputPinUsers--; + + if((m_dwNumOutstandingOutputPinUsers == 0) && (NOT_BLOCKED != m_BlockState)) { + BlockOutputPin(); + } + + #ifdef DEBUG + AssertValid(); + #endif // DEBUG +} + +bool CDynamicOutputPin::StreamingThreadUsingOutputPin(void) +{ + CAutoLock alBlockStateLock(&m_BlockStateLock); + + return (m_dwNumOutstandingOutputPinUsers > 0); +} + +void CDynamicOutputPin::SetConfigInfo(IGraphConfig *pGraphConfig, HANDLE hStopEvent) +{ + // This pointer is not addrefed because filters are not allowed to + // hold references to the filter graph manager. See the documentation for + // IBaseFilter::JoinFilterGraph() in the Direct Show SDK for more information. + m_pGraphConfig = pGraphConfig; + + m_hStopEvent = hStopEvent; +} + +HRESULT CDynamicOutputPin::Active(void) +{ + // Make sure the user initialized the object by calling SetConfigInfo(). + if((NULL == m_hStopEvent) || (NULL == m_pGraphConfig)) { + DbgBreak( ERROR: CDynamicOutputPin::Active() failed because m_pGraphConfig and m_hStopEvent were not initialized. Call SetConfigInfo() to initialize them. ); + return E_FAIL; + } + + // If this ASSERT fires, the user may have passed an invalid event handle to SetConfigInfo(). + // The ASSERT can also fire if the event if destroyed and then Active() is called. An event + // handle is invalid if 1) the event does not exist or the user does not have the security + // permissions to use the event. + EXECUTE_ASSERT(ResetEvent(m_hStopEvent)); + + return CBaseOutputPin::Active(); +} + +HRESULT CDynamicOutputPin::Inactive(void) +{ + // If this ASSERT fires, the user may have passed an invalid event handle to SetConfigInfo(). + // The ASSERT can also fire if the event if destroyed and then Active() is called. An event + // handle is invalid if 1) the event does not exist or the user does not have the security + // permissions to use the event. + EXECUTE_ASSERT(SetEvent(m_hStopEvent)); + + return CBaseOutputPin::Inactive(); +} + +HRESULT CDynamicOutputPin::DeliverBeginFlush(void) +{ + // If this ASSERT fires, the user may have passed an invalid event handle to SetConfigInfo(). + // The ASSERT can also fire if the event if destroyed and then DeliverBeginFlush() is called. + // An event handle is invalid if 1) the event does not exist or the user does not have the security + // permissions to use the event. + EXECUTE_ASSERT(SetEvent(m_hStopEvent)); + + return CBaseOutputPin::DeliverBeginFlush(); +} + +HRESULT CDynamicOutputPin::DeliverEndFlush(void) +{ + // If this ASSERT fires, the user may have passed an invalid event handle to SetConfigInfo(). + // The ASSERT can also fire if the event if destroyed and then DeliverBeginFlush() is called. + // An event handle is invalid if 1) the event does not exist or the user does not have the security + // permissions to use the event. + EXECUTE_ASSERT(ResetEvent(m_hStopEvent)); + + return CBaseOutputPin::DeliverEndFlush(); +} + + +// ChangeOutputFormat() either dynamicly changes the connection's format type or it dynamicly +// reconnects the output pin. +HRESULT CDynamicOutputPin::ChangeOutputFormat + ( + const AM_MEDIA_TYPE *pmt, + REFERENCE_TIME tSegmentStart, + REFERENCE_TIME tSegmentStop, + double dSegmentRate + ) +{ + // The caller should call StartUsingOutputPin() before calling this + // method. + ASSERT(StreamingThreadUsingOutputPin()); + + // Callers should always pass a valid media type to ChangeOutputFormat() . + ASSERT(NULL != pmt); + + CMediaType cmt(*pmt); + HRESULT hr = ChangeMediaType(&cmt); + if (FAILED(hr)) { + return hr; + } + + hr = DeliverNewSegment(tSegmentStart, tSegmentStop, dSegmentRate); + if( FAILED( hr ) ) { + return hr; + } + + return S_OK; +} + +HRESULT CDynamicOutputPin::ChangeMediaType(const CMediaType *pmt) +{ + // The caller should call StartUsingOutputPin() before calling this + // method. + ASSERT(StreamingThreadUsingOutputPin()); + + // This function assumes the filter graph is running. + ASSERT(!IsStopped()); + + if(!IsConnected()) { + return VFW_E_NOT_CONNECTED; + } + + /* First check if the downstream pin will accept a dynamic + format change + */ + QzCComPtr pConnection; + + m_Connected->QueryInterface(IID_IPinConnection, (void **)&pConnection); + if(pConnection != NULL) { + + if(S_OK == pConnection->DynamicQueryAccept(pmt)) { + + HRESULT hr = ChangeMediaTypeHelper(pmt); + if(FAILED(hr)) { + return hr; + } + + return S_OK; + } + } + + /* Can't do the dynamic connection */ + return DynamicReconnect(pmt); +} + +HRESULT CDynamicOutputPin::ChangeMediaTypeHelper(const CMediaType *pmt) +{ + // The caller should call StartUsingOutputPin() before calling this + // method. + ASSERT(StreamingThreadUsingOutputPin()); + + HRESULT hr = m_Connected->ReceiveConnection(this, pmt); + if(FAILED(hr)) { + return hr; + } + + hr = SetMediaType(pmt); + if(FAILED(hr)) { + return hr; + } + + // Does this pin use the local memory transport? + if(NULL != m_pInputPin) { + // This function assumes that m_pInputPin and m_Connected are + // two different interfaces to the same object. + ASSERT(::IsEqualObject(m_Connected, m_pInputPin)); + + ALLOCATOR_PROPERTIES apInputPinRequirements; + apInputPinRequirements.cbAlign = 0; + apInputPinRequirements.cbBuffer = 0; + apInputPinRequirements.cbPrefix = 0; + apInputPinRequirements.cBuffers = 0; + + m_pInputPin->GetAllocatorRequirements(&apInputPinRequirements); + + // A zero allignment does not make any sense. + if(0 == apInputPinRequirements.cbAlign) { + apInputPinRequirements.cbAlign = 1; + } + + hr = m_pAllocator->Decommit(); + if(FAILED(hr)) { + return hr; + } + + hr = DecideBufferSize(m_pAllocator, &apInputPinRequirements); + if(FAILED(hr)) { + return hr; + } + + hr = m_pAllocator->Commit(); + if(FAILED(hr)) { + return hr; + } + + hr = m_pInputPin->NotifyAllocator(m_pAllocator, m_bPinUsesReadOnlyAllocator); + if(FAILED(hr)) { + return hr; + } + } + + return S_OK; +} + +// this method has to be called from the thread that is pushing data, +// and it's the caller's responsibility to make sure that the thread +// has no outstand samples because they cannot be delivered after a +// reconnect +// +HRESULT CDynamicOutputPin::DynamicReconnect( const CMediaType* pmt ) +{ + // The caller should call StartUsingOutputPin() before calling this + // method. + ASSERT(StreamingThreadUsingOutputPin()); + + if((m_pGraphConfig == NULL) || (NULL == m_hStopEvent)) { + return E_FAIL; + } + + HRESULT hr = m_pGraphConfig->Reconnect( + this, + NULL, + pmt, + NULL, + m_hStopEvent, + AM_GRAPH_CONFIG_RECONNECT_CACHE_REMOVED_FILTERS ); + + return hr; +} + +HRESULT CDynamicOutputPin::CompleteConnect(IPin *pReceivePin) +{ + HRESULT hr = CBaseOutputPin::CompleteConnect(pReceivePin); + if(SUCCEEDED(hr)) { + if(!IsStopped() && m_pAllocator) { + hr = m_pAllocator->Commit(); + ASSERT(hr != VFW_E_ALREADY_COMMITTED); + } + } + + return hr; +} + +#ifdef DEBUG +void CDynamicOutputPin::AssertValid(void) +{ + // Make sure the object was correctly initialized. + + // This ASSERT only fires if the object failed to initialize + // and the user ignored the constructor's return code (phr). + ASSERT(NULL != m_hUnblockOutputPinEvent); + + // If either of these ASSERTs fire, the user did not correctly call + // SetConfigInfo(). + ASSERT(NULL != m_hStopEvent); + ASSERT(NULL != m_pGraphConfig); + + // Make sure the block state is consistent. + + CAutoLock alBlockStateLock(&m_BlockStateLock); + + // BLOCK_STATE variables only have three legal values: PENDING, BLOCKED and NOT_BLOCKED. + ASSERT((NOT_BLOCKED == m_BlockState) || (PENDING == m_BlockState) || (BLOCKED == m_BlockState)); + + // m_hNotifyCallerPinBlockedEvent is only needed when a block operation cannot complete + // immediately. + ASSERT(((NULL == m_hNotifyCallerPinBlockedEvent) && (PENDING != m_BlockState)) || + ((NULL != m_hNotifyCallerPinBlockedEvent) && (PENDING == m_BlockState)) ); + + // m_dwBlockCallerThreadID should always be 0 if the pin is not blocked and + // the user is not trying to block the pin. + ASSERT((0 == m_dwBlockCallerThreadID) || (NOT_BLOCKED != m_BlockState)); + + // If this ASSERT fires, the streaming thread is using the output pin and the + // output pin is blocked. + ASSERT(((0 != m_dwNumOutstandingOutputPinUsers) && (BLOCKED != m_BlockState)) || + ((0 == m_dwNumOutstandingOutputPinUsers) && (NOT_BLOCKED != m_BlockState)) || + ((0 == m_dwNumOutstandingOutputPinUsers) && (NOT_BLOCKED == m_BlockState)) ); +} +#endif // DEBUG + +HRESULT CDynamicOutputPin::WaitEvent(HANDLE hEvent) +{ + const DWORD EVENT_SIGNALED = WAIT_OBJECT_0; + + DWORD dwReturnValue = ::WaitForSingleObject(hEvent, INFINITE); + + switch( dwReturnValue ) { + case EVENT_SIGNALED: + return S_OK; + + case WAIT_FAILED: + return AmGetLastErrorToHResult(); + + default: + DbgBreak( "An Unexpected case occured in CDynamicOutputPin::WaitEvent()." ); + return E_UNEXPECTED; + } +} + +//===================================================================== +//===================================================================== +// Implements CBaseAllocator +//===================================================================== +//===================================================================== + + +/* Constructor overrides the default settings for the free list to request + that it be alertable (ie the list can be cast to a handle which can be + passed to WaitForSingleObject). Both of the allocator lists also ask for + object locking, the all list matches the object default settings but I + have included them here just so it is obvious what kind of list it is */ + +CBaseAllocator::CBaseAllocator(__in_opt LPCTSTR pName, + __inout_opt LPUNKNOWN pUnk, + __inout HRESULT *phr, + BOOL bEvent, + BOOL fEnableReleaseCallback + ) : + CUnknown(pName, pUnk), + m_lAllocated(0), + m_bChanged(FALSE), + m_bCommitted(FALSE), + m_bDecommitInProgress(FALSE), + m_lSize(0), + m_lCount(0), + m_lAlignment(0), + m_lPrefix(0), + m_hSem(NULL), + m_lWaiting(0), + m_fEnableReleaseCallback(fEnableReleaseCallback), + m_pNotify(NULL) +{ +#ifdef DXMPERF + PERFLOG_CTOR( pName ? pName : L"CBaseAllocator", (IMemAllocator *) this ); +#endif // DXMPERF + + if (bEvent) { + m_hSem = CreateSemaphore(NULL, 0, 0x7FFFFFFF, NULL); + if (m_hSem == NULL) { + *phr = E_OUTOFMEMORY; + return; + } + } +} + +#ifdef UNICODE +CBaseAllocator::CBaseAllocator(__in_opt LPCSTR pName, + __inout_opt LPUNKNOWN pUnk, + __inout HRESULT *phr, + BOOL bEvent, + BOOL fEnableReleaseCallback) : + CUnknown(pName, pUnk), + m_lAllocated(0), + m_bChanged(FALSE), + m_bCommitted(FALSE), + m_bDecommitInProgress(FALSE), + m_lSize(0), + m_lCount(0), + m_lAlignment(0), + m_lPrefix(0), + m_hSem(NULL), + m_lWaiting(0), + m_fEnableReleaseCallback(fEnableReleaseCallback), + m_pNotify(NULL) +{ +#ifdef DXMPERF + PERFLOG_CTOR( L"CBaseAllocator", (IMemAllocator *) this ); +#endif // DXMPERF + + if (bEvent) { + m_hSem = CreateSemaphore(NULL, 0, 0x7FFFFFFF, NULL); + if (m_hSem == NULL) { + *phr = E_OUTOFMEMORY; + return; + } + } +} +#endif + +/* Destructor */ + +CBaseAllocator::~CBaseAllocator() +{ + // we can't call Decommit here since that would mean a call to a + // pure virtual in destructor. + // We must assume that the derived class has gone into decommit state in + // its destructor. +#ifdef DXMPERF + PERFLOG_DTOR( L"CBaseAllocator", (IMemAllocator *) this ); +#endif // DXMPERF + + ASSERT(!m_bCommitted); + if (m_hSem != NULL) { + EXECUTE_ASSERT(CloseHandle(m_hSem)); + } + if (m_pNotify) { + m_pNotify->Release(); + } +} + + +/* Override this to publicise our interfaces */ + +STDMETHODIMP +CBaseAllocator::NonDelegatingQueryInterface(REFIID riid, __deref_out void **ppv) +{ + /* Do we know about this interface */ + + if (riid == IID_IMemAllocator || + riid == IID_IMemAllocatorCallbackTemp && m_fEnableReleaseCallback) { + return GetInterface((IMemAllocatorCallbackTemp *) this, ppv); + } else { + return CUnknown::NonDelegatingQueryInterface(riid, ppv); + } +} + + +/* This sets the size and count of the required samples. The memory isn't + actually allocated until Commit() is called, if memory has already been + allocated then assuming no samples are outstanding the user may call us + to change the buffering, the memory will be released in Commit() */ + +STDMETHODIMP +CBaseAllocator::SetProperties( + __in ALLOCATOR_PROPERTIES* pRequest, + __out ALLOCATOR_PROPERTIES* pActual) +{ + CheckPointer(pRequest, E_POINTER); + CheckPointer(pActual, E_POINTER); + ValidateReadWritePtr(pActual, sizeof(ALLOCATOR_PROPERTIES)); + CAutoLock cObjectLock(this); + + ZeroMemory(pActual, sizeof(ALLOCATOR_PROPERTIES)); + + ASSERT(pRequest->cbBuffer > 0); + + /* Check the alignment requested */ + if (pRequest->cbAlign != 1) { + DbgLog((LOG_ERROR, 2, TEXT("Alignment requested was 0x%x, not 1"), + pRequest->cbAlign)); + return VFW_E_BADALIGN; + } + + /* Can't do this if already committed, there is an argument that says we + should not reject the SetProperties call if there are buffers still + active. However this is called by the source filter, which is the same + person who is holding the samples. Therefore it is not unreasonable + for them to free all their samples before changing the requirements */ + + if (m_bCommitted) { + return VFW_E_ALREADY_COMMITTED; + } + + /* Must be no outstanding buffers */ + + if (m_lAllocated != m_lFree.GetCount()) { + return VFW_E_BUFFERS_OUTSTANDING; + } + + /* There isn't any real need to check the parameters as they + will just be rejected when the user finally calls Commit */ + + pActual->cbBuffer = m_lSize = pRequest->cbBuffer; + pActual->cBuffers = m_lCount = pRequest->cBuffers; + pActual->cbAlign = m_lAlignment = pRequest->cbAlign; + pActual->cbPrefix = m_lPrefix = pRequest->cbPrefix; + + m_bChanged = TRUE; + return NOERROR; +} + +STDMETHODIMP +CBaseAllocator::GetProperties( + __out ALLOCATOR_PROPERTIES * pActual) +{ + CheckPointer(pActual,E_POINTER); + ValidateReadWritePtr(pActual,sizeof(ALLOCATOR_PROPERTIES)); + + CAutoLock cObjectLock(this); + pActual->cbBuffer = m_lSize; + pActual->cBuffers = m_lCount; + pActual->cbAlign = m_lAlignment; + pActual->cbPrefix = m_lPrefix; + return NOERROR; +} + +// get container for a sample. Blocking, synchronous call to get the +// next free buffer (as represented by an IMediaSample interface). +// on return, the time etc properties will be invalid, but the buffer +// pointer and size will be correct. + +HRESULT CBaseAllocator::GetBuffer(__deref_out IMediaSample **ppBuffer, + __in_opt REFERENCE_TIME *pStartTime, + __in_opt REFERENCE_TIME *pEndTime, + DWORD dwFlags + ) +{ + UNREFERENCED_PARAMETER(pStartTime); + UNREFERENCED_PARAMETER(pEndTime); + UNREFERENCED_PARAMETER(dwFlags); + CMediaSample *pSample; + + *ppBuffer = NULL; + for (;;) + { + { // scope for lock + CAutoLock cObjectLock(this); + + /* Check we are committed */ + if (!m_bCommitted) { + return VFW_E_NOT_COMMITTED; + } + pSample = (CMediaSample *) m_lFree.RemoveHead(); + if (pSample == NULL) { + SetWaiting(); + } + } + + /* If we didn't get a sample then wait for the list to signal */ + + if (pSample) { + break; + } + if (dwFlags & AM_GBF_NOWAIT) { + return VFW_E_TIMEOUT; + } + ASSERT(m_hSem != NULL); + WaitForSingleObject(m_hSem, INFINITE); + } + + /* Addref the buffer up to one. On release + back to zero instead of being deleted, it will requeue itself by + calling the ReleaseBuffer member function. NOTE the owner of a + media sample must always be derived from CBaseAllocator */ + + + ASSERT(pSample->m_cRef == 0); + pSample->m_cRef = 1; + *ppBuffer = pSample; + +#ifdef DXMPERF + PERFLOG_GETBUFFER( (IMemAllocator *) this, pSample ); +#endif // DXMPERF + + return NOERROR; +} + + +/* Final release of a CMediaSample will call this */ + +STDMETHODIMP +CBaseAllocator::ReleaseBuffer(IMediaSample * pSample) +{ + CheckPointer(pSample,E_POINTER); + ValidateReadPtr(pSample,sizeof(IMediaSample)); + +#ifdef DXMPERF + PERFLOG_RELBUFFER( (IMemAllocator *) this, pSample ); +#endif // DXMPERF + + + BOOL bRelease = FALSE; + { + CAutoLock cal(this); + + /* Put back on the free list */ + + m_lFree.Add((CMediaSample *)pSample); + if (m_lWaiting != 0) { + NotifySample(); + } + + // if there is a pending Decommit, then we need to complete it by + // calling Free() when the last buffer is placed on the free list + + LONG l1 = m_lFree.GetCount(); + if (m_bDecommitInProgress && (l1 == m_lAllocated)) { + Free(); + m_bDecommitInProgress = FALSE; + bRelease = TRUE; + } + } + + if (m_pNotify) { + + ASSERT(m_fEnableReleaseCallback); + + // + // Note that this is not synchronized with setting up a notification + // method. + // + m_pNotify->NotifyRelease(); + } + + /* For each buffer there is one AddRef, made in GetBuffer and released + here. This may cause the allocator and all samples to be deleted */ + + if (bRelease) { + Release(); + } + return NOERROR; +} + +STDMETHODIMP +CBaseAllocator::SetNotify( + IMemAllocatorNotifyCallbackTemp* pNotify + ) +{ + ASSERT(m_fEnableReleaseCallback); + CAutoLock lck(this); + if (pNotify) { + pNotify->AddRef(); + } + if (m_pNotify) { + m_pNotify->Release(); + } + m_pNotify = pNotify; + return S_OK; +} + +STDMETHODIMP +CBaseAllocator::GetFreeCount( + __out LONG* plBuffersFree + ) +{ + ASSERT(m_fEnableReleaseCallback); + CAutoLock cObjectLock(this); + *plBuffersFree = m_lCount - m_lAllocated + m_lFree.GetCount(); + return NOERROR; +} + +void +CBaseAllocator::NotifySample() +{ + if (m_lWaiting != 0) { + ASSERT(m_hSem != NULL); + ReleaseSemaphore(m_hSem, m_lWaiting, 0); + m_lWaiting = 0; + } +} + +STDMETHODIMP +CBaseAllocator::Commit() +{ + /* Check we are not decommitted */ + CAutoLock cObjectLock(this); + + // cannot need to alloc or re-alloc if we are committed + if (m_bCommitted) { + return NOERROR; + } + + /* Allow GetBuffer calls */ + + m_bCommitted = TRUE; + + // is there a pending decommit ? if so, just cancel it + if (m_bDecommitInProgress) { + m_bDecommitInProgress = FALSE; + + // don't call Alloc at this point. He cannot allow SetProperties + // between Decommit and the last free, so the buffer size cannot have + // changed. And because some of the buffers are not free yet, he + // cannot re-alloc anyway. + return NOERROR; + } + + DbgLog((LOG_MEMORY, 1, TEXT("Allocating: %ldx%ld"), m_lCount, m_lSize)); + + // actually need to allocate the samples + HRESULT hr = Alloc(); + if (FAILED(hr)) { + m_bCommitted = FALSE; + return hr; + } + AddRef(); + return NOERROR; +} + + +STDMETHODIMP +CBaseAllocator::Decommit() +{ + BOOL bRelease = FALSE; + { + /* Check we are not already decommitted */ + CAutoLock cObjectLock(this); + if (m_bCommitted == FALSE) { + if (m_bDecommitInProgress == FALSE) { + return NOERROR; + } + } + + /* No more GetBuffer calls will succeed */ + m_bCommitted = FALSE; + + // are any buffers outstanding? + if (m_lFree.GetCount() < m_lAllocated) { + // please complete the decommit when last buffer is freed + m_bDecommitInProgress = TRUE; + } else { + m_bDecommitInProgress = FALSE; + + // need to complete the decommit here as there are no + // outstanding buffers + + Free(); + bRelease = TRUE; + } + + // Tell anyone waiting that they can go now so we can + // reject their call +#pragma warning(push) +#ifndef _PREFAST_ +#pragma warning(disable:4068) +#endif +#pragma prefast(suppress:__WARNING_DEREF_NULL_PTR, "Suppress warning related to Free() invalidating 'this' which is no applicable to CBaseAllocator::Free()") + NotifySample(); + +#pragma warning(pop) + } + + if (bRelease) { + Release(); + } + return NOERROR; +} + + +/* Base definition of allocation which checks we are ok to go ahead and do + the full allocation. We return S_FALSE if the requirements are the same */ + +HRESULT +CBaseAllocator::Alloc(void) +{ + /* Error if he hasn't set the size yet */ + if (m_lCount <= 0 || m_lSize <= 0 || m_lAlignment <= 0) { + return VFW_E_SIZENOTSET; + } + + /* should never get here while buffers outstanding */ + ASSERT(m_lFree.GetCount() == m_lAllocated); + + /* If the requirements haven't changed then don't reallocate */ + if (m_bChanged == FALSE) { + return S_FALSE; + } + + return NOERROR; +} + +/* Implement CBaseAllocator::CSampleList::Remove(pSample) + Removes pSample from the list +*/ +void +CBaseAllocator::CSampleList::Remove(__inout CMediaSample * pSample) +{ + CMediaSample **pSearch; + for (pSearch = &m_List; + *pSearch != NULL; + pSearch = &(CBaseAllocator::NextSample(*pSearch))) { + if (*pSearch == pSample) { + *pSearch = CBaseAllocator::NextSample(pSample); + CBaseAllocator::NextSample(pSample) = NULL; + m_nOnList--; + return; + } + } + DbgBreak("Couldn't find sample in list"); +} + +//===================================================================== +//===================================================================== +// Implements CMemAllocator +//===================================================================== +//===================================================================== + + +/* This goes in the factory template table to create new instances */ +CUnknown *CMemAllocator::CreateInstance(__inout_opt LPUNKNOWN pUnk, __inout HRESULT *phr) +{ + CUnknown *pUnkRet = new CMemAllocator(NAME("CMemAllocator"), pUnk, phr); + return pUnkRet; +} + +CMemAllocator::CMemAllocator( + __in_opt LPCTSTR pName, + __inout_opt LPUNKNOWN pUnk, + __inout HRESULT *phr) + : CBaseAllocator(pName, pUnk, phr, TRUE, TRUE), + m_pBuffer(NULL) +{ +} + +#ifdef UNICODE +CMemAllocator::CMemAllocator( + __in_opt LPCSTR pName, + __inout_opt LPUNKNOWN pUnk, + __inout HRESULT *phr) + : CBaseAllocator(pName, pUnk, phr, TRUE, TRUE), + m_pBuffer(NULL) +{ +} +#endif + +/* This sets the size and count of the required samples. The memory isn't + actually allocated until Commit() is called, if memory has already been + allocated then assuming no samples are outstanding the user may call us + to change the buffering, the memory will be released in Commit() */ +STDMETHODIMP +CMemAllocator::SetProperties( + __in ALLOCATOR_PROPERTIES* pRequest, + __out ALLOCATOR_PROPERTIES* pActual) +{ + CheckPointer(pActual,E_POINTER); + ValidateReadWritePtr(pActual,sizeof(ALLOCATOR_PROPERTIES)); + CAutoLock cObjectLock(this); + + ZeroMemory(pActual, sizeof(ALLOCATOR_PROPERTIES)); + + ASSERT(pRequest->cbBuffer > 0); + + SYSTEM_INFO SysInfo; + GetSystemInfo(&SysInfo); + + /* Check the alignment request is a power of 2 */ + if ((-pRequest->cbAlign & pRequest->cbAlign) != pRequest->cbAlign) { + DbgLog((LOG_ERROR, 1, TEXT("Alignment requested 0x%x not a power of 2!"), + pRequest->cbAlign)); + } + /* Check the alignment requested */ + if (pRequest->cbAlign == 0 || + (SysInfo.dwAllocationGranularity & (pRequest->cbAlign - 1)) != 0) { + DbgLog((LOG_ERROR, 1, TEXT("Invalid alignment 0x%x requested - granularity = 0x%x"), + pRequest->cbAlign, SysInfo.dwAllocationGranularity)); + return VFW_E_BADALIGN; + } + + /* Can't do this if already committed, there is an argument that says we + should not reject the SetProperties call if there are buffers still + active. However this is called by the source filter, which is the same + person who is holding the samples. Therefore it is not unreasonable + for them to free all their samples before changing the requirements */ + + if (m_bCommitted == TRUE) { + return VFW_E_ALREADY_COMMITTED; + } + + /* Must be no outstanding buffers */ + + if (m_lFree.GetCount() < m_lAllocated) { + return VFW_E_BUFFERS_OUTSTANDING; + } + + /* There isn't any real need to check the parameters as they + will just be rejected when the user finally calls Commit */ + + // round length up to alignment - remember that prefix is included in + // the alignment + LONG lSize = pRequest->cbBuffer + pRequest->cbPrefix; + LONG lRemainder = lSize % pRequest->cbAlign; + if (lRemainder != 0) { + lSize = lSize - lRemainder + pRequest->cbAlign; + } + pActual->cbBuffer = m_lSize = (lSize - pRequest->cbPrefix); + + pActual->cBuffers = m_lCount = pRequest->cBuffers; + pActual->cbAlign = m_lAlignment = pRequest->cbAlign; + pActual->cbPrefix = m_lPrefix = pRequest->cbPrefix; + + m_bChanged = TRUE; + return NOERROR; +} + +// override this to allocate our resources when Commit is called. +// +// note that our resources may be already allocated when this is called, +// since we don't free them on Decommit. We will only be called when in +// decommit state with all buffers free. +// +// object locked by caller +HRESULT +CMemAllocator::Alloc(void) +{ + CAutoLock lck(this); + + /* Check he has called SetProperties */ + HRESULT hr = CBaseAllocator::Alloc(); + if (FAILED(hr)) { + return hr; + } + + /* If the requirements haven't changed then don't reallocate */ + if (hr == S_FALSE) { + ASSERT(m_pBuffer); + return NOERROR; + } + ASSERT(hr == S_OK); // we use this fact in the loop below + + /* Free the old resources */ + if (m_pBuffer) { + ReallyFree(); + } + + /* Make sure we've got reasonable values */ + if ( m_lSize < 0 || m_lPrefix < 0 || m_lCount < 0 ) { + return E_OUTOFMEMORY; + } + + /* Compute the aligned size */ + LONG lAlignedSize = m_lSize + m_lPrefix; + + /* Check overflow */ + if (lAlignedSize < m_lSize) { + return E_OUTOFMEMORY; + } + + if (m_lAlignment > 1) { + LONG lRemainder = lAlignedSize % m_lAlignment; + if (lRemainder != 0) { + LONG lNewSize = lAlignedSize + m_lAlignment - lRemainder; + if (lNewSize < lAlignedSize) { + return E_OUTOFMEMORY; + } + lAlignedSize = lNewSize; + } + } + + /* Create the contiguous memory block for the samples + making sure it's properly aligned (64K should be enough!) + */ + ASSERT(lAlignedSize % m_lAlignment == 0); + + LONGLONG lToAllocate = m_lCount * (LONGLONG)lAlignedSize; + + /* Check overflow */ + if (lToAllocate > MAXLONG) { + return E_OUTOFMEMORY; + } + + m_pBuffer = (PBYTE)VirtualAlloc(NULL, + (LONG)lToAllocate, + MEM_COMMIT, + PAGE_READWRITE); + + if (m_pBuffer == NULL) { + return E_OUTOFMEMORY; + } + + LPBYTE pNext = m_pBuffer; + CMediaSample *pSample; + + ASSERT(m_lAllocated == 0); + + // Create the new samples - we have allocated m_lSize bytes for each sample + // plus m_lPrefix bytes per sample as a prefix. We set the pointer to + // the memory after the prefix - so that GetPointer() will return a pointer + // to m_lSize bytes. + for (; m_lAllocated < m_lCount; m_lAllocated++, pNext += lAlignedSize) { + + + pSample = new CMediaSample( + NAME("Default memory media sample"), + this, + &hr, + pNext + m_lPrefix, // GetPointer() value + m_lSize); // not including prefix + + ASSERT(SUCCEEDED(hr)); + if (pSample == NULL) { + return E_OUTOFMEMORY; + } + + // This CANNOT fail + m_lFree.Add(pSample); + } + + m_bChanged = FALSE; + return NOERROR; +} + + +// override this to free up any resources we have allocated. +// called from the base class on Decommit when all buffers have been +// returned to the free list. +// +// caller has already locked the object. + +// in our case, we keep the memory until we are deleted, so +// we do nothing here. The memory is deleted in the destructor by +// calling ReallyFree() +void +CMemAllocator::Free(void) +{ + return; +} + + +// called from the destructor (and from Alloc if changing size/count) to +// actually free up the memory +void +CMemAllocator::ReallyFree(void) +{ + /* Should never be deleting this unless all buffers are freed */ + + ASSERT(m_lAllocated == m_lFree.GetCount()); + + /* Free up all the CMediaSamples */ + + CMediaSample *pSample; + for (;;) { + pSample = m_lFree.RemoveHead(); + if (pSample != NULL) { + delete pSample; + } else { + break; + } + } + + m_lAllocated = 0; + + // free the block of buffer memory + if (m_pBuffer) { + EXECUTE_ASSERT(VirtualFree(m_pBuffer, 0, MEM_RELEASE)); + m_pBuffer = NULL; + } +} + + +/* Destructor frees our memory resources */ + +CMemAllocator::~CMemAllocator() +{ + Decommit(); + ReallyFree(); +} + +// ------------------------------------------------------------------------ +// filter registration through IFilterMapper. used if IFilterMapper is +// not found (Quartz 1.0 install) + +STDAPI +AMovieSetupRegisterFilter( const AMOVIESETUP_FILTER * const psetupdata + , IFilterMapper * pIFM + , BOOL bRegister ) +{ + DbgLog((LOG_TRACE, 3, TEXT("= AMovieSetupRegisterFilter"))); + + // check we've got data + // + if( NULL == psetupdata ) return S_FALSE; + + + // unregister filter + // (as pins are subkeys of filter's CLSID key + // they do not need to be removed separately). + // + DbgLog((LOG_TRACE, 3, TEXT("= = unregister filter"))); + HRESULT hr = pIFM->UnregisterFilter( *(psetupdata->clsID) ); + + + if( bRegister ) + { + // register filter + // + DbgLog((LOG_TRACE, 3, TEXT("= = register filter"))); + hr = pIFM->RegisterFilter( *(psetupdata->clsID) + , psetupdata->strName + , psetupdata->dwMerit ); + if( SUCCEEDED(hr) ) + { + // all its pins + // + DbgLog((LOG_TRACE, 3, TEXT("= = register filter pins"))); + for( UINT m1=0; m1 < psetupdata->nPins; m1++ ) + { + hr = pIFM->RegisterPin( *(psetupdata->clsID) + , psetupdata->lpPin[m1].strName + , psetupdata->lpPin[m1].bRendered + , psetupdata->lpPin[m1].bOutput + , psetupdata->lpPin[m1].bZero + , psetupdata->lpPin[m1].bMany + , *(psetupdata->lpPin[m1].clsConnectsToFilter) + , psetupdata->lpPin[m1].strConnectsToPin ); + + if( SUCCEEDED(hr) ) + { + // and each pin's media types + // + DbgLog((LOG_TRACE, 3, TEXT("= = register filter pin types"))); + for( UINT m2=0; m2 < psetupdata->lpPin[m1].nMediaTypes; m2++ ) + { + hr = pIFM->RegisterPinType( *(psetupdata->clsID) + , psetupdata->lpPin[m1].strName + , *(psetupdata->lpPin[m1].lpMediaType[m2].clsMajorType) + , *(psetupdata->lpPin[m1].lpMediaType[m2].clsMinorType) ); + if( FAILED(hr) ) break; + } + if( FAILED(hr) ) break; + } + if( FAILED(hr) ) break; + } + } + } + + // handle one acceptable "error" - that + // of filter not being registered! + // (couldn't find a suitable #define'd + // name for the error!) + // + if( 0x80070002 == hr) + return NOERROR; + else + return hr; +} + +// Remove warnings about unreferenced inline functions +#pragma warning(disable:4514) + +//------------------------------------------------------------------------------ +// File: Source.cpp +// +// Desc: DirectShow base classes - implements CSource, which is a Quartz +// source filter 'template.' +// +// Copyright (c) 1992-2001 Microsoft Corporation. All rights reserved. +//------------------------------------------------------------------------------ + +// Locking Strategy. +// +// Hold the filter critical section (m_pFilter->pStateLock()) to serialise +// access to functions. Note that, in general, this lock may be held +// by a function when the worker thread may want to hold it. Therefore +// if you wish to access shared state from the worker thread you will +// need to add another critical section object. The execption is during +// the threads processing loop, when it is safe to get the filter critical +// section from within FillBuffer(). + +// +// CSource::Constructor +// +// Initialise the pin count for the filter. The user will create the pins in +// the derived class. +CSource::CSource(__in_opt LPCTSTR pName, __inout_opt LPUNKNOWN lpunk, CLSID clsid) + : CBaseFilter(pName, lpunk, &m_cStateLock, clsid), + m_iPins(0), + m_paStreams(NULL) +{ +} + +CSource::CSource(__in_opt LPCTSTR pName, __inout_opt LPUNKNOWN lpunk, CLSID clsid, __inout HRESULT *phr) + : CBaseFilter(pName, lpunk, &m_cStateLock, clsid), + m_iPins(0), + m_paStreams(NULL) +{ + UNREFERENCED_PARAMETER(phr); +} + +#ifdef UNICODE +CSource::CSource(__in_opt LPCSTR pName, __inout_opt LPUNKNOWN lpunk, CLSID clsid) + : CBaseFilter(pName, lpunk, &m_cStateLock, clsid), + m_iPins(0), + m_paStreams(NULL) +{ +} + +CSource::CSource(__in_opt LPCSTR pName, __inout_opt LPUNKNOWN lpunk, CLSID clsid, __inout HRESULT *phr) + : CBaseFilter(pName, lpunk, &m_cStateLock, clsid), + m_iPins(0), + m_paStreams(NULL) +{ + UNREFERENCED_PARAMETER(phr); +} +#endif + +// +// CSource::Destructor +// +CSource::~CSource() +{ + /* Free our pins and pin array */ + while (m_iPins != 0) { + // deleting the pins causes them to be removed from the array... + delete m_paStreams[m_iPins - 1]; + } + + ASSERT(m_paStreams == NULL); +} + + +// +// Add a new pin +// +HRESULT CSource::AddPin(__in CSourceStream *pStream) +{ + CAutoLock lock(&m_cStateLock); + + /* Allocate space for this pin and the old ones */ + CSourceStream **paStreams = new CSourceStream *[m_iPins + 1]; + if (paStreams == NULL) { + return E_OUTOFMEMORY; + } + if (m_paStreams != NULL) { + CopyMemory((PVOID)paStreams, (PVOID)m_paStreams, + m_iPins * sizeof(m_paStreams[0])); + paStreams[m_iPins] = pStream; + delete [] m_paStreams; + } + m_paStreams = paStreams; + m_paStreams[m_iPins] = pStream; + m_iPins++; + return S_OK; +} + +// +// Remove a pin - pStream is NOT deleted +// +HRESULT CSource::RemovePin(__in CSourceStream *pStream) +{ + int i; + for (i = 0; i < m_iPins; i++) { + if (m_paStreams[i] == pStream) { + if (m_iPins == 1) { + delete [] m_paStreams; + m_paStreams = NULL; + } else { + /* no need to reallocate */ + while (++i < m_iPins) + m_paStreams[i - 1] = m_paStreams[i]; + } + m_iPins--; + return S_OK; + } + } + return S_FALSE; +} + +// +// FindPin +// +// Set *ppPin to the IPin* that has the id Id. +// or to NULL if the Id cannot be matched. +STDMETHODIMP CSource::FindPin(LPCWSTR Id, __deref_out IPin **ppPin) +{ + CheckPointer(ppPin,E_POINTER); + ValidateReadWritePtr(ppPin,sizeof(IPin *)); + // The -1 undoes the +1 in QueryId and ensures that totally invalid + // strings (for which WstrToInt delivers 0) give a deliver a NULL pin. + int i = WstrToInt(Id) -1; + *ppPin = GetPin(i); + if (*ppPin!=NULL){ + (*ppPin)->AddRef(); + return NOERROR; + } else { + return VFW_E_NOT_FOUND; + } +} + +// +// FindPinNumber +// +// return the number of the pin with this IPin* or -1 if none +int CSource::FindPinNumber(__in IPin *iPin) { + int i; + for (i=0; in && n>=0 it follows that m_iPins>0 + // which is what used to be checked (i.e. checking that we have a pin) + if ((n >= 0) && (n < m_iPins)) { + + ASSERT(m_paStreams[n]); + return m_paStreams[n]; + } + return NULL; +} + + +// + + +// * +// * --- CSourceStream ---- +// * + +// +// Set Id to point to a CoTaskMemAlloc'd +STDMETHODIMP CSourceStream::QueryId(__deref_out LPWSTR *Id) { + CheckPointer(Id,E_POINTER); + ValidateReadWritePtr(Id,sizeof(LPWSTR)); + + // We give the pins id's which are 1,2,... + // FindPinNumber returns -1 for an invalid pin + int i = 1+ m_pFilter->FindPinNumber(this); + if (i<1) return VFW_E_NOT_FOUND; + *Id = (LPWSTR)CoTaskMemAlloc(sizeof(WCHAR) * 12); + if (*Id==NULL) { + return E_OUTOFMEMORY; + } + IntToWstr(i, *Id); + return NOERROR; +} + + + +// +// CSourceStream::Constructor +// +// increments the number of pins present on the filter +CSourceStream::CSourceStream( + __in_opt LPCTSTR pObjectName, + __inout HRESULT *phr, + __inout CSource *ps, + __in_opt LPCWSTR pPinName) + : CBaseOutputPin(pObjectName, ps, ps->pStateLock(), phr, pPinName), + m_pFilter(ps) { + + *phr = m_pFilter->AddPin(this); +} + +#ifdef UNICODE +CSourceStream::CSourceStream( + __in_opt LPCSTR pObjectName, + __inout HRESULT *phr, + __inout CSource *ps, + __in_opt LPCWSTR pPinName) + : CBaseOutputPin(pObjectName, ps, ps->pStateLock(), phr, pPinName), + m_pFilter(ps) { + + *phr = m_pFilter->AddPin(this); +} +#endif +// +// CSourceStream::Destructor +// +// Decrements the number of pins on this filter +CSourceStream::~CSourceStream(void) { + + m_pFilter->RemovePin(this); +} + + +// +// CheckMediaType +// +// Do we support this type? Provides the default support for 1 type. +HRESULT CSourceStream::CheckMediaType(const CMediaType *pMediaType) { + + CAutoLock lock(m_pFilter->pStateLock()); + + CMediaType mt; + GetMediaType(&mt); + + if (mt == *pMediaType) { + return NOERROR; + } + + return E_FAIL; +} + + +// +// GetMediaType/3 +// +// By default we support only one type +// iPosition indexes are 0-n +HRESULT CSourceStream::GetMediaType(int iPosition, __inout CMediaType *pMediaType) { + + CAutoLock lock(m_pFilter->pStateLock()); + + if (iPosition<0) { + return E_INVALIDARG; + } + if (iPosition>0) { + return VFW_S_NO_MORE_ITEMS; + } + return GetMediaType(pMediaType); +} + + +// +// Active +// +// The pin is active - start up the worker thread +HRESULT CSourceStream::Active(void) { + + CAutoLock lock(m_pFilter->pStateLock()); + + HRESULT hr; + + if (m_pFilter->IsActive()) { + return S_FALSE; // succeeded, but did not allocate resources (they already exist...) + } + + // do nothing if not connected - its ok not to connect to + // all pins of a source filter + if (!IsConnected()) { + return NOERROR; + } + + hr = CBaseOutputPin::Active(); + if (FAILED(hr)) { + return hr; + } + + ASSERT(!ThreadExists()); + + // start the thread + if (!Create()) { + return E_FAIL; + } + + // Tell thread to initialize. If OnThreadCreate Fails, so does this. + hr = Init(); + if (FAILED(hr)) + return hr; + + return Pause(); +} + + +// +// Inactive +// +// Pin is inactive - shut down the worker thread +// Waits for the worker to exit before returning. +HRESULT CSourceStream::Inactive(void) { + + CAutoLock lock(m_pFilter->pStateLock()); + + HRESULT hr; + + // do nothing if not connected - its ok not to connect to + // all pins of a source filter + if (!IsConnected()) { + return NOERROR; + } + + // !!! need to do this before trying to stop the thread, because + // we may be stuck waiting for our own allocator!!! + + hr = CBaseOutputPin::Inactive(); // call this first to Decommit the allocator + if (FAILED(hr)) { + return hr; + } + + if (ThreadExists()) { + hr = Stop(); + + if (FAILED(hr)) { + return hr; + } + + hr = Exit(); + if (FAILED(hr)) { + return hr; + } + + Close(); // Wait for the thread to exit, then tidy up. + } + + // hr = CBaseOutputPin::Inactive(); // call this first to Decommit the allocator + //if (FAILED(hr)) { + // return hr; + //} + + return NOERROR; +} + + +// +// ThreadProc +// +// When this returns the thread exits +// Return codes > 0 indicate an error occured +DWORD CSourceStream::ThreadProc(void) { + + HRESULT hr; // the return code from calls + Command com; + + do { + com = GetRequest(); + if (com != CMD_INIT) { + DbgLog((LOG_ERROR, 1, TEXT("Thread expected init command"))); + Reply((DWORD) E_UNEXPECTED); + } + } while (com != CMD_INIT); + + DbgLog((LOG_TRACE, 1, TEXT("CSourceStream worker thread initializing"))); + + hr = OnThreadCreate(); // perform set up tasks + if (FAILED(hr)) { + DbgLog((LOG_ERROR, 1, TEXT("CSourceStream::OnThreadCreate failed. Aborting thread."))); + OnThreadDestroy(); + Reply(hr); // send failed return code from OnThreadCreate + return 1; + } + + // Initialisation suceeded + Reply(NOERROR); + + Command cmd; + do { + cmd = GetRequest(); + + switch (cmd) { + + case CMD_EXIT: + Reply(NOERROR); + break; + + case CMD_RUN: + DbgLog((LOG_ERROR, 1, TEXT("CMD_RUN received before a CMD_PAUSE???"))); + // !!! fall through??? + + case CMD_PAUSE: + Reply(NOERROR); + DoBufferProcessingLoop(); + break; + + case CMD_STOP: + Reply(NOERROR); + break; + + default: + DbgLog((LOG_ERROR, 1, TEXT("Unknown command %d received!"), cmd)); + Reply((DWORD) E_NOTIMPL); + break; + } + } while (cmd != CMD_EXIT); + + hr = OnThreadDestroy(); // tidy up. + if (FAILED(hr)) { + DbgLog((LOG_ERROR, 1, TEXT("CSourceStream::OnThreadDestroy failed. Exiting thread."))); + return 1; + } + + DbgLog((LOG_TRACE, 1, TEXT("CSourceStream worker thread exiting"))); + return 0; +} + + +// +// DoBufferProcessingLoop +// +// Grabs a buffer and calls the users processing function. +// Overridable, so that different delivery styles can be catered for. +HRESULT CSourceStream::DoBufferProcessingLoop(void) { + + Command com; + + OnThreadStartPlay(); + + do { + while (!CheckRequest(&com)) { + + IMediaSample *pSample; + + HRESULT hr = GetDeliveryBuffer(&pSample,NULL,NULL,0); + if (FAILED(hr)) { + Sleep(1); + continue; // go round again. Perhaps the error will go away + // or the allocator is decommited & we will be asked to + // exit soon. + } + + // Virtual function user will override. + hr = FillBuffer(pSample); + + if (hr == S_OK) { + hr = Deliver(pSample); + pSample->Release(); + + // downstream filter returns S_FALSE if it wants us to + // stop or an error if it's reporting an error. + if(hr != S_OK) + { + DbgLog((LOG_TRACE, 2, TEXT("Deliver() returned %08x; stopping"), hr)); + return S_OK; + } + + } else if (hr == S_FALSE) { + // derived class wants us to stop pushing data + pSample->Release(); + DeliverEndOfStream(); + return S_OK; + } else { + // derived class encountered an error + pSample->Release(); + DbgLog((LOG_ERROR, 1, TEXT("Error %08lX from FillBuffer!!!"), hr)); + DeliverEndOfStream(); + m_pFilter->NotifyEvent(EC_ERRORABORT, hr, 0); + return hr; + } + + // all paths release the sample + } + + // For all commands sent to us there must be a Reply call! + + if (com == CMD_RUN || com == CMD_PAUSE) { + Reply(NOERROR); + } else if (com != CMD_STOP) { + Reply((DWORD) E_UNEXPECTED); + DbgLog((LOG_ERROR, 1, TEXT("Unexpected command!!!"))); + } + } while (com != CMD_STOP); + + return S_FALSE; +} + +//------------------------------------------------------------------------------ +// File: CProp.cpp +// +// Desc: DirectShow base classes - implements CBasePropertyPage class. +// +// Copyright (c) 1992-2001 Microsoft Corporation. All rights reserved. +//------------------------------------------------------------------------------ + +// Constructor for the base property page class. As described in the header +// file we must be initialised with dialog and title resource identifiers. +// The class supports IPropertyPage and overrides AddRef and Release calls +// to keep track of the reference counts. When the last count is released +// we call SetPageSite(NULL) and SetObjects(0,NULL) to release interfaces +// previously obtained by the property page when it had SetObjects called + +CBasePropertyPage::CBasePropertyPage(__in_opt LPCTSTR pName, // Debug only name + __inout_opt LPUNKNOWN pUnk, // COM Delegator + int DialogId, // Resource ID + int TitleId) : // To get tital + CUnknown(pName,pUnk), + m_DialogId(DialogId), + m_TitleId(TitleId), + m_hwnd(NULL), + m_Dlg(NULL), + m_pPageSite(NULL), + m_bObjectSet(FALSE), + m_bDirty(FALSE) +{ +} + +#ifdef UNICODE +CBasePropertyPage::CBasePropertyPage(__in_opt LPCSTR pName, // Debug only name + __inout_opt LPUNKNOWN pUnk, // COM Delegator + int DialogId, // Resource ID + int TitleId) : // To get tital + CUnknown(pName,pUnk), + m_DialogId(DialogId), + m_TitleId(TitleId), + m_hwnd(NULL), + m_Dlg(NULL), + m_pPageSite(NULL), + m_bObjectSet(FALSE), + m_bDirty(FALSE) +{ +} +#endif + +// Increment our reference count + +STDMETHODIMP_(ULONG) CBasePropertyPage::NonDelegatingAddRef() +{ + LONG lRef = InterlockedIncrement(&m_cRef); + ASSERT(lRef > 0); + return max(ULONG(m_cRef),1ul); +} + + +// Release a reference count and protect against reentrancy + +STDMETHODIMP_(ULONG) CBasePropertyPage::NonDelegatingRelease() +{ + // If the reference count drops to zero delete ourselves + + LONG lRef = InterlockedDecrement(&m_cRef); + if (lRef == 0) { + m_cRef++; + SetPageSite(NULL); + SetObjects(0,NULL); + delete this; + return ULONG(0); + } else { + // Don't touch m_cRef again here! + return max(ULONG(lRef),1ul); + } +} + + +// Expose our IPropertyPage interface + +STDMETHODIMP +CBasePropertyPage::NonDelegatingQueryInterface(REFIID riid,__deref_out void **ppv) +{ + if (riid == IID_IPropertyPage) { + return GetInterface((IPropertyPage *)this,ppv); + } else { + return CUnknown::NonDelegatingQueryInterface(riid,ppv); + } +} + + +// Get the page info so that the page site can size itself + +STDMETHODIMP CBasePropertyPage::GetPageInfo(__out LPPROPPAGEINFO pPageInfo) +{ + CheckPointer(pPageInfo,E_POINTER); + WCHAR wszTitle[STR_MAX_LENGTH]; + WideStringFromResource(wszTitle,m_TitleId); + + // Allocate dynamic memory for the property page title + + LPOLESTR pszTitle; + HRESULT hr = AMGetWideString(wszTitle, &pszTitle); + if (FAILED(hr)) { + NOTE("No caption memory"); + return hr; + } + + pPageInfo->cb = sizeof(PROPPAGEINFO); + pPageInfo->pszTitle = pszTitle; + pPageInfo->pszDocString = NULL; + pPageInfo->pszHelpFile = NULL; + pPageInfo->dwHelpContext = 0; + + // Set defaults in case GetDialogSize fails + pPageInfo->size.cx = 340; + pPageInfo->size.cy = 150; + + GetDialogSize(m_DialogId, DialogProc,0L,&pPageInfo->size); + return NOERROR; +} + + +// Handles the messages for our property window + +INT_PTR CALLBACK CBasePropertyPage::DialogProc(HWND hwnd, + UINT uMsg, + WPARAM wParam, + LPARAM lParam) +{ + CBasePropertyPage *pPropertyPage; + + switch (uMsg) { + + case WM_INITDIALOG: + + _SetWindowLongPtr(hwnd, DWLP_USER, lParam); + + // This pointer may be NULL when calculating size + + pPropertyPage = (CBasePropertyPage *) lParam; + if (pPropertyPage == NULL) { + return (LRESULT) 1; + } + pPropertyPage->m_Dlg = hwnd; + } + + // This pointer may be NULL when calculating size + + pPropertyPage = _GetWindowLongPtr(hwnd, DWLP_USER); + if (pPropertyPage == NULL) { + return (LRESULT) 1; + } + return pPropertyPage->OnReceiveMessage(hwnd,uMsg,wParam,lParam); +} + + +// Tells us the object that should be informed of the property changes + +STDMETHODIMP CBasePropertyPage::SetObjects(ULONG cObjects,__in_ecount_opt(cObjects) LPUNKNOWN *ppUnk) +{ + if (cObjects == 1) { + + if ((ppUnk == NULL) || (*ppUnk == NULL)) { + return E_POINTER; + } + + // Set a flag to say that we have set the Object + m_bObjectSet = TRUE ; + return OnConnect(*ppUnk); + + } else if (cObjects == 0) { + + // Set a flag to say that we have not set the Object for the page + m_bObjectSet = FALSE ; + return OnDisconnect(); + } + + DbgBreak("No support for more than one object"); + return E_UNEXPECTED; +} + + +// Create the window we will use to edit properties + +STDMETHODIMP CBasePropertyPage::Activate(HWND hwndParent, + LPCRECT pRect, + BOOL fModal) +{ + CheckPointer(pRect,E_POINTER); + + // Return failure if SetObject has not been called. + if (m_bObjectSet == FALSE) { + return E_UNEXPECTED; + } + + if (m_hwnd) { + return E_UNEXPECTED; + } + + m_hwnd = CreateDialogParam(g_hInst, + MAKEINTRESOURCE(m_DialogId), + hwndParent, + DialogProc, + (LPARAM) this); + if (m_hwnd == NULL) { + return E_OUTOFMEMORY; + } + + OnActivate(); + Move(pRect); + return Show(SW_SHOWNORMAL); +} + + +// Set the position of the property page + +STDMETHODIMP CBasePropertyPage::Move(LPCRECT pRect) +{ + CheckPointer(pRect,E_POINTER); + + if (m_hwnd == NULL) { + return E_UNEXPECTED; + } + + MoveWindow(m_hwnd, // Property page handle + pRect->left, // x coordinate + pRect->top, // y coordinate + WIDTH(pRect), // Overall window width + HEIGHT(pRect), // And likewise height + TRUE); // Should we repaint it + + return NOERROR; +} + + +// Display the property dialog + +STDMETHODIMP CBasePropertyPage::Show(UINT nCmdShow) +{ + // Have we been activated yet + + if (m_hwnd == NULL) { + return E_UNEXPECTED; + } + + // Ignore wrong show flags + + if ((nCmdShow != SW_SHOW) && (nCmdShow != SW_SHOWNORMAL) && (nCmdShow != SW_HIDE)) { + return E_INVALIDARG; + } + + ShowWindow(m_hwnd,nCmdShow); + InvalidateRect(m_hwnd,NULL,TRUE); + return NOERROR; +} + + +// Destroy the property page dialog + +STDMETHODIMP CBasePropertyPage::Deactivate(void) +{ + if (m_hwnd == NULL) { + return E_UNEXPECTED; + } + + // Remove WS_EX_CONTROLPARENT before DestroyWindow call + + DWORD dwStyle = GetWindowLong(m_hwnd, GWL_EXSTYLE); + dwStyle = dwStyle & (~WS_EX_CONTROLPARENT); + + // Set m_hwnd to be NULL temporarily so the message handler + // for WM_STYLECHANGING doesn't add the WS_EX_CONTROLPARENT + // style back in + HWND hwnd = m_hwnd; + m_hwnd = NULL; + SetWindowLong(hwnd, GWL_EXSTYLE, dwStyle); + m_hwnd = hwnd; + + OnDeactivate(); + + // Destroy the dialog window + + DestroyWindow(m_hwnd); + m_hwnd = NULL; + return NOERROR; +} + + +// Tells the application property page site + +STDMETHODIMP CBasePropertyPage::SetPageSite(__in_opt LPPROPERTYPAGESITE pPageSite) +{ + if (pPageSite) { + + if (m_pPageSite) { + return E_UNEXPECTED; + } + + m_pPageSite = pPageSite; + m_pPageSite->AddRef(); + + } else { + + if (m_pPageSite == NULL) { + return E_UNEXPECTED; + } + + m_pPageSite->Release(); + m_pPageSite = NULL; + } + return NOERROR; +} + + +// Apply any changes so far made + +STDMETHODIMP CBasePropertyPage::Apply() +{ + // In ActiveMovie 1.0 we used to check whether we had been activated or + // not. This is too constrictive. Apply should be allowed as long as + // SetObject was called to set an object. So we will no longer check to + // see if we have been activated (ie., m_hWnd != NULL), but instead + // make sure that m_bObjectSet is TRUE (ie., SetObject has been called). + + if (m_bObjectSet == FALSE) { + return E_UNEXPECTED; + } + + // Must have had a site set + + if (m_pPageSite == NULL) { + return E_UNEXPECTED; + } + + // Has anything changed + + if (m_bDirty == FALSE) { + return NOERROR; + } + + // Commit derived class changes + + HRESULT hr = OnApplyChanges(); + if (SUCCEEDED(hr)) { + m_bDirty = FALSE; + } + return hr; +} + + +// Base class definition for message handling + +INT_PTR CBasePropertyPage::OnReceiveMessage(HWND hwnd,UINT uMsg,WPARAM wParam,LPARAM lParam) +{ + // we would like the TAB key to move around the tab stops in our property + // page, but for some reason OleCreatePropertyFrame clears the CONTROLPARENT + // style behind our back, so we need to switch it back on now behind its + // back. Otherwise the tab key will be useless in every page. + // + + CBasePropertyPage *pPropertyPage; + { + pPropertyPage = _GetWindowLongPtr(hwnd, DWLP_USER); + + if (pPropertyPage->m_hwnd == NULL) { + return 0; + } + switch (uMsg) { + case WM_STYLECHANGING: + if (wParam == GWL_EXSTYLE) { + LPSTYLESTRUCT lpss = (LPSTYLESTRUCT)lParam; + lpss->styleNew |= WS_EX_CONTROLPARENT; + return 0; + } + } + } + + return DefWindowProc(hwnd,uMsg,wParam,lParam); +} + +//------------------------------------------------------------------------------ +// File: DDMM.h +// +// Desc: DirectShow base classes - efines routines for using DirectDraw +// on a multimonitor system. +// +// Copyright (c) 1995-2001 Microsoft Corporation. All rights reserved. +//------------------------------------------------------------------------------ + +#ifdef __cplusplus +extern "C" { /* Assume C declarations for C++ */ +#endif /* __cplusplus */ + +// DDRAW.H might not include these +#ifndef DDENUM_ATTACHEDSECONDARYDEVICES +#define DDENUM_ATTACHEDSECONDARYDEVICES 0x00000001L +#endif + +typedef HRESULT (*PDRAWCREATE)(IID *,LPDIRECTDRAW *,LPUNKNOWN); +typedef HRESULT (*PDRAWENUM)(LPDDENUMCALLBACKA, LPVOID); + +IDirectDraw * DirectDrawCreateFromDevice(__in_opt LPSTR, PDRAWCREATE, PDRAWENUM); +IDirectDraw * DirectDrawCreateFromDeviceEx(__in_opt LPSTR, PDRAWCREATE, LPDIRECTDRAWENUMERATEEXA); + +#ifdef __cplusplus +} +#endif /* __cplusplus */ + +//------------------------------------------------------------------------------ +// File: DDMM.cpp +// +// Desc: DirectShow base classes - implements routines for using DirectDraw +// on a multimonitor system. +// +// Copyright (c) 1995-2001 Microsoft Corporation. All rights reserved. +//------------------------------------------------------------------------------ + +/* + * FindDeviceCallback + */ +typedef struct { + LPSTR szDevice; + GUID* lpGUID; + GUID GUID; + BOOL fFound; +} FindDeviceData; + +BOOL CALLBACK FindDeviceCallback(__in_opt GUID* lpGUID, __in LPSTR szName, __in LPSTR szDevice, __in LPVOID lParam) +{ + FindDeviceData *p = (FindDeviceData*)lParam; + + if (lstrcmpiA(p->szDevice, szDevice) == 0) { + if (lpGUID) { + p->GUID = *lpGUID; + p->lpGUID = &p->GUID; + } else { + p->lpGUID = NULL; + } + p->fFound = TRUE; + return FALSE; + } + return TRUE; +} + + +BOOL CALLBACK FindDeviceCallbackEx(__in_opt GUID* lpGUID, __in LPSTR szName, __in LPSTR szDevice, __in LPVOID lParam, HMONITOR hMonitor) +{ + FindDeviceData *p = (FindDeviceData*)lParam; + + if (lstrcmpiA(p->szDevice, szDevice) == 0) { + if (lpGUID) { + p->GUID = *lpGUID; + p->lpGUID = &p->GUID; + } else { + p->lpGUID = NULL; + } + p->fFound = TRUE; + return FALSE; + } + return TRUE; +} + + +/* + * DirectDrawCreateFromDevice + * + * create a DirectDraw object for a particular device + */ +IDirectDraw * DirectDrawCreateFromDevice(__in_opt LPSTR szDevice, PDRAWCREATE DirectDrawCreateP, PDRAWENUM DirectDrawEnumerateP) +{ + IDirectDraw* pdd = NULL; + FindDeviceData find; + + if (szDevice == NULL) { + DirectDrawCreateP(NULL, &pdd, NULL); + return pdd; + } + + find.szDevice = szDevice; + find.fFound = FALSE; + DirectDrawEnumerateP(FindDeviceCallback, (LPVOID)&find); + + if (find.fFound) + { + // + // In 4bpp mode the following DDraw call causes a message box to be popped + // up by DDraw (!?!). It's DDraw's fault, but we don't like it. So we + // make sure it doesn't happen. + // + UINT ErrorMode = SetErrorMode(SEM_FAILCRITICALERRORS); + DirectDrawCreateP(find.lpGUID, &pdd, NULL); + SetErrorMode(ErrorMode); + } + + return pdd; +} + + +/* + * DirectDrawCreateFromDeviceEx + * + * create a DirectDraw object for a particular device + */ +IDirectDraw * DirectDrawCreateFromDeviceEx(__in_opt LPSTR szDevice, PDRAWCREATE DirectDrawCreateP, LPDIRECTDRAWENUMERATEEXA DirectDrawEnumerateExP) +{ + IDirectDraw* pdd = NULL; + FindDeviceData find; + + if (szDevice == NULL) { + DirectDrawCreateP(NULL, &pdd, NULL); + return pdd; + } + + find.szDevice = szDevice; + find.fFound = FALSE; + DirectDrawEnumerateExP(FindDeviceCallbackEx, (LPVOID)&find, + DDENUM_ATTACHEDSECONDARYDEVICES); + + if (find.fFound) + { + // + // In 4bpp mode the following DDraw call causes a message box to be popped + // up by DDraw (!?!). It's DDraw's fault, but we don't like it. So we + // make sure it doesn't happen. + // + UINT ErrorMode = SetErrorMode(SEM_FAILCRITICALERRORS); + DirectDrawCreateP(find.lpGUID, &pdd, NULL); + SetErrorMode(ErrorMode); + } + + return pdd; +} + +//------------------------------------------------------------------------------ +// File: VideoCtl.cpp +// +// Desc: DirectShow base classes. +// +// Copyright (c) 1992-2001 Microsoft Corporation. All rights reserved. +//------------------------------------------------------------------------------ + +// Load a string from the resource file string table. The buffer must be at +// least STR_MAX_LENGTH bytes. The easiest way to use this is to declare a +// buffer in the property page class and use it for all string loading. It +// cannot be static as multiple property pages may be active simultaneously + +LPTSTR WINAPI StringFromResource(__out_ecount(STR_MAX_LENGTH) LPTSTR pBuffer, int iResourceID) +{ + if (LoadString(g_hInst,iResourceID,pBuffer,STR_MAX_LENGTH) == 0) { + return TEXT(""); + } + return pBuffer; +} + +#ifdef UNICODE +LPSTR WINAPI StringFromResource(__out_ecount(STR_MAX_LENGTH) LPSTR pBuffer, int iResourceID) +{ + if (LoadStringA(g_hInst,iResourceID,pBuffer,STR_MAX_LENGTH) == 0) { + return ""; + } + return pBuffer; +} +#endif + + + +// Property pages typically are called through their OLE interfaces. These +// use UNICODE strings regardless of how the binary is built. So when we +// load strings from the resource file we sometimes want to convert them +// to UNICODE. This method is passed the target UNICODE buffer and does a +// convert after loading the string (if built UNICODE this is not needed) +// On WinNT we can explicitly call LoadStringW which saves two conversions + +#ifndef UNICODE + +LPWSTR WINAPI WideStringFromResource(__out_ecount(STR_MAX_LENGTH) LPWSTR pBuffer, int iResourceID) +{ + *pBuffer = 0; + + if (g_amPlatform == VER_PLATFORM_WIN32_NT) { + LoadStringW(g_hInst,iResourceID,pBuffer,STR_MAX_LENGTH); + } else { + + CHAR szBuffer[STR_MAX_LENGTH]; + DWORD dwStringLength = LoadString(g_hInst,iResourceID,szBuffer,STR_MAX_LENGTH); + // if we loaded a string convert it to wide characters, ensuring + // that we also null terminate the result. + if (dwStringLength++) { + MultiByteToWideChar(CP_ACP,0,szBuffer,dwStringLength,pBuffer,STR_MAX_LENGTH); + } + } + return pBuffer; +} + +#endif + + +// Helper function to calculate the size of the dialog + +BOOL WINAPI GetDialogSize(int iResourceID, + DLGPROC pDlgProc, + LPARAM lParam, + __out SIZE *pResult) +{ + RECT rc; + HWND hwnd; + + // Create a temporary property page + + hwnd = CreateDialogParam(g_hInst, + MAKEINTRESOURCE(iResourceID), + GetDesktopWindow(), + pDlgProc, + lParam); + if (hwnd == NULL) { + return FALSE; + } + + GetWindowRect(hwnd, &rc); + pResult->cx = rc.right - rc.left; + pResult->cy = rc.bottom - rc.top; + + DestroyWindow(hwnd); + return TRUE; +} + + +// Class that aggregates on the IDirectDraw interface. Although DirectDraw +// has the ability in its interfaces to be aggregated they're not currently +// implemented. This makes it difficult for various parts of Quartz that want +// to aggregate these interfaces. In particular the video renderer passes out +// media samples that expose IDirectDraw and IDirectDrawSurface. The filter +// graph manager also exposes IDirectDraw as a plug in distributor. For these +// objects we provide these aggregation classes that republish the interfaces + +STDMETHODIMP CAggDirectDraw::NonDelegatingQueryInterface(REFIID riid, __deref_out void **ppv) +{ + ASSERT(m_pDirectDraw); + + // Do we have this interface + + if (riid == IID_IDirectDraw) { + return GetInterface((IDirectDraw *)this,ppv); + } else { + return CUnknown::NonDelegatingQueryInterface(riid,ppv); + } +} + + +STDMETHODIMP CAggDirectDraw::Compact() +{ + ASSERT(m_pDirectDraw); + return m_pDirectDraw->Compact(); +} + + +STDMETHODIMP CAggDirectDraw::CreateClipper(DWORD dwFlags, __deref_out LPDIRECTDRAWCLIPPER *lplpDDClipper, __inout_opt IUnknown *pUnkOuter) +{ + ASSERT(m_pDirectDraw); + return m_pDirectDraw->CreateClipper(dwFlags,lplpDDClipper,pUnkOuter); +} + + +STDMETHODIMP CAggDirectDraw::CreatePalette(DWORD dwFlags, + __in LPPALETTEENTRY lpColorTable, + __deref_out LPDIRECTDRAWPALETTE *lplpDDPalette, + __inout_opt IUnknown *pUnkOuter) +{ + ASSERT(m_pDirectDraw); + return m_pDirectDraw->CreatePalette(dwFlags,lpColorTable,lplpDDPalette,pUnkOuter); +} + + +STDMETHODIMP CAggDirectDraw::CreateSurface(__in LPDDSURFACEDESC lpDDSurfaceDesc, + __deref_out LPDIRECTDRAWSURFACE *lplpDDSurface, + __inout_opt IUnknown *pUnkOuter) +{ + ASSERT(m_pDirectDraw); + return m_pDirectDraw->CreateSurface(lpDDSurfaceDesc,lplpDDSurface,pUnkOuter); +} + + +STDMETHODIMP CAggDirectDraw::DuplicateSurface(__in LPDIRECTDRAWSURFACE lpDDSurface, + __deref_out LPDIRECTDRAWSURFACE *lplpDupDDSurface) +{ + ASSERT(m_pDirectDraw); + return m_pDirectDraw->DuplicateSurface(lpDDSurface,lplpDupDDSurface); +} + + +STDMETHODIMP CAggDirectDraw::EnumDisplayModes(DWORD dwSurfaceDescCount, + __in LPDDSURFACEDESC lplpDDSurfaceDescList, + __in LPVOID lpContext, + __in LPDDENUMMODESCALLBACK lpEnumCallback) +{ + ASSERT(m_pDirectDraw); + return m_pDirectDraw->EnumDisplayModes(dwSurfaceDescCount,lplpDDSurfaceDescList,lpContext,lpEnumCallback); +} + + +STDMETHODIMP CAggDirectDraw::EnumSurfaces(DWORD dwFlags, + __in LPDDSURFACEDESC lpDDSD, + __in LPVOID lpContext, + __in LPDDENUMSURFACESCALLBACK lpEnumCallback) +{ + ASSERT(m_pDirectDraw); + return m_pDirectDraw->EnumSurfaces(dwFlags,lpDDSD,lpContext,lpEnumCallback); +} + + +STDMETHODIMP CAggDirectDraw::FlipToGDISurface() +{ + ASSERT(m_pDirectDraw); + return m_pDirectDraw->FlipToGDISurface(); +} + + +STDMETHODIMP CAggDirectDraw::GetCaps(__out LPDDCAPS lpDDDriverCaps,__out LPDDCAPS lpDDHELCaps) +{ + ASSERT(m_pDirectDraw); + return m_pDirectDraw->GetCaps(lpDDDriverCaps,lpDDHELCaps); +} + + +STDMETHODIMP CAggDirectDraw::GetDisplayMode(__out LPDDSURFACEDESC lpDDSurfaceDesc) +{ + ASSERT(m_pDirectDraw); + return m_pDirectDraw->GetDisplayMode(lpDDSurfaceDesc); +} + + +STDMETHODIMP CAggDirectDraw::GetFourCCCodes(__inout LPDWORD lpNumCodes,__out_ecount(*lpNumCodes) LPDWORD lpCodes) +{ + ASSERT(m_pDirectDraw); + return m_pDirectDraw->GetFourCCCodes(lpNumCodes,lpCodes); +} + + +STDMETHODIMP CAggDirectDraw::GetGDISurface(__deref_out LPDIRECTDRAWSURFACE *lplpGDIDDSurface) +{ + ASSERT(m_pDirectDraw); + return m_pDirectDraw->GetGDISurface(lplpGDIDDSurface); +} + + +STDMETHODIMP CAggDirectDraw::GetMonitorFrequency(__out LPDWORD lpdwFrequency) +{ + ASSERT(m_pDirectDraw); + return m_pDirectDraw->GetMonitorFrequency(lpdwFrequency); +} + + +STDMETHODIMP CAggDirectDraw::GetScanLine(__out LPDWORD lpdwScanLine) +{ + ASSERT(m_pDirectDraw); + return m_pDirectDraw->GetScanLine(lpdwScanLine); +} + + +STDMETHODIMP CAggDirectDraw::GetVerticalBlankStatus(__out LPBOOL lpblsInVB) +{ + ASSERT(m_pDirectDraw); + return m_pDirectDraw->GetVerticalBlankStatus(lpblsInVB); +} + + +STDMETHODIMP CAggDirectDraw::Initialize(__in GUID *lpGUID) +{ + ASSERT(m_pDirectDraw); + return m_pDirectDraw->Initialize(lpGUID); +} + + +STDMETHODIMP CAggDirectDraw::RestoreDisplayMode() +{ + ASSERT(m_pDirectDraw); + return m_pDirectDraw->RestoreDisplayMode(); +} + + +STDMETHODIMP CAggDirectDraw::SetCooperativeLevel(HWND hWnd,DWORD dwFlags) +{ + ASSERT(m_pDirectDraw); + return m_pDirectDraw->SetCooperativeLevel(hWnd,dwFlags); +} + + +STDMETHODIMP CAggDirectDraw::SetDisplayMode(DWORD dwWidth,DWORD dwHeight,DWORD dwBpp) +{ + ASSERT(m_pDirectDraw); + return m_pDirectDraw->SetDisplayMode(dwWidth,dwHeight,dwBpp); +} + + +STDMETHODIMP CAggDirectDraw::WaitForVerticalBlank(DWORD dwFlags,HANDLE hEvent) +{ + ASSERT(m_pDirectDraw); + return m_pDirectDraw->WaitForVerticalBlank(dwFlags,hEvent); +} + + +// Class that aggregates an IDirectDrawSurface interface. Although DirectDraw +// has the ability in its interfaces to be aggregated they're not currently +// implemented. This makes it difficult for various parts of Quartz that want +// to aggregate these interfaces. In particular the video renderer passes out +// media samples that expose IDirectDraw and IDirectDrawSurface. The filter +// graph manager also exposes IDirectDraw as a plug in distributor. For these +// objects we provide these aggregation classes that republish the interfaces + +STDMETHODIMP CAggDrawSurface::NonDelegatingQueryInterface(REFIID riid, __deref_out void **ppv) +{ + ASSERT(m_pDirectDrawSurface); + + // Do we have this interface + + if (riid == IID_IDirectDrawSurface) { + return GetInterface((IDirectDrawSurface *)this,ppv); + } else { + return CUnknown::NonDelegatingQueryInterface(riid,ppv); + } +} + + +STDMETHODIMP CAggDrawSurface::AddAttachedSurface(__in LPDIRECTDRAWSURFACE lpDDSAttachedSurface) +{ + ASSERT(m_pDirectDrawSurface); + return m_pDirectDrawSurface->AddAttachedSurface(lpDDSAttachedSurface); +} + + +STDMETHODIMP CAggDrawSurface::AddOverlayDirtyRect(__in LPRECT lpRect) +{ + ASSERT(m_pDirectDrawSurface); + return m_pDirectDrawSurface->AddOverlayDirtyRect(lpRect); +} + + +STDMETHODIMP CAggDrawSurface::Blt(__in LPRECT lpDestRect, + __in LPDIRECTDRAWSURFACE lpDDSrcSurface, + __in LPRECT lpSrcRect, + DWORD dwFlags, + __in LPDDBLTFX lpDDBltFx) +{ + ASSERT(m_pDirectDrawSurface); + return m_pDirectDrawSurface->Blt(lpDestRect,lpDDSrcSurface,lpSrcRect,dwFlags,lpDDBltFx); +} + + +STDMETHODIMP CAggDrawSurface::BltBatch(__in_ecount(dwCount) LPDDBLTBATCH lpDDBltBatch,DWORD dwCount,DWORD dwFlags) +{ + ASSERT(m_pDirectDrawSurface); + return m_pDirectDrawSurface->BltBatch(lpDDBltBatch,dwCount,dwFlags); +} + + +STDMETHODIMP CAggDrawSurface::BltFast(DWORD dwX,DWORD dwY, + __in LPDIRECTDRAWSURFACE lpDDSrcSurface, + __in LPRECT lpSrcRect, + DWORD dwTrans) +{ + ASSERT(m_pDirectDrawSurface); + return m_pDirectDrawSurface->BltFast(dwX,dwY,lpDDSrcSurface,lpSrcRect,dwTrans); +} + + +STDMETHODIMP CAggDrawSurface::DeleteAttachedSurface(DWORD dwFlags, + __in LPDIRECTDRAWSURFACE lpDDSAttachedSurface) +{ + ASSERT(m_pDirectDrawSurface); + return m_pDirectDrawSurface->DeleteAttachedSurface(dwFlags,lpDDSAttachedSurface); +} + + +STDMETHODIMP CAggDrawSurface::EnumAttachedSurfaces(__in LPVOID lpContext, + __in LPDDENUMSURFACESCALLBACK lpEnumSurfacesCallback) +{ + ASSERT(m_pDirectDrawSurface); + return m_pDirectDrawSurface->EnumAttachedSurfaces(lpContext,lpEnumSurfacesCallback); +} + + +STDMETHODIMP CAggDrawSurface::EnumOverlayZOrders(DWORD dwFlags, + __in LPVOID lpContext, + __in LPDDENUMSURFACESCALLBACK lpfnCallback) +{ + ASSERT(m_pDirectDrawSurface); + return m_pDirectDrawSurface->EnumOverlayZOrders(dwFlags,lpContext,lpfnCallback); +} + + +STDMETHODIMP CAggDrawSurface::Flip(__in LPDIRECTDRAWSURFACE lpDDSurfaceTargetOverride,DWORD dwFlags) +{ + ASSERT(m_pDirectDrawSurface); + return m_pDirectDrawSurface->Flip(lpDDSurfaceTargetOverride,dwFlags); +} + + +STDMETHODIMP CAggDrawSurface::GetAttachedSurface(__in LPDDSCAPS lpDDSCaps, + __deref_out LPDIRECTDRAWSURFACE *lplpDDAttachedSurface) +{ + ASSERT(m_pDirectDrawSurface); + return m_pDirectDrawSurface->GetAttachedSurface(lpDDSCaps,lplpDDAttachedSurface); +} + + +STDMETHODIMP CAggDrawSurface::GetBltStatus(DWORD dwFlags) +{ + ASSERT(m_pDirectDrawSurface); + return m_pDirectDrawSurface->GetBltStatus(dwFlags); +} + + +STDMETHODIMP CAggDrawSurface::GetCaps(__out LPDDSCAPS lpDDSCaps) +{ + ASSERT(m_pDirectDrawSurface); + return m_pDirectDrawSurface->GetCaps(lpDDSCaps); +} + + +STDMETHODIMP CAggDrawSurface::GetClipper(__deref_out LPDIRECTDRAWCLIPPER *lplpDDClipper) +{ + ASSERT(m_pDirectDrawSurface); + return m_pDirectDrawSurface->GetClipper(lplpDDClipper); +} + + +STDMETHODIMP CAggDrawSurface::GetColorKey(DWORD dwFlags,__out LPDDCOLORKEY lpDDColorKey) +{ + ASSERT(m_pDirectDrawSurface); + return m_pDirectDrawSurface->GetColorKey(dwFlags,lpDDColorKey); +} + + +STDMETHODIMP CAggDrawSurface::GetDC(__out HDC *lphDC) +{ + ASSERT(m_pDirectDrawSurface); + return m_pDirectDrawSurface->GetDC(lphDC); +} + + +STDMETHODIMP CAggDrawSurface::GetFlipStatus(DWORD dwFlags) +{ + ASSERT(m_pDirectDrawSurface); + return m_pDirectDrawSurface->GetFlipStatus(dwFlags); +} + + +STDMETHODIMP CAggDrawSurface::GetOverlayPosition(__out LPLONG lpdwX,__out LPLONG lpdwY) +{ + ASSERT(m_pDirectDrawSurface); + return m_pDirectDrawSurface->GetOverlayPosition(lpdwX,lpdwY); +} + + +STDMETHODIMP CAggDrawSurface::GetPalette(__deref_out LPDIRECTDRAWPALETTE *lplpDDPalette) +{ + ASSERT(m_pDirectDrawSurface); + return m_pDirectDrawSurface->GetPalette(lplpDDPalette); +} + + +STDMETHODIMP CAggDrawSurface::GetPixelFormat(__out LPDDPIXELFORMAT lpDDPixelFormat) +{ + ASSERT(m_pDirectDrawSurface); + return m_pDirectDrawSurface->GetPixelFormat(lpDDPixelFormat); +} + + +// A bit of a warning here: Our media samples in DirectShow aggregate on +// IDirectDraw and IDirectDrawSurface (ie are available through IMediaSample +// by QueryInterface). Unfortunately the underlying DirectDraw code cannot +// be aggregated so we have to use these classes. The snag is that when we +// call a different surface and pass in this interface as perhaps the source +// surface the call will fail because DirectDraw dereferences the pointer to +// get at its private data structures. Therefore we supply this workaround to give +// access to the real IDirectDraw surface. A filter can call GetSurfaceDesc +// and we will fill in the lpSurface pointer with the real underlying surface + +STDMETHODIMP CAggDrawSurface::GetSurfaceDesc(__out LPDDSURFACEDESC lpDDSurfaceDesc) +{ + ASSERT(m_pDirectDrawSurface); + + // First call down to the underlying DirectDraw + + HRESULT hr = m_pDirectDrawSurface->GetSurfaceDesc(lpDDSurfaceDesc); + if (FAILED(hr)) { + return hr; + } + + // Store the real DirectDrawSurface interface + lpDDSurfaceDesc->lpSurface = m_pDirectDrawSurface; + return hr; +} + + +STDMETHODIMP CAggDrawSurface::Initialize(__in LPDIRECTDRAW lpDD,__in LPDDSURFACEDESC lpDDSurfaceDesc) +{ + ASSERT(m_pDirectDrawSurface); + return m_pDirectDrawSurface->Initialize(lpDD,lpDDSurfaceDesc); +} + + +STDMETHODIMP CAggDrawSurface::IsLost() +{ + ASSERT(m_pDirectDrawSurface); + return m_pDirectDrawSurface->IsLost(); +} + + +STDMETHODIMP CAggDrawSurface::Lock(__in LPRECT lpDestRect, + __inout LPDDSURFACEDESC lpDDSurfaceDesc, + DWORD dwFlags, + HANDLE hEvent) +{ + ASSERT(m_pDirectDrawSurface); + return m_pDirectDrawSurface->Lock(lpDestRect,lpDDSurfaceDesc,dwFlags,hEvent); +} + + +STDMETHODIMP CAggDrawSurface::ReleaseDC(HDC hDC) +{ + ASSERT(m_pDirectDrawSurface); + return m_pDirectDrawSurface->ReleaseDC(hDC); +} + + +STDMETHODIMP CAggDrawSurface::Restore() +{ + ASSERT(m_pDirectDrawSurface); + return m_pDirectDrawSurface->Restore(); +} + + +STDMETHODIMP CAggDrawSurface::SetClipper(__in LPDIRECTDRAWCLIPPER lpDDClipper) +{ + ASSERT(m_pDirectDrawSurface); + return m_pDirectDrawSurface->SetClipper(lpDDClipper); +} + + +STDMETHODIMP CAggDrawSurface::SetColorKey(DWORD dwFlags,__in LPDDCOLORKEY lpDDColorKey) +{ + ASSERT(m_pDirectDrawSurface); + return m_pDirectDrawSurface->SetColorKey(dwFlags,lpDDColorKey); +} + + +STDMETHODIMP CAggDrawSurface::SetOverlayPosition(LONG dwX,LONG dwY) +{ + ASSERT(m_pDirectDrawSurface); + return m_pDirectDrawSurface->SetOverlayPosition(dwX,dwY); +} + + +STDMETHODIMP CAggDrawSurface::SetPalette(__in LPDIRECTDRAWPALETTE lpDDPalette) +{ + ASSERT(m_pDirectDrawSurface); + return m_pDirectDrawSurface->SetPalette(lpDDPalette); +} + + +STDMETHODIMP CAggDrawSurface::Unlock(__in LPVOID lpSurfaceData) +{ + ASSERT(m_pDirectDrawSurface); + return m_pDirectDrawSurface->Unlock(lpSurfaceData); +} + + +STDMETHODIMP CAggDrawSurface::UpdateOverlay(__in LPRECT lpSrcRect, + __in LPDIRECTDRAWSURFACE lpDDDestSurface, + __in LPRECT lpDestRect, + DWORD dwFlags, + __in LPDDOVERLAYFX lpDDOverlayFX) +{ + ASSERT(m_pDirectDrawSurface); + return m_pDirectDrawSurface->UpdateOverlay(lpSrcRect,lpDDDestSurface,lpDestRect,dwFlags,lpDDOverlayFX); +} + + +STDMETHODIMP CAggDrawSurface::UpdateOverlayDisplay(DWORD dwFlags) +{ + ASSERT(m_pDirectDrawSurface); + return m_pDirectDrawSurface->UpdateOverlayDisplay(dwFlags); +} + + +STDMETHODIMP CAggDrawSurface::UpdateOverlayZOrder(DWORD dwFlags,__in LPDIRECTDRAWSURFACE lpDDSReference) +{ + ASSERT(m_pDirectDrawSurface); + return m_pDirectDrawSurface->UpdateOverlayZOrder(dwFlags,lpDDSReference); +} + + +// DirectShow must work on multiple platforms. In particular, it also runs on +// Windows NT 3.51 which does not have DirectDraw capabilities. The filters +// cannot therefore link statically to the DirectDraw library. To make their +// lives that little bit easier we provide this class that manages loading +// and unloading the library and creating the initial IDirectDraw interface + +CLoadDirectDraw::CLoadDirectDraw() : + m_pDirectDraw(NULL), + m_hDirectDraw(NULL) +{ +} + + +// Destructor forces unload + +CLoadDirectDraw::~CLoadDirectDraw() +{ + ReleaseDirectDraw(); + + if (m_hDirectDraw) { + NOTE("Unloading library"); + FreeLibrary(m_hDirectDraw); + } +} + + +// We can't be sure that DirectDraw is always available so we can't statically +// link to the library. Therefore we load the library, get the function entry +// point addresses and call them to create the driver objects. We return S_OK +// if we manage to load DirectDraw correctly otherwise we return E_NOINTERFACE +// We initialise a DirectDraw instance by explicitely loading the library and +// calling GetProcAddress on the DirectDrawCreate entry point that it exports + +// On a multi monitor system, we can get the DirectDraw object for any +// monitor (device) with the optional szDevice parameter + +HRESULT CLoadDirectDraw::LoadDirectDraw(__in LPSTR szDevice) +{ + PDRAWCREATE pDrawCreate; + PDRAWENUM pDrawEnum; + LPDIRECTDRAWENUMERATEEXA pDrawEnumEx; + HRESULT hr = NOERROR; + + NOTE("Entering DoLoadDirectDraw"); + + // Is DirectDraw already loaded + + if (m_pDirectDraw) { + NOTE("Already loaded"); + ASSERT(m_hDirectDraw); + return NOERROR; + } + + // Make sure the library is available + + if(!m_hDirectDraw) + { + UINT ErrorMode = SetErrorMode(SEM_NOOPENFILEERRORBOX); + m_hDirectDraw = LoadLibrary(TEXT("DDRAW.DLL")); + SetErrorMode(ErrorMode); + + if (m_hDirectDraw == NULL) { + DbgLog((LOG_ERROR,1,TEXT("Can't load DDRAW.DLL"))); + NOTE("No library"); + return E_NOINTERFACE; + } + } + + // Get the DLL address for the creator function + + pDrawCreate = (PDRAWCREATE)GetProcAddress(m_hDirectDraw,"DirectDrawCreate"); + // force ANSI, we assume it + pDrawEnum = (PDRAWENUM)GetProcAddress(m_hDirectDraw,"DirectDrawEnumerateA"); + pDrawEnumEx = (LPDIRECTDRAWENUMERATEEXA)GetProcAddress(m_hDirectDraw, + "DirectDrawEnumerateExA"); + + // We don't NEED DirectDrawEnumerateEx, that's just for multimon stuff + if (pDrawCreate == NULL || pDrawEnum == NULL) { + DbgLog((LOG_ERROR,1,TEXT("Can't get functions: Create=%x Enum=%x"), + pDrawCreate, pDrawEnum)); + NOTE("No entry point"); + ReleaseDirectDraw(); + return E_NOINTERFACE; + } + + DbgLog((LOG_TRACE,3,TEXT("Creating DDraw for device %s"), + szDevice ? szDevice : "")); + + // Create a DirectDraw display provider for this device, using the fancy + // multimon-aware version, if it exists + if (pDrawEnumEx) + m_pDirectDraw = DirectDrawCreateFromDeviceEx(szDevice, pDrawCreate, + pDrawEnumEx); + else + m_pDirectDraw = DirectDrawCreateFromDevice(szDevice, pDrawCreate, + pDrawEnum); + + if (m_pDirectDraw == NULL) { + DbgLog((LOG_ERROR,1,TEXT("Can't create DDraw"))); + NOTE("No instance"); + ReleaseDirectDraw(); + return E_NOINTERFACE; + } + return NOERROR; +} + + +// Called to release any DirectDraw provider we previously loaded. We may be +// called at any time especially when something goes horribly wrong and when +// we need to clean up before returning so we can't guarantee that all state +// variables are consistent so free only those really allocated allocated +// This should only be called once all reference counts have been released + +void CLoadDirectDraw::ReleaseDirectDraw() +{ + NOTE("Releasing DirectDraw driver"); + + // Release any DirectDraw provider interface + + if (m_pDirectDraw) { + NOTE("Releasing instance"); + m_pDirectDraw->Release(); + m_pDirectDraw = NULL; + } + +} + + +// Return NOERROR (S_OK) if DirectDraw has been loaded by this object + +HRESULT CLoadDirectDraw::IsDirectDrawLoaded() +{ + NOTE("Entering IsDirectDrawLoaded"); + + if (m_pDirectDraw == NULL) { + NOTE("DirectDraw not loaded"); + return S_FALSE; + } + return NOERROR; +} + + +// Return the IDirectDraw interface we look after + +LPDIRECTDRAW CLoadDirectDraw::GetDirectDraw() +{ + NOTE("Entering GetDirectDraw"); + + if (m_pDirectDraw == NULL) { + NOTE("No DirectDraw"); + return NULL; + } + + NOTE("Returning DirectDraw"); + m_pDirectDraw->AddRef(); + return m_pDirectDraw; +} + + +// Are we running on Direct Draw version 1? We need to find out as +// we rely on specific bug fixes in DirectDraw 2 for fullscreen playback. To +// find out, we simply see if it supports IDirectDraw2. Only version 2 and +// higher support this. + +BOOL CLoadDirectDraw::IsDirectDrawVersion1() +{ + + if (m_pDirectDraw == NULL) + return FALSE; + + IDirectDraw2 *p = NULL; + HRESULT hr = m_pDirectDraw->QueryInterface(IID_IDirectDraw2, (void **)&p); + if (p) + p->Release(); + if (hr == NOERROR) { + DbgLog((LOG_TRACE,3,TEXT("Direct Draw Version 2 or greater"))); + return FALSE; + } else { + DbgLog((LOG_TRACE,3,TEXT("Direct Draw Version 1"))); + return TRUE; + } +} + +//------------------------------------------------------------------------------ +// File: DllSetup.cpp +// +// Desc: DirectShow base classes. +// +// Copyright (c) 1992-2001 Microsoft Corporation. All rights reserved. +//------------------------------------------------------------------------------ + +//--------------------------------------------------------------------------- +// defines + +#define MAX_KEY_LEN 260 + + +//--------------------------------------------------------------------------- +// externally defined functions/variable + +extern int g_cTemplates; +extern CFactoryTemplate g_Templates[]; + +//--------------------------------------------------------------------------- +// +// EliminateSubKey +// +// Try to enumerate all keys under this one. +// if we find anything, delete it completely. +// Otherwise just delete it. +// +// note - this was pinched/duplicated from +// Filgraph\Mapper.cpp - so should it be in +// a lib somewhere? +// +//--------------------------------------------------------------------------- + +STDAPI +EliminateSubKey( HKEY hkey, LPCTSTR strSubKey ) +{ + HKEY hk; + if (0 == lstrlen(strSubKey) ) { + // defensive approach + return E_FAIL; + } + + LONG lreturn = RegOpenKeyEx( hkey + , strSubKey + , 0 + , MAXIMUM_ALLOWED + , &hk ); + + ASSERT( lreturn == ERROR_SUCCESS + || lreturn == ERROR_FILE_NOT_FOUND + || lreturn == ERROR_INVALID_HANDLE ); + + if( ERROR_SUCCESS == lreturn ) + { + // Keep on enumerating the first (zero-th) + // key and deleting that + + for( ; ; ) + { + TCHAR Buffer[MAX_KEY_LEN]; + DWORD dw = MAX_KEY_LEN; + FILETIME ft; + + lreturn = RegEnumKeyEx( hk + , 0 + , Buffer + , &dw + , NULL + , NULL + , NULL + , &ft); + + ASSERT( lreturn == ERROR_SUCCESS + || lreturn == ERROR_NO_MORE_ITEMS ); + + if( ERROR_SUCCESS == lreturn ) + { + EliminateSubKey(hk, Buffer); + } + else + { + break; + } + } + + RegCloseKey(hk); + RegDeleteKey(hkey, strSubKey); + } + + return NOERROR; +} + + +//--------------------------------------------------------------------------- +// +// AMovieSetupRegisterServer() +// +// registers specfied file "szFileName" as server for +// CLSID "clsServer". A description is also required. +// The ThreadingModel and ServerType are optional, as +// they default to InprocServer32 (i.e. dll) and Both. +// +//--------------------------------------------------------------------------- + +STDAPI +AMovieSetupRegisterServer( CLSID clsServer + , LPCWSTR szDescription + , LPCWSTR szFileName + , LPCWSTR szThreadingModel = L"Both" + , LPCWSTR szServerType = L"InprocServer32" ) +{ + // temp buffer + // + TCHAR achTemp[MAX_PATH]; + + // convert CLSID uuid to string and write + // out subkey as string - CLSID\{} + // + OLECHAR szCLSID[CHARS_IN_GUID]; + HRESULT hr = StringFromGUID2( clsServer + , szCLSID + , CHARS_IN_GUID ); + ASSERT( SUCCEEDED(hr) ); + + // create key + // + HKEY hkey; + (void)StringCchPrintf( achTemp, NUMELMS(achTemp), TEXT("CLSID\\%ls"), szCLSID ); + LONG lreturn = RegCreateKey( HKEY_CLASSES_ROOT + , (LPCTSTR)achTemp + , &hkey ); + if( ERROR_SUCCESS != lreturn ) + { + return AmHresultFromWin32(lreturn); + } + + // set description string + // + + (void)StringCchPrintf( achTemp, NUMELMS(achTemp), TEXT("%ls"), szDescription ); + lreturn = RegSetValue( hkey + , (LPCTSTR)NULL + , REG_SZ + , achTemp + , sizeof(achTemp) ); + if( ERROR_SUCCESS != lreturn ) + { + RegCloseKey( hkey ); + return AmHresultFromWin32(lreturn); + } + + // create CLSID\\{"CLSID"}\\"ServerType" key, + // using key to CLSID\\{"CLSID"} passed back by + // last call to RegCreateKey(). + // + HKEY hsubkey; + + (void)StringCchPrintf( achTemp, NUMELMS(achTemp), TEXT("%ls"), szServerType ); + lreturn = RegCreateKey( hkey + , achTemp + , &hsubkey ); + if( ERROR_SUCCESS != lreturn ) + { + RegCloseKey( hkey ); + return AmHresultFromWin32(lreturn); + } + + // set Server string + // + (void)StringCchPrintf( achTemp, NUMELMS(achTemp), TEXT("%ls"), szFileName ); + lreturn = RegSetValue( hsubkey + , (LPCTSTR)NULL + , REG_SZ + , (LPCTSTR)achTemp + , sizeof(TCHAR) * (lstrlen(achTemp)+1) ); + if( ERROR_SUCCESS != lreturn ) + { + RegCloseKey( hkey ); + RegCloseKey( hsubkey ); + return AmHresultFromWin32(lreturn); + } + + (void)StringCchPrintf( achTemp, NUMELMS(achTemp), TEXT("%ls"), szThreadingModel ); + lreturn = RegSetValueEx( hsubkey + , TEXT("ThreadingModel") + , 0L + , REG_SZ + , (CONST BYTE *)achTemp + , sizeof(TCHAR) * (lstrlen(achTemp)+1) ); + + // close hkeys + // + RegCloseKey( hkey ); + RegCloseKey( hsubkey ); + + // and return + // + return HRESULT_FROM_WIN32(lreturn); + +} + + +//--------------------------------------------------------------------------- +// +// AMovieSetupUnregisterServer() +// +// default ActiveMovie dll setup function +// - to use must be called from an exported +// function named DllRegisterServer() +// +//--------------------------------------------------------------------------- + +STDAPI +AMovieSetupUnregisterServer( CLSID clsServer ) +{ + // convert CLSID uuid to string and write + // out subkey CLSID\{} + // + OLECHAR szCLSID[CHARS_IN_GUID]; + HRESULT hr = StringFromGUID2( clsServer + , szCLSID + , CHARS_IN_GUID ); + ASSERT( SUCCEEDED(hr) ); + + TCHAR achBuffer[MAX_KEY_LEN]; + (void)StringCchPrintf( achBuffer, NUMELMS(achBuffer), TEXT("CLSID\\%ls"), szCLSID ); + + // delete subkey + // + + hr = EliminateSubKey( HKEY_CLASSES_ROOT, achBuffer ); + ASSERT( SUCCEEDED(hr) ); + + // return + // + return NOERROR; +} + + +//--------------------------------------------------------------------------- +// +// AMovieSetupRegisterFilter through IFilterMapper2 +// +//--------------------------------------------------------------------------- + +STDAPI +AMovieSetupRegisterFilter2( const AMOVIESETUP_FILTER * const psetupdata + , IFilterMapper2 * pIFM2 + , BOOL bRegister ) +{ + DbgLog((LOG_TRACE, 3, TEXT("= AMovieSetupRegisterFilter"))); + + // check we've got data + // + if( NULL == psetupdata ) return S_FALSE; + + + // unregister filter + // (as pins are subkeys of filter's CLSID key + // they do not need to be removed separately). + // + DbgLog((LOG_TRACE, 3, TEXT("= = unregister filter"))); + HRESULT hr = pIFM2->UnregisterFilter( + 0, // default category + 0, // default instance name + *psetupdata->clsID ); + + + if( bRegister ) + { + REGFILTER2 rf2; + rf2.dwVersion = 1; + rf2.dwMerit = psetupdata->dwMerit; + rf2.cPins = psetupdata->nPins; + rf2.rgPins = psetupdata->lpPin; + + // register filter + // + DbgLog((LOG_TRACE, 3, TEXT("= = register filter"))); + hr = pIFM2->RegisterFilter(*psetupdata->clsID + , psetupdata->strName + , 0 // moniker + , 0 // category + , NULL // instance + , &rf2); + } + + // handle one acceptable "error" - that + // of filter not being registered! + // (couldn't find a suitable #define'd + // name for the error!) + // + if( 0x80070002 == hr) + return NOERROR; + else + return hr; +} + +#ifndef STREAMS_PROVIDE_CUSTOM_FACTORY + +//--------------------------------------------------------------------------- +// +// RegisterAllServers() +// +//--------------------------------------------------------------------------- + +STDAPI +RegisterAllServers( LPCWSTR szFileName, BOOL bRegister ) +{ + HRESULT hr = NOERROR; + + for( int i = 0; i < g_cTemplates; i++ ) + { + // get i'th template + // + const CFactoryTemplate *pT = &g_Templates[i]; + + DbgLog((LOG_TRACE, 2, TEXT("- - register %ls"), + (LPCWSTR)pT->m_Name )); + + // register CLSID and InprocServer32 + // + if( bRegister ) + { + hr = AMovieSetupRegisterServer( *(pT->m_ClsID) + , (LPCWSTR)pT->m_Name + , szFileName ); + } + else + { + hr = AMovieSetupUnregisterServer( *(pT->m_ClsID) ); + } + + // check final error for this pass + // and break loop if we failed + // + if( FAILED(hr) ) + break; + } + + return hr; +} + + +//--------------------------------------------------------------------------- +// +// AMovieDllRegisterServer2() +// +// default ActiveMovie dll setup function +// - to use must be called from an exported +// function named DllRegisterServer() +// +// this function is table driven using the +// static members of the CFactoryTemplate +// class defined in the dll. +// +// it registers the Dll as the InprocServer32 +// and then calls the IAMovieSetup.Register +// method. +// +//--------------------------------------------------------------------------- + +STDAPI +AMovieDllRegisterServer2( BOOL bRegister ) +{ + HRESULT hr = NOERROR; + + DbgLog((LOG_TRACE, 2, TEXT("AMovieDllRegisterServer2()"))); + + // get file name (where g_hInst is the + // instance handle of the filter dll) + // + WCHAR achFileName[MAX_PATH]; + + // WIN95 doesn't support GetModuleFileNameW + // + { + char achTemp[MAX_PATH]; + + DbgLog((LOG_TRACE, 2, TEXT("- get module file name"))); + + // g_hInst handle is set in our dll entry point. Make sure + // DllEntryPoint in dllentry.cpp is called + ASSERT(g_hInst != 0); + + if( 0 == GetModuleFileNameA( g_hInst + , achTemp + , sizeof(achTemp) ) ) + { + // we've failed! + DWORD dwerr = GetLastError(); + return AmHresultFromWin32(dwerr); + } + + MultiByteToWideChar( CP_ACP + , 0L + , achTemp + , lstrlenA(achTemp) + 1 + , achFileName + , NUMELMS(achFileName) ); + } + + // + // first registering, register all OLE servers + // + if( bRegister ) + { + DbgLog((LOG_TRACE, 2, TEXT("- register OLE Servers"))); + hr = RegisterAllServers( achFileName, TRUE ); + } + + // + // next, register/unregister all filters + // + + if( SUCCEEDED(hr) ) + { + // init is ref counted so call just in case + // we're being called cold. + // + DbgLog((LOG_TRACE, 2, TEXT("- CoInitialize"))); + hr = CoInitialize( (LPVOID)NULL ); + ASSERT( SUCCEEDED(hr) ); + + // get hold of IFilterMapper2 + // + DbgLog((LOG_TRACE, 2, TEXT("- obtain IFilterMapper2"))); + IFilterMapper2 *pIFM2 = 0; + IFilterMapper *pIFM = 0; + hr = CoCreateInstance( CLSID_FilterMapper2 + , NULL + , CLSCTX_INPROC_SERVER + , IID_IFilterMapper2 + , (void **)&pIFM2 ); + if(FAILED(hr)) + { + DbgLog((LOG_TRACE, 2, TEXT("- trying IFilterMapper instead"))); + + hr = CoCreateInstance( + CLSID_FilterMapper, + NULL, + CLSCTX_INPROC_SERVER, + IID_IFilterMapper, + (void **)&pIFM); + } + if( SUCCEEDED(hr) ) + { + // scan through array of CFactoryTemplates + // registering servers and filters. + // + DbgLog((LOG_TRACE, 2, TEXT("- register Filters"))); + for( int i = 0; i < g_cTemplates; i++ ) + { + // get i'th template + // + const CFactoryTemplate *pT = &g_Templates[i]; + + if( NULL != pT->m_pAMovieSetup_Filter ) + { + DbgLog((LOG_TRACE, 2, TEXT("- - register %ls"), (LPCWSTR)pT->m_Name )); + + if(pIFM2) + { + hr = AMovieSetupRegisterFilter2( pT->m_pAMovieSetup_Filter, pIFM2, bRegister ); + } + else + { + hr = AMovieSetupRegisterFilter( pT->m_pAMovieSetup_Filter, pIFM, bRegister ); + } + } + + // check final error for this pass + // and break loop if we failed + // + if( FAILED(hr) ) + break; + } + + // release interface + // + if(pIFM2) + pIFM2->Release(); + else + pIFM->Release(); + + } + + // and clear up + // + CoFreeUnusedLibraries(); + CoUninitialize(); + } + + // + // if unregistering, unregister all OLE servers + // + if( SUCCEEDED(hr) && !bRegister ) + { + DbgLog((LOG_TRACE, 2, TEXT("- register OLE Servers"))); + hr = RegisterAllServers( achFileName, FALSE ); + } + + DbgLog((LOG_TRACE, 2, TEXT("- return %0x"), hr)); + return hr; +} + + +//--------------------------------------------------------------------------- +// +// AMovieDllRegisterServer() +// +// default ActiveMovie dll setup function +// - to use must be called from an exported +// function named DllRegisterServer() +// +// this function is table driven using the +// static members of the CFactoryTemplate +// class defined in the dll. +// +// it registers the Dll as the InprocServer32 +// and then calls the IAMovieSetup.Register +// method. +// +//--------------------------------------------------------------------------- + + +STDAPI +AMovieDllRegisterServer( void ) +{ + HRESULT hr = NOERROR; + + // get file name (where g_hInst is the + // instance handle of the filter dll) + // + WCHAR achFileName[MAX_PATH]; + + { + // WIN95 doesn't support GetModuleFileNameW + // + char achTemp[MAX_PATH]; + + if( 0 == GetModuleFileNameA( g_hInst + , achTemp + , sizeof(achTemp) ) ) + { + // we've failed! + DWORD dwerr = GetLastError(); + return AmHresultFromWin32(dwerr); + } + + MultiByteToWideChar( CP_ACP + , 0L + , achTemp + , lstrlenA(achTemp) + 1 + , achFileName + , NUMELMS(achFileName) ); + } + + // scan through array of CFactoryTemplates + // registering servers and filters. + // + for( int i = 0; i < g_cTemplates; i++ ) + { + // get i'th template + // + const CFactoryTemplate *pT = &g_Templates[i]; + + // register CLSID and InprocServer32 + // + hr = AMovieSetupRegisterServer( *(pT->m_ClsID) + , (LPCWSTR)pT->m_Name + , achFileName ); + + // instantiate all servers and get hold of + // IAMovieSetup, if implemented, and call + // IAMovieSetup.Register() method + // + if( SUCCEEDED(hr) && (NULL != pT->m_lpfnNew) ) + { + // instantiate object + // + PAMOVIESETUP psetup; + hr = CoCreateInstance( *(pT->m_ClsID) + , 0 + , CLSCTX_INPROC_SERVER + , IID_IAMovieSetup + , reinterpret_cast(&psetup) ); + if( SUCCEEDED(hr) ) + { + hr = psetup->Unregister(); + if( SUCCEEDED(hr) ) + hr = psetup->Register(); + psetup->Release(); + } + else + { + if( (E_NOINTERFACE == hr ) + || (VFW_E_NEED_OWNER == hr ) ) + hr = NOERROR; + } + } + + // check final error for this pass + // and break loop if we failed + // + if( FAILED(hr) ) + break; + + } // end-for + + return hr; +} + + +//--------------------------------------------------------------------------- +// +// AMovieDllUnregisterServer() +// +// default ActiveMovie dll uninstall function +// - to use must be called from an exported +// function named DllRegisterServer() +// +// this function is table driven using the +// static members of the CFactoryTemplate +// class defined in the dll. +// +// it calls the IAMovieSetup.Unregister +// method and then unregisters the Dll +// as the InprocServer32 +// +//--------------------------------------------------------------------------- + +STDAPI +AMovieDllUnregisterServer() +{ + // initialize return code + // + HRESULT hr = NOERROR; + + // scan through CFactory template and unregister + // all OLE servers and filters. + // + for( int i = g_cTemplates; i--; ) + { + // get i'th template + // + const CFactoryTemplate *pT = &g_Templates[i]; + + // check method exists + // + if( NULL != pT->m_lpfnNew ) + { + // instantiate object + // + PAMOVIESETUP psetup; + hr = CoCreateInstance( *(pT->m_ClsID) + , 0 + , CLSCTX_INPROC_SERVER + , IID_IAMovieSetup + , reinterpret_cast(&psetup) ); + if( SUCCEEDED(hr) ) + { + hr = psetup->Unregister(); + psetup->Release(); + } + else + { + if( (E_NOINTERFACE == hr ) + || (VFW_E_NEED_OWNER == hr ) ) + hr = NOERROR; + } + } + + // unregister CLSID and InprocServer32 + // + if( SUCCEEDED(hr) ) + { + hr = AMovieSetupUnregisterServer( *(pT->m_ClsID) ); + } + + // check final error for this pass + // and break loop if we failed + // + if( FAILED(hr) ) + break; + } + + return hr; +} +#endif diff --git a/Source/streams.h b/Source/streams.h new file mode 100644 index 0000000..4bedc81 --- /dev/null +++ b/Source/streams.h @@ -0,0 +1,3876 @@ +//------------------------------------------------------------------------------ +// File: streams.h +// +// Desc: DirectShow base classes - defines overall streams architecture. +// +// Copyright (c) 1992-2001 Microsoft Corporation. All rights reserved. +//------------------------------------------------------------------------------ + +#ifndef __STREAMS__ +#define __STREAMS__ + +#define _HAS_EXCEPTIONS 0 +#define WIN32_LEAN_AND_MEAN +#include + +#if defined(_MSC_VER) && _MSC_VER>=1100 +#define AM_NOVTABLE __declspec(novtable) +#else +#define AM_NOVTABLE +#endif + +#if defined(_DEBUG) && !defined(DEBUG) +#define DEBUG +#endif + +#include +#include // Generated IDL header file for streams interfaces +#include // required by amvideo.h +#include // ActiveMovie video interfaces and definitions +#include // HRESULT status and error definitions +#include // declaration of type GUIDs and well-known clsids +#include // event code definitions + +//// -- UNUSED FOR THIS PROJECT -- +//include amaudio.h explicitly if you need it. it requires the DX SDK. +//#include // ActiveMovie audio interfaces and definitions +//#include // Light weight com function prototypes +//#include // generated from control.odl +//#include // External device control interface defines +//#include // audio filter device error event codes +//#include "dllsetup.h" // Filter registration support functions +//#include "cache.h" // Simple cache container class +//#include "ctlutil.h" // control interface utility classes +//#include "transfrm.h" // Generic transform filter +//#include "transip.h" // Generic transform-in-place filter +//#include "outputq.h" // Output pin queueing +//#include "renbase.h" // Base class for writing ActiveX renderers +//#include "winctrl.h" // Implements the IVideoWindow interface +//#include "sysclock.h" // System clock +//#include "pstream.h" // IPersistStream helper class +//#include "vtrans.h" // Video Transform Filter base class +//#include "amextra.h" +//#include "strmctl.h" // IAMStreamControl support + +//// -- EMBEDDED BELOW -- +//#include "reftime.h" // Helper class for REFERENCE_TIME management +//#include "wxdebug.h" // Debug support for logging and ASSERTs +//#include "wxutil.h" // General helper classes for threads etc +//#include "combase.h" // Base COM classes to support IUnknown +//#include "wxlist.h" // Non MFC generic list class +//#include "mtype.h" // Helper class for managing media types +//#include "amfilter.h" // Main streams architecture class hierachy +//#include "source.h" // Generic source filter +//#include "cprop.h" // Base property page class + +//// -- EMBEDDED IN streams.cpp -- +//#include "fourcc.h" // conversions between FOURCCs and GUIDs +//#include "msgthrd.h" // CMsgThread +//#include "refclock.h" // Base clock class +//#include "videoctl.h" // Specifically video related classes +//#include "measure.h" // Performance measurement +//#include "winutil.h" // Helps with filters that manage windows + +#endif // __STREAMS__ + +//------------------------------------------------------------------------------ +// File: RefTime.h +// +// Desc: DirectShow base classes - defines CRefTime, a class that manages +// reference times. +// +// Copyright (c) 1992-2001 Microsoft Corporation. All rights reserved. +//------------------------------------------------------------------------------ + + +// +// CRefTime +// +// Manage reference times. +// Shares same data layout as REFERENCE_TIME, but adds some (nonvirtual) +// functions providing simple comparison, conversion and arithmetic. +// +// A reference time (at the moment) is a unit of seconds represented in +// 100ns units as is used in the Win32 FILETIME structure. BUT the time +// a REFERENCE_TIME represents is NOT the time elapsed since 1/1/1601 it +// will either be stream time or reference time depending upon context +// +// This class provides simple arithmetic operations on reference times +// +// keep non-virtual otherwise the data layout will not be the same as +// REFERENCE_TIME + + +// ----- +// note that you are safe to cast a CRefTime* to a REFERENCE_TIME*, but +// you will need to do so explicitly +// ----- + + +#ifndef __REFTIME__ +#define __REFTIME__ + + +const LONGLONG MILLISECONDS = (1000); // 10 ^ 3 +const LONGLONG NANOSECONDS = (1000000000); // 10 ^ 9 +const LONGLONG UNITS = (NANOSECONDS / 100); // 10 ^ 7 + +/* Unfortunately an inline function here generates a call to __allmul + - even for constants! +*/ +#define MILLISECONDS_TO_100NS_UNITS(lMs) \ + Int32x32To64((lMs), (UNITS / MILLISECONDS)) + +class CRefTime +{ +public: + + // *MUST* be the only data member so that this class is exactly + // equivalent to a REFERENCE_TIME. + // Also, must be *no virtual functions* + + REFERENCE_TIME m_time; + + inline CRefTime() + { + // default to 0 time + m_time = 0; + }; + + inline CRefTime(LONG msecs) + { + m_time = MILLISECONDS_TO_100NS_UNITS(msecs); + }; + + inline CRefTime(REFERENCE_TIME rt) + { + m_time = rt; + }; + + inline operator REFERENCE_TIME() const + { + return m_time; + }; + + inline CRefTime& operator=(const CRefTime& rt) + { + m_time = rt.m_time; + return *this; + }; + + inline CRefTime& operator=(const LONGLONG ll) + { + m_time = ll; + return *this; + }; + + inline CRefTime& operator+=(const CRefTime& rt) + { + return (*this = *this + rt); + }; + + inline CRefTime& operator-=(const CRefTime& rt) + { + return (*this = *this - rt); + }; + + inline LONG Millisecs(void) + { + return (LONG)(m_time / (UNITS / MILLISECONDS)); + }; + + inline LONGLONG GetUnits(void) + { + return m_time; + }; +}; + +const LONGLONG TimeZero = 0; + +#endif /* __REFTIME__ */ + +//------------------------------------------------------------------------------ +// File: WXDebug.h +// +// Desc: DirectShow base classes - provides debugging facilities. +// +// Copyright (c) 1992-2001 Microsoft Corporation. All rights reserved. +//------------------------------------------------------------------------------ + + +#ifndef __WXDEBUG__ +#define __WXDEBUG__ + +// This library provides fairly straight forward debugging functionality, this +// is split into two main sections. The first is assertion handling, there are +// three types of assertions provided here. The most commonly used one is the +// ASSERT(condition) macro which will pop up a message box including the file +// and line number if the condition evaluates to FALSE. Then there is the +// EXECUTE_ASSERT macro which is the same as ASSERT except the condition will +// still be executed in NON debug builds. The final type of assertion is the +// KASSERT macro which is more suitable for pure (perhaps kernel) filters as +// the condition is printed onto the debugger rather than in a message box. +// +// The other part of the debug module facilties is general purpose logging. +// This is accessed by calling DbgLog(). The function takes a type and level +// field which define the type of informational string you are presenting and +// it's relative importance. The type field can be a combination (one or more) +// of LOG_TIMING, LOG_TRACE, LOG_MEMORY, LOG_LOCKING and LOG_ERROR. The level +// is a DWORD value where zero defines highest important. Use of zero as the +// debug logging level is to be encouraged ONLY for major errors or events as +// they will ALWAYS be displayed on the debugger. Other debug output has it's +// level matched against the current debug output level stored in the registry +// for this module and if less than the current setting it will be displayed. +// +// Each module or executable has it's own debug output level for each of the +// five types. These are read in when the DbgInitialise function is called +// for DLLs linking to STRMBASE.LIB this is done automatically when the DLL +// is loaded, executables must call it explicitely with the module instance +// handle given to them through the WINMAIN entry point. An executable must +// also call DbgTerminate when they have finished to clean up the resources +// the debug library uses, once again this is done automatically for DLLs + +// These are the five different categories of logging information + +enum { LOG_TIMING = 0x01, // Timing and performance measurements + LOG_TRACE = 0x02, // General step point call tracing + LOG_MEMORY = 0x04, // Memory and object allocation/destruction + LOG_LOCKING = 0x08, // Locking/unlocking of critical sections + LOG_ERROR = 0x10, // Debug error notification + LOG_CUSTOM1 = 0x20, + LOG_CUSTOM2 = 0x40, + LOG_CUSTOM3 = 0x80, + LOG_CUSTOM4 = 0x100, + LOG_CUSTOM5 = 0x200, +}; + +#define LOG_FORCIBLY_SET 0x80000000 + +enum { CDISP_HEX = 0x01, + CDISP_DEC = 0x02}; + +// For each object created derived from CBaseObject (in debug builds) we +// create a descriptor that holds it's name (statically allocated memory) +// and a cookie we assign it. We keep a list of all the active objects +// we have registered so that we can dump a list of remaining objects + +typedef struct tag_ObjectDesc { + LPCSTR m_szName; + LPCWSTR m_wszName; + DWORD m_dwCookie; + tag_ObjectDesc *m_pNext; +} ObjectDesc; + +#define DLLIMPORT __declspec(dllimport) +#define DLLEXPORT __declspec(dllexport) + +#ifdef DEBUG + + #define NAME(x) TEXT(x) + + // These are used internally by the debug library (PRIVATE) + + void WINAPI DbgInitKeyLevels(HKEY hKey, bool fTakeMax); + void WINAPI DbgInitGlobalSettings(bool fTakeMax); + void WINAPI DbgInitModuleSettings(bool fTakeMax); + void WINAPI DbgInitModuleName(); + DWORD WINAPI DbgRegisterObjectCreation( + LPCSTR szObjectName, LPCWSTR wszObjectName); + + BOOL WINAPI DbgRegisterObjectDestruction(DWORD dwCookie); + + // These are the PUBLIC entry points + + BOOL WINAPI DbgCheckModuleLevel(DWORD Type,DWORD Level); + void WINAPI DbgSetModuleLevel(DWORD Type,DWORD Level); + void WINAPI DbgSetAutoRefreshLevels(bool fAuto); + + // Initialise the library with the module handle + + void WINAPI DbgInitialise(HINSTANCE hInst); + void WINAPI DbgTerminate(); + + void WINAPI DbgDumpObjectRegister(); + + // Display error and logging to the user + + void WINAPI DbgAssert(LPCTSTR pCondition,LPCTSTR pFileName,INT iLine); + void WINAPI DbgBreakPoint(LPCTSTR pCondition,LPCTSTR pFileName,INT iLine); + void WINAPI DbgBreakPoint(LPCTSTR pFileName,INT iLine,__format_string LPCTSTR szFormatString,...); + + void WINAPI DbgKernelAssert(LPCTSTR pCondition,LPCTSTR pFileName,INT iLine); + void WINAPI DbgLogInfo(DWORD Type,DWORD Level,__format_string LPCTSTR pFormat,...); +#ifdef UNICODE + void WINAPI DbgLogInfo(DWORD Type,DWORD Level,__format_string LPCSTR pFormat,...); + void WINAPI DbgAssert(LPCSTR pCondition,LPCSTR pFileName,INT iLine); + void WINAPI DbgBreakPoint(LPCSTR pCondition,LPCSTR pFileName,INT iLine); + void WINAPI DbgKernelAssert(LPCSTR pCondition,LPCSTR pFileName,INT iLine); +#endif + void WINAPI DbgOutString(LPCTSTR psz); + + // Debug infinite wait stuff + DWORD WINAPI DbgWaitForSingleObject(HANDLE h); + DWORD WINAPI DbgWaitForMultipleObjects(DWORD nCount, + __in_ecount(nCount) CONST HANDLE *lpHandles, + BOOL bWaitAll); + void WINAPI DbgSetWaitTimeout(DWORD dwTimeout); + +#ifdef __strmif_h__ + // Display a media type: Terse at level 2, verbose at level 5 + void WINAPI DisplayType(LPCTSTR label, const AM_MEDIA_TYPE *pmtIn); + + // Dump lots of information about a filter graph + void WINAPI DumpGraph(IFilterGraph *pGraph, DWORD dwLevel); +#endif + + #define KASSERT(_x_) if (!(_x_)) \ + DbgKernelAssert(TEXT(#_x_),TEXT(__FILE__),__LINE__) + + // Break on the debugger without putting up a message box + // message goes to debugger instead + + #define KDbgBreak(_x_) \ + DbgKernelAssert(TEXT(#_x_),TEXT(__FILE__),__LINE__) + + // We chose a common name for our ASSERT macro, MFC also uses this name + // So long as the implementation evaluates the condition and handles it + // then we will be ok. Rather than override the behaviour expected we + // will leave whatever first defines ASSERT as the handler (i.e. MFC) + #ifndef ASSERT + #define ASSERT(_x_) if (!(_x_)) \ + DbgAssert(TEXT(#_x_),TEXT(__FILE__),__LINE__) + #endif + + #define DbgAssertAligned( _ptr_, _alignment_ ) ASSERT( ((DWORD_PTR) (_ptr_)) % (_alignment_) == 0) + + // Put up a message box informing the user of a halt + // condition in the program + + #define DbgBreak(_x_) \ + DbgBreakPoint(TEXT(#_x_),TEXT(__FILE__),__LINE__) + + #define EXECUTE_ASSERT(_x_) ASSERT(_x_) + #define DbgLog(_x_) DbgLogInfo _x_ + // MFC style trace macros + + #define NOTE(_x_) DbgLog((LOG_TRACE,5,TEXT(_x_))) + #define NOTE1(_x_,a) DbgLog((LOG_TRACE,5,TEXT(_x_),a)) + #define NOTE2(_x_,a,b) DbgLog((LOG_TRACE,5,TEXT(_x_),a,b)) + #define NOTE3(_x_,a,b,c) DbgLog((LOG_TRACE,5,TEXT(_x_),a,b,c)) + #define NOTE4(_x_,a,b,c,d) DbgLog((LOG_TRACE,5,TEXT(_x_),a,b,c,d)) + #define NOTE5(_x_,a,b,c,d,e) DbgLog((LOG_TRACE,5,TEXT(_x_),a,b,c,d,e)) + +#else + + // Retail builds make public debug functions inert - WARNING the source + // files do not define or build any of the entry points in debug builds + // (public entry points compile to nothing) so if you go trying to call + // any of the private entry points in your source they won't compile + + #define NAME(_x_) ((LPTSTR) NULL) + + #define DbgInitialise(hInst) + #define DbgTerminate() + #define DbgLog(_x_) 0 + #define DbgOutString(psz) + #define DbgAssertAligned( _ptr_, _alignment_ ) 0 + + #define DbgRegisterObjectCreation(pObjectName) + #define DbgRegisterObjectDestruction(dwCookie) + #define DbgDumpObjectRegister() + + #define DbgCheckModuleLevel(Type,Level) + #define DbgSetModuleLevel(Type,Level) + #define DbgSetAutoRefreshLevels(fAuto) + + #define DbgWaitForSingleObject(h) WaitForSingleObject(h, INFINITE) + #define DbgWaitForMultipleObjects(nCount, lpHandles, bWaitAll) \ + WaitForMultipleObjects(nCount, lpHandles, bWaitAll, INFINITE) + #define DbgSetWaitTimeout(dwTimeout) + + #define KDbgBreak(_x_) + #define DbgBreak(_x_) + + #define KASSERT(_x_) ((void)0) + #ifndef ASSERT + #define ASSERT(_x_) ((void)0) + #endif + #define EXECUTE_ASSERT(_x_) ((void)(_x_)) + + // MFC style trace macros + + #define NOTE(_x_) ((void)0) + #define NOTE1(_x_,a) ((void)0) + #define NOTE2(_x_,a,b) ((void)0) + #define NOTE3(_x_,a,b,c) ((void)0) + #define NOTE4(_x_,a,b,c,d) ((void)0) + #define NOTE5(_x_,a,b,c,d,e) ((void)0) + + #define DisplayType(label, pmtIn) ((void)0) + #define DumpGraph(pGraph, label) ((void)0) +#endif + + +// Checks a pointer which should be non NULL - can be used as follows. + +#define CheckPointer(p,ret) {if((p)==NULL) return (ret);} + +// HRESULT Foo(VOID *pBar) +// { +// CheckPointer(pBar,E_INVALIDARG) +// } +// +// Or if the function returns a boolean +// +// BOOL Foo(VOID *pBar) +// { +// CheckPointer(pBar,FALSE) +// } + +#define ValidateReadPtr(p,cb) 0 +#define ValidateWritePtr(p,cb) 0 +#define ValidateReadWritePtr(p,cb) 0 +#define ValidateStringPtr(p) 0 +#define ValidateStringPtrA(p) 0 +#define ValidateStringPtrW(p) 0 + + +#ifdef _OBJBASE_H_ + + // Outputting GUID names. If you want to include the name + // associated with a GUID (eg CLSID_...) then + // + // GuidNames[yourGUID] + // + // Returns the name defined in uuids.h as a string + + typedef struct { + CHAR *szName; + GUID guid; + } GUID_STRING_ENTRY; + + class CGuidNameList { + public: + CHAR *operator [] (const GUID& guid); + }; + + extern CGuidNameList GuidNames; + +#endif + +#ifndef REMIND + // REMIND macro - generates warning as reminder to complete coding + // (eg) usage: + // + // #pragma message (REMIND("Add automation support")) + + + #define QUOTE(x) #x + #define QQUOTE(y) QUOTE(y) + #define REMIND(str) __FILE__ "(" QQUOTE(__LINE__) ") : " str +#endif + +// Method to display objects in a useful format +// +// eg If you want to display a LONGLONG ll in a debug string do (eg) +// +// DbgLog((LOG_TRACE, n, TEXT("Value is %s"), (LPCTSTR)CDisp(ll, CDISP_HEX))); + + +class CDispBasic +{ +public: + CDispBasic() { m_pString = m_String; }; + ~CDispBasic(); +protected: + PTCHAR m_pString; // normally points to m_String... unless too much data + TCHAR m_String[50]; +}; +class CDisp : public CDispBasic +{ +public: + CDisp(LONGLONG ll, int Format = CDISP_HEX); // Display a LONGLONG in CDISP_HEX or CDISP_DEC form + CDisp(REFCLSID clsid); // Display a GUID + CDisp(double d); // Display a floating point number +#ifdef __strmif_h__ +#ifdef __STREAMS__ + CDisp(CRefTime t); // Display a Reference Time +#endif + CDisp(IPin *pPin); // Display a pin as {filter clsid}(pin name) + CDisp(IUnknown *pUnk); // Display a filter or pin +#endif // __strmif_h__ + ~CDisp(); + + // Implement cast to (LPCTSTR) as parameter to logger + operator LPCTSTR() + { + return (LPCTSTR)m_pString; + }; +}; + + +#if defined(DEBUG) +class CAutoTrace +{ +private: + LPCTSTR _szBlkName; + const int _level; + static const TCHAR _szEntering[]; + static const TCHAR _szLeaving[]; +public: + CAutoTrace(LPCTSTR szBlkName, const int level = 15) + : _szBlkName(szBlkName), _level(level) + {DbgLog((LOG_TRACE, _level, _szEntering, _szBlkName));} + + ~CAutoTrace() + {DbgLog((LOG_TRACE, _level, _szLeaving, _szBlkName));} +}; + +#if defined (__FUNCTION__) + +#define AMTRACEFN() CAutoTrace __trace(TEXT(__FUNCTION__)) +#define AMTRACE(_x_) CAutoTrace __trace(TEXT(__FUNCTION__)) + +#else + +#define AMTRACE(_x_) CAutoTrace __trace _x_ +#define AMTRACEFN() + +#endif + +#else + +#define AMTRACE(_x_) +#define AMTRACEFN() + +#endif + +#endif // __WXDEBUG__ + +//------------------------------------------------------------------------------ +// File: WXUtil.h +// +// Desc: DirectShow base classes - defines helper classes and functions for +// building multimedia filters. +// +// Copyright (c) 1992-2001 Microsoft Corporation. All rights reserved. +//------------------------------------------------------------------------------ + + +#ifndef __WXUTIL__ +#define __WXUTIL__ + +// eliminate spurious "statement has no effect" warnings. +#pragma warning(disable: 4705) + +// wrapper for whatever critical section we have +class CCritSec { + + // make copy constructor and assignment operator inaccessible + + CCritSec(const CCritSec &refCritSec); + CCritSec &operator=(const CCritSec &refCritSec); + + CRITICAL_SECTION m_CritSec; + +#ifdef DEBUG +public: + DWORD m_currentOwner; + DWORD m_lockCount; + BOOL m_fTrace; // Trace this one +public: + CCritSec(); + ~CCritSec(); + void Lock(); + void Unlock(); +#else + +public: + CCritSec() { + InitializeCriticalSection(&m_CritSec); + }; + + ~CCritSec() { + DeleteCriticalSection(&m_CritSec); + }; + + void Lock() { + EnterCriticalSection(&m_CritSec); + }; + + void Unlock() { + LeaveCriticalSection(&m_CritSec); + }; +#endif +}; + +// +// To make deadlocks easier to track it is useful to insert in the +// code an assertion that says whether we own a critical section or +// not. We make the routines that do the checking globals to avoid +// having different numbers of member functions in the debug and +// retail class implementations of CCritSec. In addition we provide +// a routine that allows usage of specific critical sections to be +// traced. This is NOT on by default - there are far too many. +// + +#ifdef DEBUG + BOOL WINAPI CritCheckIn(CCritSec * pcCrit); + BOOL WINAPI CritCheckIn(const CCritSec * pcCrit); + BOOL WINAPI CritCheckOut(CCritSec * pcCrit); + BOOL WINAPI CritCheckOut(const CCritSec * pcCrit); + void WINAPI DbgLockTrace(CCritSec * pcCrit, BOOL fTrace); +#else + #define CritCheckIn(x) TRUE + #define CritCheckOut(x) TRUE + #define DbgLockTrace(pc, fT) +#endif + + +// locks a critical section, and unlocks it automatically +// when the lock goes out of scope +class CAutoLock { + + // make copy constructor and assignment operator inaccessible + + CAutoLock(const CAutoLock &refAutoLock); + CAutoLock &operator=(const CAutoLock &refAutoLock); + +protected: + CCritSec * m_pLock; + +public: + CAutoLock(CCritSec * plock) + { + m_pLock = plock; + m_pLock->Lock(); + }; + + ~CAutoLock() { + m_pLock->Unlock(); + }; +}; + + + +// wrapper for event objects +class CAMEvent +{ + + // make copy constructor and assignment operator inaccessible + + CAMEvent(const CAMEvent &refEvent); + CAMEvent &operator=(const CAMEvent &refEvent); + +protected: + HANDLE m_hEvent; +public: + CAMEvent(BOOL fManualReset = FALSE, __inout_opt HRESULT *phr = NULL); + CAMEvent(__inout_opt HRESULT *phr); + ~CAMEvent(); + + // Cast to HANDLE - we don't support this as an lvalue + operator HANDLE () const { return m_hEvent; }; + + void Set() {EXECUTE_ASSERT(SetEvent(m_hEvent));}; + BOOL Wait(DWORD dwTimeout = INFINITE) { + return (WaitForSingleObject(m_hEvent, dwTimeout) == WAIT_OBJECT_0); + }; + void Reset() { ResetEvent(m_hEvent); }; + BOOL Check() { return Wait(0); }; +}; + + +// wrapper for event objects that do message processing +// This adds ONE method to the CAMEvent object to allow sent +// messages to be processed while waiting + +class CAMMsgEvent : public CAMEvent +{ + +public: + + CAMMsgEvent(__inout_opt HRESULT *phr = NULL); + + // Allow SEND messages to be processed while waiting + BOOL WaitMsg(DWORD dwTimeout = INFINITE); +}; + +// old name supported for the time being +#define CTimeoutEvent CAMEvent + +// support for a worker thread + +#ifdef AM_NOVTABLE +// simple thread class supports creation of worker thread, synchronization +// and communication. Can be derived to simplify parameter passing +class AM_NOVTABLE CAMThread { + + // make copy constructor and assignment operator inaccessible + + CAMThread(const CAMThread &refThread); + CAMThread &operator=(const CAMThread &refThread); + + CAMEvent m_EventSend; + CAMEvent m_EventComplete; + + DWORD m_dwParam; + DWORD m_dwReturnVal; + +protected: + HANDLE m_hThread; + + // thread will run this function on startup + // must be supplied by derived class + virtual DWORD ThreadProc() = 0; + +public: + CAMThread(__inout_opt HRESULT *phr = NULL); + virtual ~CAMThread(); + + CCritSec m_AccessLock; // locks access by client threads + CCritSec m_WorkerLock; // locks access to shared objects + + // thread initially runs this. param is actually 'this'. function + // just gets this and calls ThreadProc + static DWORD WINAPI InitialThreadProc(__inout LPVOID pv); + + // start thread running - error if already running + BOOL Create(); + + // signal the thread, and block for a response + // + DWORD CallWorker(DWORD); + + // accessor thread calls this when done with thread (having told thread + // to exit) + void Close() { + + // Disable warning: Conversion from LONG to PVOID of greater size +#pragma warning(push) +#pragma warning(disable: 4312) + HANDLE hThread = (HANDLE)InterlockedExchangePointer(&m_hThread, 0); +#pragma warning(pop) + + if (hThread) { + WaitForSingleObject(hThread, INFINITE); + CloseHandle(hThread); + } + }; + + // ThreadExists + // Return TRUE if the thread exists. FALSE otherwise + BOOL ThreadExists(void) const + { + if (m_hThread == 0) { + return FALSE; + } else { + return TRUE; + } + } + + // wait for the next request + DWORD GetRequest(); + + // is there a request? + BOOL CheckRequest(__out_opt DWORD * pParam); + + // reply to the request + void Reply(DWORD); + + // If you want to do WaitForMultipleObjects you'll need to include + // this handle in your wait list or you won't be responsive + HANDLE GetRequestHandle() const { return m_EventSend; }; + + // Find out what the request was + DWORD GetRequestParam() const { return m_dwParam; }; + + // call CoInitializeEx (COINIT_DISABLE_OLE1DDE) if + // available. S_FALSE means it's not available. + static HRESULT CoInitializeHelper(); +}; +#endif // AM_NOVTABLE + + +// CQueue +// +// Implements a simple Queue ADT. The queue contains a finite number of +// objects, access to which is controlled by a semaphore. The semaphore +// is created with an initial count (N). Each time an object is added +// a call to WaitForSingleObject is made on the semaphore's handle. When +// this function returns a slot has been reserved in the queue for the new +// object. If no slots are available the function blocks until one becomes +// available. Each time an object is removed from the queue ReleaseSemaphore +// is called on the semaphore's handle, thus freeing a slot in the queue. +// If no objects are present in the queue the function blocks until an +// object has been added. + +#define DEFAULT_QUEUESIZE 2 + +template class CQueue { +private: + HANDLE hSemPut; // Semaphore controlling queue "putting" + HANDLE hSemGet; // Semaphore controlling queue "getting" + CRITICAL_SECTION CritSect; // Thread seriallization + int nMax; // Max objects allowed in queue + int iNextPut; // Array index of next "PutMsg" + int iNextGet; // Array index of next "GetMsg" + T *QueueObjects; // Array of objects (ptr's to void) + + void Initialize(int n) { + iNextPut = iNextGet = 0; + nMax = n; + InitializeCriticalSection(&CritSect); + hSemPut = CreateSemaphore(NULL, n, n, NULL); + hSemGet = CreateSemaphore(NULL, 0, n, NULL); + QueueObjects = new T[n]; + } + + +public: + CQueue(int n) { + Initialize(n); + } + + CQueue() { + Initialize(DEFAULT_QUEUESIZE); + } + + ~CQueue() { + delete [] QueueObjects; + DeleteCriticalSection(&CritSect); + CloseHandle(hSemPut); + CloseHandle(hSemGet); + } + + T GetQueueObject() { + int iSlot; + T Object; + LONG lPrevious; + + // Wait for someone to put something on our queue, returns straight + // away is there is already an object on the queue. + // + WaitForSingleObject(hSemGet, INFINITE); + + EnterCriticalSection(&CritSect); + iSlot = iNextGet++ % nMax; + Object = QueueObjects[iSlot]; + LeaveCriticalSection(&CritSect); + + // Release anyone waiting to put an object onto our queue as there + // is now space available in the queue. + // + ReleaseSemaphore(hSemPut, 1L, &lPrevious); + return Object; + } + + void PutQueueObject(T Object) { + int iSlot; + LONG lPrevious; + + // Wait for someone to get something from our queue, returns straight + // away is there is already an empty slot on the queue. + // + WaitForSingleObject(hSemPut, INFINITE); + + EnterCriticalSection(&CritSect); + iSlot = iNextPut++ % nMax; + QueueObjects[iSlot] = Object; + LeaveCriticalSection(&CritSect); + + // Release anyone waiting to remove an object from our queue as there + // is now an object available to be removed. + // + ReleaseSemaphore(hSemGet, 1L, &lPrevious); + } +}; + +// Ensures that memory is not read past the length source buffer +// and that memory is not written past the length of the dst buffer +// dst - buffer to copy to +// dst_size - total size of destination buffer +// cb_dst_offset - offset, first byte copied to dst+cb_dst_offset +// src - buffer to copy from +// src_size - total size of source buffer +// cb_src_offset - offset, first byte copied from src+cb_src_offset +// count - number of bytes to copy +// +// Returns: +// S_OK - no error +// E_INVALIDARG - values passed would lead to overrun +HRESULT AMSafeMemMoveOffset( + __in_bcount(dst_size) void * dst, + __in size_t dst_size, + __in DWORD cb_dst_offset, + __in_bcount(src_size) const void * src, + __in size_t src_size, + __in DWORD cb_src_offset, + __in size_t count); + +extern "C" +void * __stdcall memmoveInternal(void *, const void *, size_t); + +inline void * __cdecl memchrInternal(const void *buf, int chr, size_t cnt) +{ +#ifdef _X86_ + void *pRet = NULL; + + _asm { + cld // make sure we get the direction right + mov ecx, cnt // num of bytes to scan + mov edi, buf // pointer byte stream + mov eax, chr // byte to scan for + repne scasb // look for the byte in the byte stream + jnz exit_memchr // Z flag set if byte found + dec edi // scasb always increments edi even when it + // finds the required byte + mov pRet, edi +exit_memchr: + } + return pRet; + +#else + while ( cnt && (*(unsigned char *)buf != (unsigned char)chr) ) { + buf = (unsigned char *)buf + 1; + cnt--; + } + + return(cnt ? (void *)buf : NULL); +#endif +} + +void WINAPI IntToWstr(int i, __out_ecount(12) LPWSTR wstr); + +#define WstrToInt(sz) _wtoi(sz) +#define atoiW(sz) _wtoi(sz) +#define atoiA(sz) atoi(sz) + +// These are available to help managing bitmap VIDEOINFOHEADER media structures + +extern const DWORD bits555[3]; +extern const DWORD bits565[3]; +extern const DWORD bits888[3]; + +// These help convert between VIDEOINFOHEADER and BITMAPINFO structures + +STDAPI_(const GUID) GetTrueColorType(const BITMAPINFOHEADER *pbmiHeader); +STDAPI_(const GUID) GetBitmapSubtype(const BITMAPINFOHEADER *pbmiHeader); +STDAPI_(WORD) GetBitCount(const GUID *pSubtype); + +// strmbase.lib implements this for compatibility with people who +// managed to link to this directly. we don't want to advertise it. +// +// STDAPI_(/* T */ CHAR *) GetSubtypeName(const GUID *pSubtype); + +STDAPI_(CHAR *) GetSubtypeNameA(const GUID *pSubtype); +STDAPI_(WCHAR *) GetSubtypeNameW(const GUID *pSubtype); + +#ifdef UNICODE +#define GetSubtypeName GetSubtypeNameW +#else +#define GetSubtypeName GetSubtypeNameA +#endif + +STDAPI_(LONG) GetBitmapFormatSize(const BITMAPINFOHEADER *pHeader); +STDAPI_(DWORD) GetBitmapSize(const BITMAPINFOHEADER *pHeader); + +#ifdef __AMVIDEO__ +STDAPI_(BOOL) ContainsPalette(const VIDEOINFOHEADER *pVideoInfo); +STDAPI_(const RGBQUAD *) GetBitmapPalette(const VIDEOINFOHEADER *pVideoInfo); +#endif // __AMVIDEO__ + + +// Compares two interfaces and returns TRUE if they are on the same object +BOOL WINAPI IsEqualObject(IUnknown *pFirst, IUnknown *pSecond); + +// This is for comparing pins +#define EqualPins(pPin1, pPin2) IsEqualObject(pPin1, pPin2) + + +// Arithmetic helper functions + +// Compute (a * b + rnd) / c +LONGLONG WINAPI llMulDiv(LONGLONG a, LONGLONG b, LONGLONG c, LONGLONG rnd); +LONGLONG WINAPI Int64x32Div32(LONGLONG a, LONG b, LONG c, LONG rnd); + + +// Avoids us dyna-linking to SysAllocString to copy BSTR strings +STDAPI WriteBSTR(__deref_out BSTR * pstrDest, LPCWSTR szSrc); +STDAPI FreeBSTR(__deref_in BSTR* pstr); + +// Return a wide string - allocating memory for it +// Returns: +// S_OK - no error +// E_POINTER - ppszReturn == NULL +// E_OUTOFMEMORY - can't allocate memory for returned string +STDAPI AMGetWideString(LPCWSTR pszString, __deref_out LPWSTR *ppszReturn); + +// Special wait for objects owning windows +DWORD WINAPI WaitDispatchingMessages( + HANDLE hObject, + DWORD dwWait, + HWND hwnd = NULL, + UINT uMsg = 0, + HANDLE hEvent = NULL); + +// HRESULT_FROM_WIN32 converts ERROR_SUCCESS to a success code, but in +// our use of HRESULT_FROM_WIN32, it typically means a function failed +// to call SetLastError(), and we still want a failure code. +// +#define AmHresultFromWin32(x) (MAKE_HRESULT(SEVERITY_ERROR, FACILITY_WIN32, x)) + +// call GetLastError and return an HRESULT value that will fail the +// SUCCEEDED() macro. +HRESULT AmGetLastErrorToHResult(void); + +// duplicate of ATL's CComPtr to avoid linker conflicts. + +IUnknown* QzAtlComPtrAssign(__deref_inout_opt IUnknown** pp, __in_opt IUnknown* lp); + +template +class QzCComPtr +{ +public: + typedef T _PtrClass; + QzCComPtr() {p=NULL;} + QzCComPtr(T* lp) + { + if ((p = lp) != NULL) + p->AddRef(); + } + QzCComPtr(const QzCComPtr& lp) + { + if ((p = lp.p) != NULL) + p->AddRef(); + } + ~QzCComPtr() {if (p) p->Release();} + void Release() {if (p) p->Release(); p=NULL;} + operator T*() {return (T*)p;} + T& operator*() {ASSERT(p!=NULL); return *p; } + //The assert on operator& usually indicates a bug. If this is really + //what is needed, however, take the address of the p member explicitly. + T** operator&() { ASSERT(p==NULL); return &p; } + T* operator->() { ASSERT(p!=NULL); return p; } + T* operator=(T* lp){return (T*)QzAtlComPtrAssign((IUnknown**)&p, lp);} + T* operator=(const QzCComPtr& lp) + { + return (T*)QzAtlComPtrAssign((IUnknown**)&p, lp.p); + } +#if _MSC_VER>1020 + bool operator!(){return (p == NULL);} +#else + BOOL operator!(){return (p == NULL) ? TRUE : FALSE;} +#endif + T* p; +}; + +MMRESULT CompatibleTimeSetEvent( UINT uDelay, UINT uResolution, __in LPTIMECALLBACK lpTimeProc, DWORD_PTR dwUser, UINT fuEvent ); +bool TimeKillSynchronousFlagAvailable( void ); + +// Helper to replace lstrcpmi +__inline int lstrcmpiLocaleIndependentW(LPCWSTR lpsz1, LPCWSTR lpsz2) +{ + return CompareStringW(LOCALE_INVARIANT, NORM_IGNORECASE, lpsz1, -1, lpsz2, -1) - CSTR_EQUAL; +} +__inline int lstrcmpiLocaleIndependentA(LPCSTR lpsz1, LPCSTR lpsz2) +{ + return CompareStringA(LOCALE_INVARIANT, NORM_IGNORECASE, lpsz1, -1, lpsz2, -1) - CSTR_EQUAL; +} + +#endif /* __WXUTIL__ */ + +//------------------------------------------------------------------------------ +// File: ComBase.h +// +// Desc: DirectShow base classes - defines a class hierarchy for creating +// COM objects. +// +// Copyright (c) 1992-2001 Microsoft Corporation. All rights reserved. +//------------------------------------------------------------------------------ + + +/* + +a. Derive your COM object from CUnknown + +b. Make a static CreateInstance function that takes an LPUNKNOWN, an HRESULT * + and a TCHAR *. The LPUNKNOWN defines the object to delegate IUnknown calls + to. The HRESULT * allows error codes to be passed around constructors and + the TCHAR * is a descriptive name that can be printed on the debugger. + + It is important that constructors only change the HRESULT * if they have + to set an ERROR code, if it was successful then leave it alone or you may + overwrite an error code from an object previously created. + + When you call a constructor the descriptive name should be in static store + as we do not copy the string. To stop large amounts of memory being used + in retail builds by all these static strings use the NAME macro, + + CMyFilter = new CImplFilter(NAME("My filter"),pUnknown,phr); + if (FAILED(hr)) { + return hr; + } + + In retail builds NAME(_x_) compiles to NULL, the base CBaseObject class + knows not to do anything with objects that don't have a name. + +c. Have a constructor for your object that passes the LPUNKNOWN, HRESULT * and + TCHAR * to the CUnknown constructor. You can set the HRESULT if you have an + error, or just simply pass it through to the constructor. + + The object creation will fail in the class factory if the HRESULT indicates + an error (ie FAILED(HRESULT) == TRUE) + +d. Create a FactoryTemplate with your object's class id and CreateInstance + function. + +Then (for each interface) either + +Multiple inheritance + +1. Also derive it from ISomeInterface +2. Include DECLARE_IUNKNOWN in your class definition to declare + implementations of QueryInterface, AddRef and Release that + call the outer unknown +3. Override NonDelegatingQueryInterface to expose ISomeInterface by + code something like + + if (riid == IID_ISomeInterface) { + return GetInterface((ISomeInterface *) this, ppv); + } else { + return CUnknown::NonDelegatingQueryInterface(riid, ppv); + } + +4. Declare and implement the member functions of ISomeInterface. + +or: Nested interfaces + +1. Declare a class derived from CUnknown +2. Include DECLARE_IUNKNOWN in your class definition +3. Override NonDelegatingQueryInterface to expose ISomeInterface by + code something like + + if (riid == IID_ISomeInterface) { + return GetInterface((ISomeInterface *) this, ppv); + } else { + return CUnknown::NonDelegatingQueryInterface(riid, ppv); + } + +4. Implement the member functions of ISomeInterface. Use GetOwner() to + access the COM object class. + +And in your COM object class: + +5. Make the nested class a friend of the COM object class, and declare + an instance of the nested class as a member of the COM object class. + + NOTE that because you must always pass the outer unknown and an hResult + to the CUnknown constructor you cannot use a default constructor, in + other words you will have to make the member variable a pointer to the + class and make a NEW call in your constructor to actually create it. + +6. override the NonDelegatingQueryInterface with code like this: + + if (riid == IID_ISomeInterface) { + return m_pImplFilter-> + NonDelegatingQueryInterface(IID_ISomeInterface, ppv); + } else { + return CUnknown::NonDelegatingQueryInterface(riid, ppv); + } + +You can have mixed classes which support some interfaces via multiple +inheritance and some via nested classes + +*/ + +#ifndef __COMBASE__ +#define __COMBASE__ + +// Filter Setup data structures no defined in axextend.idl + +typedef REGPINTYPES +AMOVIESETUP_MEDIATYPE, * PAMOVIESETUP_MEDIATYPE, * FAR LPAMOVIESETUP_MEDIATYPE; + +typedef REGFILTERPINS +AMOVIESETUP_PIN, * PAMOVIESETUP_PIN, * FAR LPAMOVIESETUP_PIN; + +typedef struct _AMOVIESETUP_FILTER +{ + const CLSID * clsID; + const WCHAR * strName; + DWORD dwMerit; + UINT nPins; + const AMOVIESETUP_PIN * lpPin; +} +AMOVIESETUP_FILTER, * PAMOVIESETUP_FILTER, * FAR LPAMOVIESETUP_FILTER; + +/* The DLLENTRY module initialises the module handle on loading */ + +extern HINSTANCE g_hInst; + +/* On DLL load remember which platform we are running on */ + +extern DWORD g_amPlatform; +extern OSVERSIONINFO g_osInfo; // Filled in by GetVersionEx + +/* Version of IUnknown that is renamed to allow a class to support both + non delegating and delegating IUnknowns in the same COM object */ + +#ifndef INONDELEGATINGUNKNOWN_DEFINED +DECLARE_INTERFACE(INonDelegatingUnknown) +{ + STDMETHOD(NonDelegatingQueryInterface) (THIS_ REFIID, LPVOID *) PURE; + STDMETHOD_(ULONG, NonDelegatingAddRef)(THIS) PURE; + STDMETHOD_(ULONG, NonDelegatingRelease)(THIS) PURE; +}; +#define INONDELEGATINGUNKNOWN_DEFINED +#endif + +typedef INonDelegatingUnknown *PNDUNKNOWN; + + +/* This is the base object class that supports active object counting. As + part of the debug facilities we trace every time a C++ object is created + or destroyed. The name of the object has to be passed up through the class + derivation list during construction as you cannot call virtual functions + in the constructor. The downside of all this is that every single object + constructor has to take an object name parameter that describes it */ + +class CBaseObject +{ + +private: + + // Disable the copy constructor and assignment by default so you will get + // compiler errors instead of unexpected behaviour if you pass objects + // by value or assign objects. + CBaseObject(const CBaseObject& objectSrc); // no implementation + void operator=(const CBaseObject& objectSrc); // no implementation + +private: + static LONG m_cObjects; /* Total number of objects active */ + +protected: +#ifdef DEBUG + DWORD m_dwCookie; /* Cookie identifying this object */ +#endif + + +public: + + /* These increment and decrement the number of active objects */ + + CBaseObject(__in_opt LPCTSTR pName); +#ifdef UNICODE + CBaseObject(__in_opt LPCSTR pName); +#endif + ~CBaseObject(); + + /* Call this to find if there are any CUnknown derived objects active */ + + static LONG ObjectsActive() { + return m_cObjects; + }; +}; + + +/* An object that supports one or more COM interfaces will be based on + this class. It supports counting of total objects for DLLCanUnloadNow + support, and an implementation of the core non delegating IUnknown */ + +class AM_NOVTABLE CUnknown : public INonDelegatingUnknown, + public CBaseObject +{ +private: + const LPUNKNOWN m_pUnknown; /* Owner of this object */ + +protected: /* So we can override NonDelegatingRelease() */ + volatile LONG m_cRef; /* Number of reference counts */ + +public: + + CUnknown(__in_opt LPCTSTR pName, __in_opt LPUNKNOWN pUnk); + virtual ~CUnknown() {}; + + // This is redundant, just use the other constructor + // as we never touch the HRESULT in this anyway + CUnknown(__in_opt LPCTSTR Name, __in_opt LPUNKNOWN pUnk, __inout_opt HRESULT *phr); +#ifdef UNICODE + CUnknown(__in_opt LPCSTR pName, __in_opt LPUNKNOWN pUnk); + CUnknown(__in_opt LPCSTR pName, __in_opt LPUNKNOWN pUnk,__inout_opt HRESULT *phr); +#endif + + /* Return the owner of this object */ + + LPUNKNOWN GetOwner() const { + return m_pUnknown; + }; + + /* Called from the class factory to create a new instance, it is + pure virtual so it must be overriden in your derived class */ + + /* static CUnknown *CreateInstance(LPUNKNOWN, HRESULT *) */ + + /* Non delegating unknown implementation */ + + STDMETHODIMP NonDelegatingQueryInterface(REFIID, __deref_out void **); + STDMETHODIMP_(ULONG) NonDelegatingAddRef(); + STDMETHODIMP_(ULONG) NonDelegatingRelease(); +}; + +/* Return an interface pointer to a requesting client + performing a thread safe AddRef as necessary */ + +STDAPI GetInterface(LPUNKNOWN pUnk, __out void **ppv); + +/* A function that can create a new COM object */ + +typedef CUnknown *(CALLBACK *LPFNNewCOMObject)(__in_opt LPUNKNOWN pUnkOuter, __inout_opt HRESULT *phr); + +/* A function (can be NULL) which is called from the DLL entrypoint + routine for each factory template: + + bLoading - TRUE on DLL load, FALSE on DLL unload + rclsid - the m_ClsID of the entry +*/ +typedef void (CALLBACK *LPFNInitRoutine)(BOOL bLoading, const CLSID *rclsid); + +/* Create one of these per object class in an array so that + the default class factory code can create new instances */ + +class CFactoryTemplate { + +public: + + const WCHAR * m_Name; + const CLSID * m_ClsID; + LPFNNewCOMObject m_lpfnNew; + LPFNInitRoutine m_lpfnInit; + const AMOVIESETUP_FILTER * m_pAMovieSetup_Filter; + + BOOL IsClassID(REFCLSID rclsid) const { + return (IsEqualCLSID(*m_ClsID,rclsid)); + }; + + CUnknown *CreateInstance(__inout_opt LPUNKNOWN pUnk, __inout_opt HRESULT *phr) const { + CheckPointer(phr,NULL); + return m_lpfnNew(pUnk, phr); + }; +}; + + +/* You must override the (pure virtual) NonDelegatingQueryInterface to return + interface pointers (using GetInterface) to the interfaces your derived + class supports (the default implementation only supports IUnknown) */ + +#define DECLARE_IUNKNOWN \ + STDMETHODIMP QueryInterface(REFIID riid, __deref_out void **ppv) { \ + return GetOwner()->QueryInterface(riid,ppv); \ + }; \ + STDMETHODIMP_(ULONG) AddRef() { \ + return GetOwner()->AddRef(); \ + }; \ + STDMETHODIMP_(ULONG) Release() { \ + return GetOwner()->Release(); \ + }; + + + +HINSTANCE LoadOLEAut32(); + + +#endif /* __COMBASE__ */ + +//------------------------------------------------------------------------------ +// File: WXList.h +// +// Desc: DirectShow base classes - defines a non-MFC generic template list +// class. +// +// Copyright (c) 1992-2001 Microsoft Corporation. All rights reserved. +//------------------------------------------------------------------------------ + + +/* A generic list of pointers to objects. + No storage management or copying is done on the objects pointed to. + Objectives: avoid using MFC libraries in ndm kernel mode and + provide a really useful list type. + + The class is thread safe in that separate threads may add and + delete items in the list concurrently although the application + must ensure that constructor and destructor access is suitably + synchronised. An application can cause deadlock with operations + which use two lists by simultaneously calling + list1->Operation(list2) and list2->Operation(list1). So don't! + + The names must not conflict with MFC classes as an application + may use both. + */ + +#ifndef __WXLIST__ +#define __WXLIST__ + + /* A POSITION represents (in some fashion that's opaque) a cursor + on the list that can be set to identify any element. NULL is + a valid value and several operations regard NULL as the position + "one step off the end of the list". (In an n element list there + are n+1 places to insert and NULL is that "n+1-th" value). + The POSITION of an element in the list is only invalidated if + that element is deleted. Move operations may mean that what + was a valid POSITION in one list is now a valid POSITION in + a different list. + + Some operations which at first sight are illegal are allowed as + harmless no-ops. For instance RemoveHead is legal on an empty + list and it returns NULL. This allows an atomic way to test if + there is an element there, and if so, get it. The two operations + AddTail and RemoveHead thus implement a MONITOR (See Hoare's paper). + + Single element operations return POSITIONs, non-NULL means it worked. + whole list operations return a BOOL. TRUE means it all worked. + + This definition is the same as the POSITION type for MFCs, so we must + avoid defining it twice. + */ +#ifndef __AFX_H__ +struct __POSITION { int unused; }; +typedef __POSITION* POSITION; +#endif + +const int DEFAULTCACHE = 10; /* Default node object cache size */ + +/* A class representing one node in a list. + Each node knows a pointer to it's adjacent nodes and also a pointer + to the object that it looks after. + All of these pointers can be retrieved or set through member functions. +*/ +class CBaseList +#ifdef DEBUG + : public CBaseObject +#endif +{ + /* Making these classes inherit from CBaseObject does nothing + functionally but it allows us to check there are no memory + leaks in debug builds. + */ + +public: + +#ifdef DEBUG + class CNode : public CBaseObject { +#else + class CNode { +#endif + + CNode *m_pPrev; /* Previous node in the list */ + CNode *m_pNext; /* Next node in the list */ + void *m_pObject; /* Pointer to the object */ + + public: + + /* Constructor - initialise the object's pointers */ + CNode() +#ifdef DEBUG + : CBaseObject(NAME("List node")) +#endif + { + }; + + + /* Return the previous node before this one */ + __out CNode *Prev() const { return m_pPrev; }; + + + /* Return the next node after this one */ + __out CNode *Next() const { return m_pNext; }; + + + /* Set the previous node before this one */ + void SetPrev(__in_opt CNode *p) { m_pPrev = p; }; + + + /* Set the next node after this one */ + void SetNext(__in_opt CNode *p) { m_pNext = p; }; + + + /* Get the pointer to the object for this node */ + __out void *GetData() const { return m_pObject; }; + + + /* Set the pointer to the object for this node */ + void SetData(__in void *p) { m_pObject = p; }; + }; + + class CNodeCache + { + public: + CNodeCache(INT iCacheSize) : m_iCacheSize(iCacheSize), + m_pHead(NULL), + m_iUsed(0) + {}; + ~CNodeCache() { + CNode *pNode = m_pHead; + while (pNode) { + CNode *pCurrent = pNode; + pNode = pNode->Next(); + delete pCurrent; + } + }; + void AddToCache(__inout CNode *pNode) + { + if (m_iUsed < m_iCacheSize) { + pNode->SetNext(m_pHead); + m_pHead = pNode; + m_iUsed++; + } else { + delete pNode; + } + }; + CNode *RemoveFromCache() + { + CNode *pNode = m_pHead; + if (pNode != NULL) { + m_pHead = pNode->Next(); + m_iUsed--; + ASSERT(m_iUsed >= 0); + } else { + ASSERT(m_iUsed == 0); + } + return pNode; + }; + private: + INT m_iCacheSize; + INT m_iUsed; + CNode *m_pHead; + }; + +protected: + + CNode* m_pFirst; /* Pointer to first node in the list */ + CNode* m_pLast; /* Pointer to the last node in the list */ + LONG m_Count; /* Number of nodes currently in the list */ + +private: + + CNodeCache m_Cache; /* Cache of unused node pointers */ + +private: + + /* These override the default copy constructor and assignment + operator for all list classes. They are in the private class + declaration section so that anybody trying to pass a list + object by value will generate a compile time error of + "cannot access the private member function". If these were + not here then the compiler will create default constructors + and assignment operators which when executed first take a + copy of all member variables and then during destruction + delete them all. This must not be done for any heap + allocated data. + */ + CBaseList(const CBaseList &refList); + CBaseList &operator=(const CBaseList &refList); + +public: + + CBaseList(__in_opt LPCTSTR pName, + INT iItems); + + CBaseList(__in_opt LPCTSTR pName); +#ifdef UNICODE + CBaseList(__in_opt LPCSTR pName, + INT iItems); + + CBaseList(__in_opt LPCSTR pName); +#endif + ~CBaseList(); + + /* Remove all the nodes from *this i.e. make the list empty */ + void RemoveAll(); + + + /* Return a cursor which identifies the first element of *this */ + __out_opt POSITION GetHeadPositionI() const; + + + /* Return a cursor which identifies the last element of *this */ + __out_opt POSITION GetTailPositionI() const; + + + /* Return the number of objects in *this */ + int GetCountI() const; + +protected: + /* Return the pointer to the object at rp, + Update rp to the next node in *this + but make it NULL if it was at the end of *this. + This is a wart retained for backwards compatibility. + GetPrev is not implemented. + Use Next, Prev and Get separately. + */ + __out void *GetNextI(__inout POSITION& rp) const; + + + /* Return a pointer to the object at p + Asking for the object at NULL will return NULL harmlessly. + */ + __out_opt void *GetI(__in_opt POSITION p) const; + __out void *GetValidI(__in POSITION p) const; + +public: + /* return the next / prev position in *this + return NULL when going past the end/start. + Next(NULL) is same as GetHeadPosition() + Prev(NULL) is same as GetTailPosition() + An n element list therefore behaves like a n+1 element + cycle with NULL at the start/end. + + !!WARNING!! - This handling of NULL is DIFFERENT from GetNext. + + Some reasons are: + 1. For a list of n items there are n+1 positions to insert + These are conveniently encoded as the n POSITIONs and NULL. + 2. If you are keeping a list sorted (fairly common) and you + search forward for an element to insert before and don't + find it you finish up with NULL as the element before which + to insert. You then want that NULL to be a valid POSITION + so that you can insert before it and you want that insertion + point to mean the (n+1)-th one that doesn't have a POSITION. + (symmetrically if you are working backwards through the list). + 3. It simplifies the algebra which the methods generate. + e.g. AddBefore(p,x) is identical to AddAfter(Prev(p),x) + in ALL cases. All the other arguments probably are reflections + of the algebraic point. + */ + __out_opt POSITION Next(__in_opt POSITION pos) const + { + if (pos == NULL) { + return (POSITION) m_pFirst; + } + CNode *pn = (CNode *) pos; + return (POSITION) pn->Next(); + } //Next + + // See Next + __out_opt POSITION Prev(__in_opt POSITION pos) const + { + if (pos == NULL) { + return (POSITION) m_pLast; + } + CNode *pn = (CNode *) pos; + return (POSITION) pn->Prev(); + } //Prev + + + /* Return the first position in *this which holds the given + pointer. Return NULL if the pointer was not not found. + */ +protected: + __out_opt POSITION FindI( __in void * pObj) const; + + // ??? Should there be (or even should there be only) + // ??? POSITION FindNextAfter(void * pObj, POSITION p) + // ??? And of course FindPrevBefore too. + // ??? List.Find(&Obj) then becomes List.FindNextAfter(&Obj, NULL) + + + /* Remove the first node in *this (deletes the pointer to its + object from the list, does not free the object itself). + Return the pointer to its object. + If *this was already empty it will harmlessly return NULL. + */ + __out_opt void *RemoveHeadI(); + + + /* Remove the last node in *this (deletes the pointer to its + object from the list, does not free the object itself). + Return the pointer to its object. + If *this was already empty it will harmlessly return NULL. + */ + __out_opt void *RemoveTailI(); + + + /* Remove the node identified by p from the list (deletes the pointer + to its object from the list, does not free the object itself). + Asking to Remove the object at NULL will harmlessly return NULL. + Return the pointer to the object removed. + */ + __out_opt void *RemoveI(__in_opt POSITION p); + + /* Add single object *pObj to become a new last element of the list. + Return the new tail position, NULL if it fails. + If you are adding a COM objects, you might want AddRef it first. + Other existing POSITIONs in *this are still valid + */ + __out_opt POSITION AddTailI(__in void * pObj); +public: + + + /* Add all the elements in *pList to the tail of *this. + This duplicates all the nodes in *pList (i.e. duplicates + all its pointers to objects). It does not duplicate the objects. + If you are adding a list of pointers to a COM object into the list + it's a good idea to AddRef them all it when you AddTail it. + Return TRUE if it all worked, FALSE if it didn't. + If it fails some elements may have been added. + Existing POSITIONs in *this are still valid + + If you actually want to MOVE the elements, use MoveToTail instead. + */ + BOOL AddTail(__in CBaseList *pList); + + + /* Mirror images of AddHead: */ + + /* Add single object to become a new first element of the list. + Return the new head position, NULL if it fails. + Existing POSITIONs in *this are still valid + */ +protected: + __out_opt POSITION AddHeadI(__in void * pObj); +public: + + /* Add all the elements in *pList to the head of *this. + Same warnings apply as for AddTail. + Return TRUE if it all worked, FALSE if it didn't. + If it fails some of the objects may have been added. + + If you actually want to MOVE the elements, use MoveToHead instead. + */ + BOOL AddHead(__in CBaseList *pList); + + + /* Add the object *pObj to *this after position p in *this. + AddAfter(NULL,x) adds x to the start - equivalent to AddHead + Return the position of the object added, NULL if it failed. + Existing POSITIONs in *this are undisturbed, including p. + */ +protected: + __out_opt POSITION AddAfterI(__in_opt POSITION p, __in void * pObj); +public: + + /* Add the list *pList to *this after position p in *this + AddAfter(NULL,x) adds x to the start - equivalent to AddHead + Return TRUE if it all worked, FALSE if it didn't. + If it fails, some of the objects may be added + Existing POSITIONs in *this are undisturbed, including p. + */ + BOOL AddAfter(__in_opt POSITION p, __in CBaseList *pList); + + + /* Mirror images: + Add the object *pObj to this-List after position p in *this. + AddBefore(NULL,x) adds x to the end - equivalent to AddTail + Return the position of the new object, NULL if it fails + Existing POSITIONs in *this are undisturbed, including p. + */ + protected: + __out_opt POSITION AddBeforeI(__in_opt POSITION p, __in void * pObj); + public: + + /* Add the list *pList to *this before position p in *this + AddAfter(NULL,x) adds x to the start - equivalent to AddHead + Return TRUE if it all worked, FALSE if it didn't. + If it fails, some of the objects may be added + Existing POSITIONs in *this are undisturbed, including p. + */ + BOOL AddBefore(__in_opt POSITION p, __in CBaseList *pList); + + + /* Note that AddAfter(p,x) is equivalent to AddBefore(Next(p),x) + even in cases where p is NULL or Next(p) is NULL. + Similarly for mirror images etc. + This may make it easier to argue about programs. + */ + + + + /* The following operations do not copy any elements. + They move existing blocks of elements around by switching pointers. + They are fairly efficient for long lists as for short lists. + (Alas, the Count slows things down). + + They split the list into two parts. + One part remains as the original list, the other part + is appended to the second list. There are eight possible + variations: + Split the list {after/before} a given element + keep the {head/tail} portion in the original list + append the rest to the {head/tail} of the new list. + + Since After is strictly equivalent to Before Next + we are not in serious need of the Before/After variants. + That leaves only four. + + If you are processing a list left to right and dumping + the bits that you have processed into another list as + you go, the Tail/Tail variant gives the most natural result. + If you are processing in reverse order, Head/Head is best. + + By using NULL positions and empty lists judiciously either + of the other two can be built up in two operations. + + The definition of NULL (see Next/Prev etc) means that + degenerate cases include + "move all elements to new list" + "Split a list into two lists" + "Concatenate two lists" + (and quite a few no-ops) + + !!WARNING!! The type checking won't buy you much if you get list + positions muddled up - e.g. use a POSITION that's in a different + list and see what a mess you get! + */ + + /* Split *this after position p in *this + Retain as *this the tail portion of the original *this + Add the head portion to the tail end of *pList + Return TRUE if it all worked, FALSE if it didn't. + + e.g. + foo->MoveToTail(foo->GetHeadPosition(), bar); + moves one element from the head of foo to the tail of bar + foo->MoveToTail(NULL, bar); + is a no-op, returns NULL + foo->MoveToTail(foo->GetTailPosition, bar); + concatenates foo onto the end of bar and empties foo. + + A better, except excessively long name might be + MoveElementsFromHeadThroughPositionToOtherTail + */ + BOOL MoveToTail(__in_opt POSITION pos, __in CBaseList *pList); + + + /* Mirror image: + Split *this before position p in *this. + Retain in *this the head portion of the original *this + Add the tail portion to the start (i.e. head) of *pList + + e.g. + foo->MoveToHead(foo->GetTailPosition(), bar); + moves one element from the tail of foo to the head of bar + foo->MoveToHead(NULL, bar); + is a no-op, returns NULL + foo->MoveToHead(foo->GetHeadPosition, bar); + concatenates foo onto the start of bar and empties foo. + */ + BOOL MoveToHead(__in_opt POSITION pos, __in CBaseList *pList); + + + /* Reverse the order of the [pointers to] objects in *this + */ + void Reverse(); + + + /* set cursor to the position of each element of list in turn */ + #define TRAVERSELIST(list, cursor) \ + for ( cursor = (list).GetHeadPosition() \ + ; cursor!=NULL \ + ; cursor = (list).Next(cursor) \ + ) + + + /* set cursor to the position of each element of list in turn + in reverse order + */ + #define REVERSETRAVERSELIST(list, cursor) \ + for ( cursor = (list).GetTailPosition() \ + ; cursor!=NULL \ + ; cursor = (list).Prev(cursor) \ + ) + +}; // end of class declaration + +template class CGenericList : public CBaseList +{ +public: + CGenericList(__in_opt LPCTSTR pName, + INT iItems, + BOOL bLock = TRUE, + BOOL bAlert = FALSE) : + CBaseList(pName, iItems) { + UNREFERENCED_PARAMETER(bAlert); + UNREFERENCED_PARAMETER(bLock); + }; + CGenericList(__in_opt LPCTSTR pName) : + CBaseList(pName) { + }; + + __out_opt POSITION GetHeadPosition() const { return (POSITION)m_pFirst; } + __out_opt POSITION GetTailPosition() const { return (POSITION)m_pLast; } + int GetCount() const { return m_Count; } + + __out OBJECT *GetNext(__inout POSITION& rp) const { return (OBJECT *) GetNextI(rp); } + + __out_opt OBJECT *Get(__in_opt POSITION p) const { return (OBJECT *) GetI(p); } + __out OBJECT *GetValid(__in POSITION p) const { return (OBJECT *) GetValidI(p); } + __out_opt OBJECT *GetHead() const { return Get(GetHeadPosition()); } + + __out_opt OBJECT *RemoveHead() { return (OBJECT *) RemoveHeadI(); } + + __out_opt OBJECT *RemoveTail() { return (OBJECT *) RemoveTailI(); } + + __out_opt OBJECT *Remove(__in_opt POSITION p) { return (OBJECT *) RemoveI(p); } + __out_opt POSITION AddBefore(__in_opt POSITION p, __in OBJECT * pObj) { return AddBeforeI(p, pObj); } + __out_opt POSITION AddAfter(__in_opt POSITION p, __in OBJECT * pObj) { return AddAfterI(p, pObj); } + __out_opt POSITION AddHead(__in OBJECT * pObj) { return AddHeadI(pObj); } + __out_opt POSITION AddTail(__in OBJECT * pObj) { return AddTailI(pObj); } + BOOL AddTail(__in CGenericList *pList) + { return CBaseList::AddTail((CBaseList *) pList); } + BOOL AddHead(__in CGenericList *pList) + { return CBaseList::AddHead((CBaseList *) pList); } + BOOL AddAfter(__in_opt POSITION p, __in CGenericList *pList) + { return CBaseList::AddAfter(p, (CBaseList *) pList); }; + BOOL AddBefore(__in_opt POSITION p, __in CGenericList *pList) + { return CBaseList::AddBefore(p, (CBaseList *) pList); }; + __out_opt POSITION Find( __in OBJECT * pObj) const { return FindI(pObj); } +}; // end of class declaration + + + +/* These define the standard list types */ + +typedef CGenericList CBaseObjectList; +typedef CGenericList CBaseInterfaceList; + +#endif /* __WXLIST__ */ + +//------------------------------------------------------------------------------ +// File: MtType.h +// +// Desc: DirectShow base classes - defines a class that holds and manages +// media type information. +// +// Copyright (c) 1992-2001 Microsoft Corporation. All rights reserved. +//------------------------------------------------------------------------------ + + +#ifndef __MTYPE__ +#define __MTYPE__ + +/* Helper class that derived pin objects can use to compare media + types etc. Has same data members as the struct AM_MEDIA_TYPE defined + in the streams IDL file, but also has (non-virtual) functions */ + +class CMediaType : public _AMMediaType { + +public: + + ~CMediaType(); + CMediaType(); + CMediaType(const GUID * majortype); + CMediaType(const AM_MEDIA_TYPE&, __out_opt HRESULT* phr = NULL); + CMediaType(const CMediaType&, __out_opt HRESULT* phr = NULL); + + CMediaType& operator=(const CMediaType&); + CMediaType& operator=(const AM_MEDIA_TYPE&); + + BOOL operator == (const CMediaType&) const; + BOOL operator != (const CMediaType&) const; + + HRESULT Set(const CMediaType& rt); + HRESULT Set(const AM_MEDIA_TYPE& rt); + + BOOL IsValid() const; + + const GUID *Type() const { return &majortype;} ; + void SetType(const GUID *); + const GUID *Subtype() const { return &subtype;} ; + void SetSubtype(const GUID *); + + BOOL IsFixedSize() const {return bFixedSizeSamples; }; + BOOL IsTemporalCompressed() const {return bTemporalCompression; }; + ULONG GetSampleSize() const; + + void SetSampleSize(ULONG sz); + void SetVariableSize(); + void SetTemporalCompression(BOOL bCompressed); + + // read/write pointer to format - can't change length without + // calling SetFormat, AllocFormatBuffer or ReallocFormatBuffer + + BYTE* Format() const {return pbFormat; }; + ULONG FormatLength() const { return cbFormat; }; + + void SetFormatType(const GUID *); + const GUID *FormatType() const {return &formattype; }; + BOOL SetFormat(__in_bcount(length) BYTE *pFormat, ULONG length); + void ResetFormatBuffer(); + BYTE* AllocFormatBuffer(ULONG length); + BYTE* ReallocFormatBuffer(ULONG length); + + void InitMediaType(); + + BOOL MatchesPartial(const CMediaType* ppartial) const; + BOOL IsPartiallySpecified(void) const; +}; + + +/* General purpose functions to copy and delete a task allocated AM_MEDIA_TYPE + structure which is useful when using the IEnumMediaFormats interface as + the implementation allocates the structures which you must later delete */ + +void WINAPI DeleteMediaType(__inout_opt AM_MEDIA_TYPE *pmt); +AM_MEDIA_TYPE * WINAPI CreateMediaType(AM_MEDIA_TYPE const *pSrc); +HRESULT WINAPI CopyMediaType(__out AM_MEDIA_TYPE *pmtTarget, const AM_MEDIA_TYPE *pmtSource); +void WINAPI FreeMediaType(__inout AM_MEDIA_TYPE& mt); + +// Initialize a media type from a WAVEFORMATEX + +STDAPI CreateAudioMediaType( + const WAVEFORMATEX *pwfx, + __out AM_MEDIA_TYPE *pmt, + BOOL bSetFormat); + +#endif /* __MTYPE__ */ + +//------------------------------------------------------------------------------ +// File: AMFilter.h +// +// Desc: DirectShow base classes - efines class hierarchy for streams +// architecture. +// +// Copyright (c) 1992-2001 Microsoft Corporation. All rights reserved. +//------------------------------------------------------------------------------ + + +#ifndef __FILTER__ +#define __FILTER__ + +/* The following classes are declared in this header: */ + +class CBaseMediaFilter; // IMediaFilter support +class CBaseFilter; // IBaseFilter,IMediaFilter support +class CBasePin; // Abstract base class for IPin interface +class CEnumPins; // Enumerate input and output pins +class CEnumMediaTypes; // Enumerate the pin's preferred formats +class CBaseOutputPin; // Adds data provider member functions +class CBaseInputPin; // Implements IMemInputPin interface +class CMediaSample; // Basic transport unit for IMemInputPin +class CBaseAllocator; // General list guff for most allocators +class CMemAllocator; // Implements memory buffer allocation + + +//===================================================================== +//===================================================================== +// +// QueryFilterInfo and QueryPinInfo AddRef the interface pointers +// they return. You can use the macro below to release the interface. +// +//===================================================================== +//===================================================================== + +#define QueryFilterInfoReleaseGraph(fi) if ((fi).pGraph) (fi).pGraph->Release(); + +#define QueryPinInfoReleaseFilter(pi) if ((pi).pFilter) (pi).pFilter->Release(); + +//===================================================================== +//===================================================================== +// Defines CBaseMediaFilter +// +// Abstract base class implementing IMediaFilter. +// +// Typically you will derive your filter from CBaseFilter rather than +// this, unless you are implementing an object such as a plug-in +// distributor that needs to support IMediaFilter but not IBaseFilter. +// +// Note that IMediaFilter is derived from IPersist to allow query of +// class id. +//===================================================================== +//===================================================================== + +class AM_NOVTABLE CBaseMediaFilter : public CUnknown, + public IMediaFilter +{ + +protected: + + FILTER_STATE m_State; // current state: running, paused + IReferenceClock *m_pClock; // this filter's reference clock + // note: all filters in a filter graph use the same clock + + // offset from stream time to reference time + CRefTime m_tStart; + + CLSID m_clsid; // This filters clsid + // used for serialization + CCritSec *m_pLock; // Object we use for locking + +public: + + CBaseMediaFilter( + __in_opt LPCTSTR pName, + __inout_opt LPUNKNOWN pUnk, + __in CCritSec *pLock, + REFCLSID clsid); + + virtual ~CBaseMediaFilter(); + + DECLARE_IUNKNOWN + + // override this to say what interfaces we support where + STDMETHODIMP NonDelegatingQueryInterface(REFIID riid, __deref_out void ** ppv); + + // + // --- IPersist method --- + // + + STDMETHODIMP GetClassID(__out CLSID *pClsID); + + // --- IMediaFilter methods --- + + STDMETHODIMP GetState(DWORD dwMSecs, __out FILTER_STATE *State); + + STDMETHODIMP SetSyncSource(__inout_opt IReferenceClock *pClock); + + STDMETHODIMP GetSyncSource(__deref_out_opt IReferenceClock **pClock); + + // default implementation of Stop and Pause just record the + // state. Override to activate or de-activate your filter. + // Note that Run when called from Stopped state will call Pause + // to ensure activation, so if you are a source or transform + // you will probably not need to override Run. + STDMETHODIMP Stop(); + STDMETHODIMP Pause(); + + + // the start parameter is the difference to be added to the + // sample's stream time to get the reference time for + // its presentation + STDMETHODIMP Run(REFERENCE_TIME tStart); + + // --- helper methods --- + + // return the current stream time - ie find out what + // stream time should be appearing now + virtual HRESULT StreamTime(CRefTime& rtStream); + + // Is the filter currently active? (running or paused) + BOOL IsActive() { + CAutoLock cObjectLock(m_pLock); + return ((m_State == State_Paused) || (m_State == State_Running)); + }; +}; + +//===================================================================== +//===================================================================== +// Defines CBaseFilter +// +// An abstract class providing basic IBaseFilter support for pin +// enumeration and filter information reading. +// +// We cannot derive from CBaseMediaFilter since methods in IMediaFilter +// are also in IBaseFilter and would be ambiguous. Since much of the code +// assumes that they derive from a class that has m_State and other state +// directly available, we duplicate code from CBaseMediaFilter rather than +// having a member variable. +// +// Derive your filter from this, or from a derived object such as +// CTransformFilter. +//===================================================================== +//===================================================================== + + +class AM_NOVTABLE CBaseFilter : public CUnknown, // Handles an IUnknown + public IBaseFilter, // The Filter Interface + public IAMovieSetup // For un/registration +{ + +friend class CBasePin; + +protected: + FILTER_STATE m_State; // current state: running, paused + IReferenceClock *m_pClock; // this graph's ref clock + CRefTime m_tStart; // offset from stream time to reference time + CLSID m_clsid; // This filters clsid + // used for serialization + CCritSec *m_pLock; // Object we use for locking + + WCHAR *m_pName; // Full filter name + IFilterGraph *m_pGraph; // Graph we belong to + IMediaEventSink *m_pSink; // Called with notify events + LONG m_PinVersion; // Current pin version + +public: + + CBaseFilter( + __in_opt LPCTSTR pName, // Object description + __inout_opt LPUNKNOWN pUnk, // IUnknown of delegating object + __in CCritSec *pLock, // Object who maintains lock + REFCLSID clsid); // The clsid to be used to serialize this filter + + CBaseFilter( + __in_opt LPCTSTR pName, // Object description + __in_opt LPUNKNOWN pUnk, // IUnknown of delegating object + __in CCritSec *pLock, // Object who maintains lock + REFCLSID clsid, // The clsid to be used to serialize this filter + __inout HRESULT *phr); // General OLE return code +#ifdef UNICODE + CBaseFilter( + __in_opt LPCSTR pName, // Object description + __in_opt LPUNKNOWN pUnk, // IUnknown of delegating object + __in CCritSec *pLock, // Object who maintains lock + REFCLSID clsid); // The clsid to be used to serialize this filter + + CBaseFilter( + __in_opt LPCSTR pName, // Object description + __in_opt LPUNKNOWN pUnk, // IUnknown of delegating object + __in CCritSec *pLock, // Object who maintains lock + REFCLSID clsid, // The clsid to be used to serialize this filter + __inout HRESULT *phr); // General OLE return code +#endif + ~CBaseFilter(); + + DECLARE_IUNKNOWN + + // override this to say what interfaces we support where + STDMETHODIMP NonDelegatingQueryInterface(REFIID riid, __deref_out void ** ppv); +#ifdef DEBUG + STDMETHODIMP_(ULONG) NonDelegatingRelease(); +#endif + + // + // --- IPersist method --- + // + + STDMETHODIMP GetClassID(__out CLSID *pClsID); + + // --- IMediaFilter methods --- + + STDMETHODIMP GetState(DWORD dwMSecs, __out FILTER_STATE *State); + + STDMETHODIMP SetSyncSource(__in_opt IReferenceClock *pClock); + + STDMETHODIMP GetSyncSource(__deref_out_opt IReferenceClock **pClock); + + + // override Stop and Pause so we can activate the pins. + // Note that Run will call Pause first if activation needed. + // Override these if you want to activate your filter rather than + // your pins. + STDMETHODIMP Stop(); + STDMETHODIMP Pause(); + + // the start parameter is the difference to be added to the + // sample's stream time to get the reference time for + // its presentation + STDMETHODIMP Run(REFERENCE_TIME tStart); + + // --- helper methods --- + + // return the current stream time - ie find out what + // stream time should be appearing now + virtual HRESULT StreamTime(CRefTime& rtStream); + + // Is the filter currently active? + BOOL IsActive() { + CAutoLock cObjectLock(m_pLock); + return ((m_State == State_Paused) || (m_State == State_Running)); + }; + + // Is this filter stopped (without locking) + BOOL IsStopped() { + return (m_State == State_Stopped); + }; + + // + // --- IBaseFilter methods --- + // + + // pin enumerator + STDMETHODIMP EnumPins( + __deref_out IEnumPins ** ppEnum); + + + // default behaviour of FindPin assumes pin ids are their names + STDMETHODIMP FindPin( + LPCWSTR Id, + __deref_out IPin ** ppPin + ); + + STDMETHODIMP QueryFilterInfo( + __out FILTER_INFO * pInfo); + + STDMETHODIMP JoinFilterGraph( + __inout_opt IFilterGraph * pGraph, + __in_opt LPCWSTR pName); + + // return a Vendor information string. Optional - may return E_NOTIMPL. + // memory returned should be freed using CoTaskMemFree + // default implementation returns E_NOTIMPL + STDMETHODIMP QueryVendorInfo( + __deref_out LPWSTR* pVendorInfo + ); + + // --- helper methods --- + + // send an event notification to the filter graph if we know about it. + // returns S_OK if delivered, S_FALSE if the filter graph does not sink + // events, or an error otherwise. + HRESULT NotifyEvent( + long EventCode, + LONG_PTR EventParam1, + LONG_PTR EventParam2); + + // return the filter graph we belong to + __out_opt IFilterGraph *GetFilterGraph() { + return m_pGraph; + } + + // Request reconnect + // pPin is the pin to reconnect + // pmt is the type to reconnect with - can be NULL + // Calls ReconnectEx on the filter graph + HRESULT ReconnectPin(IPin *pPin, __in_opt AM_MEDIA_TYPE const *pmt); + + // find out the current pin version (used by enumerators) + virtual LONG GetPinVersion(); + void IncrementPinVersion(); + + // you need to supply these to access the pins from the enumerator + // and for default Stop and Pause/Run activation. + virtual int GetPinCount() PURE; + virtual CBasePin *GetPin(int n) PURE; + + // --- IAMovieSetup methods --- + + STDMETHODIMP Register(); // ask filter to register itself + STDMETHODIMP Unregister(); // and unregister itself + + // --- setup helper methods --- + // (override to return filters setup data) + + virtual __out_opt LPAMOVIESETUP_FILTER GetSetupData(){ return NULL; } + +}; + + +//===================================================================== +//===================================================================== +// Defines CBasePin +// +// Abstract class that supports the basics of IPin +//===================================================================== +//===================================================================== + +class AM_NOVTABLE CBasePin : public CUnknown, public IPin, public IQualityControl +{ + +protected: + + WCHAR * m_pName; // This pin's name + IPin *m_Connected; // Pin we have connected to + PIN_DIRECTION m_dir; // Direction of this pin + CCritSec *m_pLock; // Object we use for locking + bool m_bRunTimeError; // Run time error generated + bool m_bCanReconnectWhenActive; // OK to reconnect when active + bool m_bTryMyTypesFirst; // When connecting enumerate + // this pin's types first + CBaseFilter *m_pFilter; // Filter we were created by + IQualityControl *m_pQSink; // Target for Quality messages + LONG m_TypeVersion; // Holds current type version + CMediaType m_mt; // Media type of connection + + CRefTime m_tStart; // time from NewSegment call + CRefTime m_tStop; // time from NewSegment + double m_dRate; // rate from NewSegment + +#ifdef DEBUG + LONG m_cRef; // Ref count tracing +#endif + + // displays pin connection information + +#ifdef DEBUG + void DisplayPinInfo(IPin *pReceivePin); + void DisplayTypeInfo(IPin *pPin, const CMediaType *pmt); +#else + void DisplayPinInfo(IPin *pReceivePin) {}; + void DisplayTypeInfo(IPin *pPin, const CMediaType *pmt) {}; +#endif + + // used to agree a media type for a pin connection + + // given a specific media type, attempt a connection (includes + // checking that the type is acceptable to this pin) + HRESULT + AttemptConnection( + IPin* pReceivePin, // connect to this pin + const CMediaType* pmt // using this type + ); + + // try all the media types in this enumerator - for each that + // we accept, try to connect using ReceiveConnection. + HRESULT TryMediaTypes( + IPin *pReceivePin, // connect to this pin + __in_opt const CMediaType *pmt, // proposed type from Connect + IEnumMediaTypes *pEnum); // try this enumerator + + // establish a connection with a suitable mediatype. Needs to + // propose a media type if the pmt pointer is null or partially + // specified - use TryMediaTypes on both our and then the other pin's + // enumerator until we find one that works. + HRESULT AgreeMediaType( + IPin *pReceivePin, // connect to this pin + const CMediaType *pmt); // proposed type from Connect + +public: + + CBasePin( + __in_opt LPCTSTR pObjectName, // Object description + __in CBaseFilter *pFilter, // Owning filter who knows about pins + __in CCritSec *pLock, // Object who implements the lock + __inout HRESULT *phr, // General OLE return code + __in_opt LPCWSTR pName, // Pin name for us + PIN_DIRECTION dir); // Either PINDIR_INPUT or PINDIR_OUTPUT +#ifdef UNICODE + CBasePin( + __in_opt LPCSTR pObjectName, // Object description + __in CBaseFilter *pFilter, // Owning filter who knows about pins + __in CCritSec *pLock, // Object who implements the lock + __inout HRESULT *phr, // General OLE return code + __in_opt LPCWSTR pName, // Pin name for us + PIN_DIRECTION dir); // Either PINDIR_INPUT or PINDIR_OUTPUT +#endif + virtual ~CBasePin(); + + DECLARE_IUNKNOWN + + STDMETHODIMP NonDelegatingQueryInterface(REFIID riid, __deref_out void ** ppv); + STDMETHODIMP_(ULONG) NonDelegatingRelease(); + STDMETHODIMP_(ULONG) NonDelegatingAddRef(); + + // --- IPin methods --- + + // take lead role in establishing a connection. Media type pointer + // may be null, or may point to partially-specified mediatype + // (subtype or format type may be GUID_NULL). + STDMETHODIMP Connect( + IPin * pReceivePin, + __in_opt const AM_MEDIA_TYPE *pmt // optional media type + ); + + // (passive) accept a connection from another pin + STDMETHODIMP ReceiveConnection( + IPin * pConnector, // this is the initiating connecting pin + const AM_MEDIA_TYPE *pmt // this is the media type we will exchange + ); + + STDMETHODIMP Disconnect(); + + STDMETHODIMP ConnectedTo(__deref_out IPin **pPin); + + STDMETHODIMP ConnectionMediaType(__out AM_MEDIA_TYPE *pmt); + + STDMETHODIMP QueryPinInfo( + __out PIN_INFO * pInfo + ); + + STDMETHODIMP QueryDirection( + __out PIN_DIRECTION * pPinDir + ); + + STDMETHODIMP QueryId( + __deref_out LPWSTR * Id + ); + + // does the pin support this media type + STDMETHODIMP QueryAccept( + const AM_MEDIA_TYPE *pmt + ); + + // return an enumerator for this pins preferred media types + STDMETHODIMP EnumMediaTypes( + __deref_out IEnumMediaTypes **ppEnum + ); + + // return an array of IPin* - the pins that this pin internally connects to + // All pins put in the array must be AddReffed (but no others) + // Errors: "Can't say" - FAIL, not enough slots - return S_FALSE + // Default: return E_NOTIMPL + // The filter graph will interpret NOT_IMPL as any input pin connects to + // all visible output pins and vice versa. + // apPin can be NULL if nPin==0 (not otherwise). + STDMETHODIMP QueryInternalConnections( + __out_ecount_part(*nPin,*nPin) IPin* *apPin, // array of IPin* + __inout ULONG *nPin // on input, the number of slots + // on output the number of pins + ) { return E_NOTIMPL; } + + // Called when no more data will be sent + STDMETHODIMP EndOfStream(void); + + // Begin/EndFlush still PURE + + // NewSegment notifies of the start/stop/rate applying to the data + // about to be received. Default implementation records data and + // returns S_OK. + // Override this to pass downstream. + STDMETHODIMP NewSegment( + REFERENCE_TIME tStart, + REFERENCE_TIME tStop, + double dRate); + + //================================================================================ + // IQualityControl methods + //================================================================================ + + STDMETHODIMP Notify(IBaseFilter * pSender, Quality q); + + STDMETHODIMP SetSink(IQualityControl * piqc); + + // --- helper methods --- + + // Returns true if the pin is connected. false otherwise. + BOOL IsConnected(void) {return (m_Connected != NULL); }; + // Return the pin this is connected to (if any) + IPin * GetConnected() { return m_Connected; }; + + // Check if our filter is currently stopped + BOOL IsStopped() { + return (m_pFilter->m_State == State_Stopped); + }; + + // find out the current type version (used by enumerators) + virtual LONG GetMediaTypeVersion(); + void IncrementTypeVersion(); + + // switch the pin to active (paused or running) mode + // not an error to call this if already active + virtual HRESULT Active(void); + + // switch the pin to inactive state - may already be inactive + virtual HRESULT Inactive(void); + + // Notify of Run() from filter + virtual HRESULT Run(REFERENCE_TIME tStart); + + // check if the pin can support this specific proposed type and format + virtual HRESULT CheckMediaType(const CMediaType *) PURE; + + // set the connection to use this format (previously agreed) + virtual HRESULT SetMediaType(const CMediaType *); + + // check that the connection is ok before verifying it + // can be overridden eg to check what interfaces will be supported. + virtual HRESULT CheckConnect(IPin *); + + // Set and release resources required for a connection + virtual HRESULT BreakConnect(); + virtual HRESULT CompleteConnect(IPin *pReceivePin); + + // returns the preferred formats for a pin + virtual HRESULT GetMediaType(int iPosition, __inout CMediaType *pMediaType); + + // access to NewSegment values + REFERENCE_TIME CurrentStopTime() { + return m_tStop; + } + REFERENCE_TIME CurrentStartTime() { + return m_tStart; + } + double CurrentRate() { + return m_dRate; + } + + // Access name + LPWSTR Name() { return m_pName; }; + + // Can reconnectwhen active? + void SetReconnectWhenActive(bool bCanReconnect) + { + m_bCanReconnectWhenActive = bCanReconnect; + } + + bool CanReconnectWhenActive() + { + return m_bCanReconnectWhenActive; + } + +protected: + STDMETHODIMP DisconnectInternal(); +}; + + +//===================================================================== +//===================================================================== +// Defines CEnumPins +// +// Pin enumerator class that works by calling CBaseFilter. This interface +// is provided by CBaseFilter::EnumPins and calls GetPinCount() and +// GetPin() to enumerate existing pins. Needs to be a separate object so +// that it can be cloned (creating an existing object at the same +// position in the enumeration) +// +//===================================================================== +//===================================================================== + +class CEnumPins : public IEnumPins // The interface we support +{ + int m_Position; // Current ordinal position + int m_PinCount; // Number of pins available + CBaseFilter *m_pFilter; // The filter who owns us + LONG m_Version; // Pin version information + LONG m_cRef; + + typedef CGenericList CPinList; + + CPinList m_PinCache; // These pointers have not been AddRef'ed and + // so they should not be dereferenced. They are + // merely kept to ID which pins have been enumerated. + +#ifdef DEBUG + DWORD m_dwCookie; +#endif + + /* If while we are retrieving a pin for example from the filter an error + occurs we assume that our internal state is stale with respect to the + filter (someone may have deleted all the pins). We can check before + starting whether or not the operation is likely to fail by asking the + filter what it's current version number is. If the filter has not + overriden the GetPinVersion method then this will always match */ + + BOOL AreWeOutOfSync() { + return (m_pFilter->GetPinVersion() == m_Version ? FALSE : TRUE); + }; + + /* This method performs the same operations as Reset, except is does not clear + the cache of pins already enumerated. */ + + STDMETHODIMP Refresh(); + +public: + + CEnumPins( + __in CBaseFilter *pFilter, + __in_opt CEnumPins *pEnumPins); + + virtual ~CEnumPins(); + + // IUnknown + STDMETHODIMP QueryInterface(REFIID riid, __deref_out void **ppv); + STDMETHODIMP_(ULONG) AddRef(); + STDMETHODIMP_(ULONG) Release(); + + // IEnumPins + STDMETHODIMP Next( + ULONG cPins, // place this many pins... + __out_ecount(cPins) IPin ** ppPins, // ...in this array of IPin* + __out_opt ULONG * pcFetched // actual count passed returned here + ); + + STDMETHODIMP Skip(ULONG cPins); + STDMETHODIMP Reset(); + STDMETHODIMP Clone(__deref_out IEnumPins **ppEnum); + + +}; + + +//===================================================================== +//===================================================================== +// Defines CEnumMediaTypes +// +// Enumerates the preferred formats for input and output pins +//===================================================================== +//===================================================================== + +class CEnumMediaTypes : public IEnumMediaTypes // The interface we support +{ + int m_Position; // Current ordinal position + CBasePin *m_pPin; // The pin who owns us + LONG m_Version; // Media type version value + LONG m_cRef; +#ifdef DEBUG + DWORD m_dwCookie; +#endif + + /* The media types a filter supports can be quite dynamic so we add to + the general IEnumXXXX interface the ability to be signaled when they + change via an event handle the connected filter supplies. Until the + Reset method is called after the state changes all further calls to + the enumerator (except Reset) will return E_UNEXPECTED error code */ + + BOOL AreWeOutOfSync() { + return (m_pPin->GetMediaTypeVersion() == m_Version ? FALSE : TRUE); + }; + +public: + + CEnumMediaTypes( + __in CBasePin *pPin, + __in_opt CEnumMediaTypes *pEnumMediaTypes); + + virtual ~CEnumMediaTypes(); + + // IUnknown + STDMETHODIMP QueryInterface(REFIID riid, __deref_out void **ppv); + STDMETHODIMP_(ULONG) AddRef(); + STDMETHODIMP_(ULONG) Release(); + + // IEnumMediaTypes + STDMETHODIMP Next( + ULONG cMediaTypes, // place this many pins... + __out_ecount(cMediaTypes) AM_MEDIA_TYPE ** ppMediaTypes, // ...in this array + __out_opt ULONG * pcFetched // actual count passed + ); + + STDMETHODIMP Skip(ULONG cMediaTypes); + STDMETHODIMP Reset(); + STDMETHODIMP Clone(__deref_out IEnumMediaTypes **ppEnum); +}; + + + + +//===================================================================== +//===================================================================== +// Defines CBaseOutputPin +// +// class derived from CBasePin that can pass buffers to a connected pin +// that supports IMemInputPin. Supports IPin. +// +// Derive your output pin from this. +// +//===================================================================== +//===================================================================== + +class AM_NOVTABLE CBaseOutputPin : public CBasePin +{ + +protected: + + IMemAllocator *m_pAllocator; + IMemInputPin *m_pInputPin; // interface on the downstreaminput pin + // set up in CheckConnect when we connect. + +public: + + CBaseOutputPin( + __in_opt LPCTSTR pObjectName, + __in CBaseFilter *pFilter, + __in CCritSec *pLock, + __inout HRESULT *phr, + __in_opt LPCWSTR pName); +#ifdef UNICODE + CBaseOutputPin( + __in_opt LPCSTR pObjectName, + __in CBaseFilter *pFilter, + __in CCritSec *pLock, + __inout HRESULT *phr, + __in_opt LPCWSTR pName); +#endif + // override CompleteConnect() so we can negotiate an allocator + virtual HRESULT CompleteConnect(IPin *pReceivePin); + + // negotiate the allocator and its buffer size/count and other properties + // Calls DecideBufferSize to set properties + virtual HRESULT DecideAllocator(IMemInputPin * pPin, __deref_out IMemAllocator ** pAlloc); + + // override this to set the buffer size and count. Return an error + // if the size/count is not to your liking. + // The allocator properties passed in are those requested by the + // input pin - use eg the alignment and prefix members if you have + // no preference on these. + virtual HRESULT DecideBufferSize( + IMemAllocator * pAlloc, + __inout ALLOCATOR_PROPERTIES * ppropInputRequest + ) PURE; + + // returns an empty sample buffer from the allocator + virtual HRESULT GetDeliveryBuffer(__deref_out IMediaSample ** ppSample, + __in_opt REFERENCE_TIME * pStartTime, + __in_opt REFERENCE_TIME * pEndTime, + DWORD dwFlags); + + // deliver a filled-in sample to the connected input pin + // note - you need to release it after calling this. The receiving + // pin will addref the sample if it needs to hold it beyond the + // call. + virtual HRESULT Deliver(IMediaSample *); + + // override this to control the connection + virtual HRESULT InitAllocator(__deref_out IMemAllocator **ppAlloc); + HRESULT CheckConnect(IPin *pPin); + HRESULT BreakConnect(); + + // override to call Commit and Decommit + HRESULT Active(void); + HRESULT Inactive(void); + + // we have a default handling of EndOfStream which is to return + // an error, since this should be called on input pins only + STDMETHODIMP EndOfStream(void); + + // called from elsewhere in our filter to pass EOS downstream to + // our connected input pin + virtual HRESULT DeliverEndOfStream(void); + + // same for Begin/EndFlush - we handle Begin/EndFlush since it + // is an error on an output pin, and we have Deliver methods to + // call the methods on the connected pin + STDMETHODIMP BeginFlush(void); + STDMETHODIMP EndFlush(void); + virtual HRESULT DeliverBeginFlush(void); + virtual HRESULT DeliverEndFlush(void); + + // deliver NewSegment to connected pin - you will need to + // override this if you queue any data in your output pin. + virtual HRESULT DeliverNewSegment( + REFERENCE_TIME tStart, + REFERENCE_TIME tStop, + double dRate); + + //================================================================================ + // IQualityControl methods + //================================================================================ + + // All inherited from CBasePin and not overridden here. + // STDMETHODIMP Notify(IBaseFilter * pSender, Quality q); + // STDMETHODIMP SetSink(IQualityControl * piqc); +}; + + +//===================================================================== +//===================================================================== +// Defines CBaseInputPin +// +// derive your standard input pin from this. +// you need to supply GetMediaType and CheckConnect etc (see CBasePin), +// and you need to supply Receive to do something more useful. +// +//===================================================================== +//===================================================================== + +class AM_NOVTABLE CBaseInputPin : public CBasePin, + public IMemInputPin +{ + +protected: + + IMemAllocator *m_pAllocator; // Default memory allocator + + // allocator is read-only, so received samples + // cannot be modified (probably only relevant to in-place + // transforms + BYTE m_bReadOnly; + + // in flushing state (between BeginFlush and EndFlush) + // if TRUE, all Receives are returned with S_FALSE + BYTE m_bFlushing; + + // Sample properties - initalized in Receive + AM_SAMPLE2_PROPERTIES m_SampleProps; + +public: + + CBaseInputPin( + __in_opt LPCTSTR pObjectName, + __in CBaseFilter *pFilter, + __in CCritSec *pLock, + __inout HRESULT *phr, + __in_opt LPCWSTR pName); +#ifdef UNICODE + CBaseInputPin( + __in_opt LPCSTR pObjectName, + __in CBaseFilter *pFilter, + __in CCritSec *pLock, + __inout HRESULT *phr, + __in_opt LPCWSTR pName); +#endif + virtual ~CBaseInputPin(); + + DECLARE_IUNKNOWN + + // override this to publicise our interfaces + STDMETHODIMP NonDelegatingQueryInterface(REFIID riid, __deref_out void **ppv); + + // return the allocator interface that this input pin + // would like the output pin to use + STDMETHODIMP GetAllocator(__deref_out IMemAllocator ** ppAllocator); + + // tell the input pin which allocator the output pin is actually + // going to use. + STDMETHODIMP NotifyAllocator( + IMemAllocator * pAllocator, + BOOL bReadOnly); + + // do something with this media sample + STDMETHODIMP Receive(IMediaSample *pSample); + + // do something with these media samples + STDMETHODIMP ReceiveMultiple ( + __in_ecount(nSamples) IMediaSample **pSamples, + long nSamples, + __out long *nSamplesProcessed); + + // See if Receive() blocks + STDMETHODIMP ReceiveCanBlock(); + + // Default handling for BeginFlush - call at the beginning + // of your implementation (makes sure that all Receive calls + // fail). After calling this, you need to free any queued data + // and then call downstream. + STDMETHODIMP BeginFlush(void); + + // default handling for EndFlush - call at end of your implementation + // - before calling this, ensure that there is no queued data and no thread + // pushing any more without a further receive, then call downstream, + // then call this method to clear the m_bFlushing flag and re-enable + // receives + STDMETHODIMP EndFlush(void); + + // this method is optional (can return E_NOTIMPL). + // default implementation returns E_NOTIMPL. Override if you have + // specific alignment or prefix needs, but could use an upstream + // allocator + STDMETHODIMP GetAllocatorRequirements(__out ALLOCATOR_PROPERTIES*pProps); + + // Release the pin's allocator. + HRESULT BreakConnect(); + + // helper method to check the read-only flag + BOOL IsReadOnly() { + return m_bReadOnly; + }; + + // helper method to see if we are flushing + BOOL IsFlushing() { + return m_bFlushing; + }; + + // Override this for checking whether it's OK to process samples + // Also call this from EndOfStream. + virtual HRESULT CheckStreaming(); + + // Pass a Quality notification on to the appropriate sink + HRESULT PassNotify(Quality& q); + + + //================================================================================ + // IQualityControl methods (from CBasePin) + //================================================================================ + + STDMETHODIMP Notify(IBaseFilter * pSender, Quality q); + + // no need to override: + // STDMETHODIMP SetSink(IQualityControl * piqc); + + + // switch the pin to inactive state - may already be inactive + virtual HRESULT Inactive(void); + + // Return sample properties pointer + AM_SAMPLE2_PROPERTIES * SampleProps() { + ASSERT(m_SampleProps.cbData != 0); + return &m_SampleProps; + } + +}; + +/////////////////////////////////////////////////////////////////////////// +// CDynamicOutputPin +// + +class CDynamicOutputPin : public CBaseOutputPin, + public IPinFlowControl +{ +public: +#ifdef UNICODE + CDynamicOutputPin( + __in_opt LPCSTR pObjectName, + __in CBaseFilter *pFilter, + __in CCritSec *pLock, + __inout HRESULT *phr, + __in_opt LPCWSTR pName); +#endif + + CDynamicOutputPin( + __in_opt LPCTSTR pObjectName, + __in CBaseFilter *pFilter, + __in CCritSec *pLock, + __inout HRESULT *phr, + __in_opt LPCWSTR pName); + + ~CDynamicOutputPin(); + + // IUnknown Methods + DECLARE_IUNKNOWN + STDMETHODIMP NonDelegatingQueryInterface(REFIID riid, __deref_out void **ppv); + + // IPin Methods + STDMETHODIMP Disconnect(void); + + // IPinFlowControl Methods + STDMETHODIMP Block(DWORD dwBlockFlags, HANDLE hEvent); + + // Set graph config info + void SetConfigInfo(IGraphConfig *pGraphConfig, HANDLE hStopEvent); + + #ifdef DEBUG + virtual HRESULT Deliver(IMediaSample *pSample); + virtual HRESULT DeliverEndOfStream(void); + virtual HRESULT DeliverNewSegment(REFERENCE_TIME tStart, REFERENCE_TIME tStop, double dRate); + #endif // DEBUG + + HRESULT DeliverBeginFlush(void); + HRESULT DeliverEndFlush(void); + + HRESULT Inactive(void); + HRESULT Active(void); + virtual HRESULT CompleteConnect(IPin *pReceivePin); + + virtual HRESULT StartUsingOutputPin(void); + virtual void StopUsingOutputPin(void); + virtual bool StreamingThreadUsingOutputPin(void); + + HRESULT ChangeOutputFormat + ( + const AM_MEDIA_TYPE *pmt, + REFERENCE_TIME tSegmentStart, + REFERENCE_TIME tSegmentStop, + double dSegmentRate + ); + HRESULT ChangeMediaType(const CMediaType *pmt); + HRESULT DynamicReconnect(const CMediaType *pmt); + +protected: + HRESULT SynchronousBlockOutputPin(void); + HRESULT AsynchronousBlockOutputPin(HANDLE hNotifyCallerPinBlockedEvent); + HRESULT UnblockOutputPin(void); + + void BlockOutputPin(void); + void ResetBlockState(void); + + static HRESULT WaitEvent(HANDLE hEvent); + + enum BLOCK_STATE + { + NOT_BLOCKED, + PENDING, + BLOCKED + }; + + // This lock should be held when the following class members are + // being used: m_hNotifyCallerPinBlockedEvent, m_BlockState, + // m_dwBlockCallerThreadID and m_dwNumOutstandingOutputPinUsers. + CCritSec m_BlockStateLock; + + // This event should be signaled when the output pin is + // not blocked. This is a manual reset event. For more + // information on events, see the documentation for + // CreateEvent() in the Windows SDK. + HANDLE m_hUnblockOutputPinEvent; + + // This event will be signaled when block operation succeedes or + // when the user cancels the block operation. The block operation + // can be canceled by calling IPinFlowControl2::Block( 0, NULL ) + // while the block operation is pending. + HANDLE m_hNotifyCallerPinBlockedEvent; + + // The state of the current block operation. + BLOCK_STATE m_BlockState; + + // The ID of the thread which last called IPinFlowControl::Block(). + // For more information on thread IDs, see the documentation for + // GetCurrentThreadID() in the Windows SDK. + DWORD m_dwBlockCallerThreadID; + + // The number of times StartUsingOutputPin() has been sucessfully + // called and a corresponding call to StopUsingOutputPin() has not + // been made. When this variable is greater than 0, the streaming + // thread is calling IPin::NewSegment(), IPin::EndOfStream(), + // IMemInputPin::Receive() or IMemInputPin::ReceiveMultiple(). The + // streaming thread could also be calling: DynamicReconnect(), + // ChangeMediaType() or ChangeOutputFormat(). The output pin cannot + // be blocked while the output pin is being used. + DWORD m_dwNumOutstandingOutputPinUsers; + + // This event should be set when the IMediaFilter::Stop() is called. + // This is a manual reset event. It is also set when the output pin + // delivers a flush to the connected input pin. + HANDLE m_hStopEvent; + IGraphConfig* m_pGraphConfig; + + // TRUE if the output pin's allocator's samples are read only. + // Otherwise FALSE. For more information, see the documentation + // for IMemInputPin::NotifyAllocator(). + BOOL m_bPinUsesReadOnlyAllocator; + +private: + HRESULT Initialize(void); + HRESULT ChangeMediaTypeHelper(const CMediaType *pmt); + + #ifdef DEBUG + void AssertValid(void); + #endif // DEBUG +}; + +class CAutoUsingOutputPin +{ +public: + CAutoUsingOutputPin( __in CDynamicOutputPin* pOutputPin, __inout HRESULT* phr ); + ~CAutoUsingOutputPin(); + +private: + CDynamicOutputPin* m_pOutputPin; +}; + +inline CAutoUsingOutputPin::CAutoUsingOutputPin( __in CDynamicOutputPin* pOutputPin, __inout HRESULT* phr ) : + m_pOutputPin(NULL) +{ + // The caller should always pass in valid pointers. + ASSERT( NULL != pOutputPin ); + ASSERT( NULL != phr ); + + // Make sure the user initialized phr. + ASSERT( S_OK == *phr ); + + HRESULT hr = pOutputPin->StartUsingOutputPin(); + if( FAILED( hr ) ) + { + *phr = hr; + return; + } + + m_pOutputPin = pOutputPin; +} + +inline CAutoUsingOutputPin::~CAutoUsingOutputPin() +{ + if( NULL != m_pOutputPin ) + { + m_pOutputPin->StopUsingOutputPin(); + } +} + +#ifdef DEBUG + +inline HRESULT CDynamicOutputPin::Deliver(IMediaSample *pSample) +{ + // The caller should call StartUsingOutputPin() before calling this + // method. + ASSERT(StreamingThreadUsingOutputPin()); + + return CBaseOutputPin::Deliver(pSample); +} + +inline HRESULT CDynamicOutputPin::DeliverEndOfStream(void) +{ + // The caller should call StartUsingOutputPin() before calling this + // method. + ASSERT( StreamingThreadUsingOutputPin() ); + + return CBaseOutputPin::DeliverEndOfStream(); +} + +inline HRESULT CDynamicOutputPin::DeliverNewSegment(REFERENCE_TIME tStart, REFERENCE_TIME tStop, double dRate) +{ + // The caller should call StartUsingOutputPin() before calling this + // method. + ASSERT(StreamingThreadUsingOutputPin()); + + return CBaseOutputPin::DeliverNewSegment(tStart, tStop, dRate); +} + +#endif // DEBUG + +//===================================================================== +//===================================================================== +// Memory allocators +// +// the shared memory transport between pins requires the input pin +// to provide a memory allocator that can provide sample objects. A +// sample object supports the IMediaSample interface. +// +// CBaseAllocator handles the management of free and busy samples. It +// allocates CMediaSample objects. CBaseAllocator is an abstract class: +// in particular it has no method of initializing the list of free +// samples. CMemAllocator is derived from CBaseAllocator and initializes +// the list of samples using memory from the standard IMalloc interface. +// +// If you want your buffers to live in some special area of memory, +// derive your allocator object from CBaseAllocator. If you derive your +// IMemInputPin interface object from CBaseMemInputPin, you will get +// CMemAllocator-based allocation etc for free and will just need to +// supply the Receive handling, and media type / format negotiation. +//===================================================================== +//===================================================================== + + +//===================================================================== +//===================================================================== +// Defines CMediaSample +// +// an object of this class supports IMediaSample and represents a buffer +// for media data with some associated properties. Releasing it returns +// it to a freelist managed by a CBaseAllocator derived object. +//===================================================================== +//===================================================================== + +class CMediaSample : public IMediaSample2 // The interface we support +{ + +protected: + + friend class CBaseAllocator; + + /* Values for dwFlags - these are used for backward compatiblity + only now - use AM_SAMPLE_xxx + */ + enum { Sample_SyncPoint = 0x01, /* Is this a sync point */ + Sample_Preroll = 0x02, /* Is this a preroll sample */ + Sample_Discontinuity = 0x04, /* Set if start of new segment */ + Sample_TypeChanged = 0x08, /* Has the type changed */ + Sample_TimeValid = 0x10, /* Set if time is valid */ + Sample_MediaTimeValid = 0x20, /* Is the media time valid */ + Sample_TimeDiscontinuity = 0x40, /* Time discontinuity */ + Sample_StopValid = 0x100, /* Stop time valid */ + Sample_ValidFlags = 0x1FF + }; + + /* Properties, the media sample class can be a container for a format + change in which case we take a copy of a type through the SetMediaType + interface function and then return it when GetMediaType is called. As + we do no internal processing on it we leave it as a pointer */ + + DWORD m_dwFlags; /* Flags for this sample */ + /* Type specific flags are packed + into the top word + */ + DWORD m_dwTypeSpecificFlags; /* Media type specific flags */ + __field_ecount_opt(m_cbBuffer) LPBYTE m_pBuffer; /* Pointer to the complete buffer */ + LONG m_lActual; /* Length of data in this sample */ + LONG m_cbBuffer; /* Size of the buffer */ + CBaseAllocator *m_pAllocator; /* The allocator who owns us */ + CMediaSample *m_pNext; /* Chaining in free list */ + REFERENCE_TIME m_Start; /* Start sample time */ + REFERENCE_TIME m_End; /* End sample time */ + LONGLONG m_MediaStart; /* Real media start position */ + LONG m_MediaEnd; /* A difference to get the end */ + AM_MEDIA_TYPE *m_pMediaType; /* Media type change data */ + DWORD m_dwStreamId; /* Stream id */ +public: + LONG m_cRef; /* Reference count */ + + +public: + + CMediaSample( + __in_opt LPCTSTR pName, + __in_opt CBaseAllocator *pAllocator, + __inout_opt HRESULT *phr, + __in_bcount_opt(length) LPBYTE pBuffer = NULL, + LONG length = 0); +#ifdef UNICODE + CMediaSample( + __in_opt LPCSTR pName, + __in_opt CBaseAllocator *pAllocator, + __inout_opt HRESULT *phr, + __in_bcount_opt(length) LPBYTE pBuffer = NULL, + LONG length = 0); +#endif + + virtual ~CMediaSample(); + + /* Note the media sample does not delegate to its owner */ + + STDMETHODIMP QueryInterface(REFIID riid, __deref_out void **ppv); + STDMETHODIMP_(ULONG) AddRef(); + STDMETHODIMP_(ULONG) Release(); + + // set the buffer pointer and length. Used by allocators that + // want variable sized pointers or pointers into already-read data. + // This is only available through a CMediaSample* not an IMediaSample* + // and so cannot be changed by clients. + HRESULT SetPointer(__in_bcount(cBytes) BYTE * ptr, LONG cBytes); + + // Get me a read/write pointer to this buffer's memory. + STDMETHODIMP GetPointer(__deref_out BYTE ** ppBuffer); + + STDMETHODIMP_(LONG) GetSize(void); + + // get the stream time at which this sample should start and finish. + STDMETHODIMP GetTime( + __out REFERENCE_TIME * pTimeStart, // put time here + __out REFERENCE_TIME * pTimeEnd + ); + + // Set the stream time at which this sample should start and finish. + STDMETHODIMP SetTime( + __in_opt REFERENCE_TIME * pTimeStart, // put time here + __in_opt REFERENCE_TIME * pTimeEnd + ); + STDMETHODIMP IsSyncPoint(void); + STDMETHODIMP SetSyncPoint(BOOL bIsSyncPoint); + STDMETHODIMP IsPreroll(void); + STDMETHODIMP SetPreroll(BOOL bIsPreroll); + + STDMETHODIMP_(LONG) GetActualDataLength(void); + STDMETHODIMP SetActualDataLength(LONG lActual); + + // these allow for limited format changes in band + + STDMETHODIMP GetMediaType(__deref_out AM_MEDIA_TYPE **ppMediaType); + STDMETHODIMP SetMediaType(__in_opt AM_MEDIA_TYPE *pMediaType); + + // returns S_OK if there is a discontinuity in the data (this same is + // not a continuation of the previous stream of data + // - there has been a seek). + STDMETHODIMP IsDiscontinuity(void); + // set the discontinuity property - TRUE if this sample is not a + // continuation, but a new sample after a seek. + STDMETHODIMP SetDiscontinuity(BOOL bDiscontinuity); + + // get the media times for this sample + STDMETHODIMP GetMediaTime( + __out LONGLONG * pTimeStart, + __out LONGLONG * pTimeEnd + ); + + // Set the media times for this sample + STDMETHODIMP SetMediaTime( + __in_opt LONGLONG * pTimeStart, + __in_opt LONGLONG * pTimeEnd + ); + + // Set and get properties (IMediaSample2) + STDMETHODIMP GetProperties( + DWORD cbProperties, + __out_bcount(cbProperties) BYTE * pbProperties + ); + + STDMETHODIMP SetProperties( + DWORD cbProperties, + __in_bcount(cbProperties) const BYTE * pbProperties + ); +}; + + +//===================================================================== +//===================================================================== +// Defines CBaseAllocator +// +// Abstract base class that manages a list of media samples +// +// This class provides support for getting buffers from the free list, +// including handling of commit and (asynchronous) decommit. +// +// Derive from this class and override the Alloc and Free functions to +// allocate your CMediaSample (or derived) objects and add them to the +// free list, preparing them as necessary. +//===================================================================== +//===================================================================== + +class AM_NOVTABLE CBaseAllocator : public CUnknown,// A non delegating IUnknown + public IMemAllocatorCallbackTemp, // The interface we support + public CCritSec // Provides object locking +{ + class CSampleList; + friend class CSampleList; + + /* Trick to get at protected member in CMediaSample */ + static CMediaSample * &NextSample(__in CMediaSample *pSample) + { + return pSample->m_pNext; + }; + + /* Mini list class for the free list */ + class CSampleList + { + public: + CSampleList() : m_List(NULL), m_nOnList(0) {}; +#ifdef DEBUG + ~CSampleList() + { + ASSERT(m_nOnList == 0); + }; +#endif + CMediaSample *Head() const { return m_List; }; + CMediaSample *Next(__in CMediaSample *pSample) const { return CBaseAllocator::NextSample(pSample); }; + int GetCount() const { return m_nOnList; }; + void Add(__inout CMediaSample *pSample) + { + ASSERT(pSample != NULL); + CBaseAllocator::NextSample(pSample) = m_List; + m_List = pSample; + m_nOnList++; + }; + CMediaSample *RemoveHead() + { + CMediaSample *pSample = m_List; + if (pSample != NULL) { + m_List = CBaseAllocator::NextSample(m_List); + m_nOnList--; + } + return pSample; + }; + void Remove(__inout CMediaSample *pSample); + + public: + CMediaSample *m_List; + int m_nOnList; + }; +protected: + + CSampleList m_lFree; // Free list + + /* Note to overriders of CBaseAllocator. + + We use a lazy signalling mechanism for waiting for samples. + This means we don't call the OS if no waits occur. + + In order to implement this: + + 1. When a new sample is added to m_lFree call NotifySample() which + calls ReleaseSemaphore on m_hSem with a count of m_lWaiting and + sets m_lWaiting to 0. + This must all be done holding the allocator's critical section. + + 2. When waiting for a sample call SetWaiting() which increments + m_lWaiting BEFORE leaving the allocator's critical section. + + 3. Actually wait by calling WaitForSingleObject(m_hSem, INFINITE) + having left the allocator's critical section. The effect of + this is to remove 1 from the semaphore's count. You MUST call + this once having incremented m_lWaiting. + + The following are then true when the critical section is not held : + (let nWaiting = number about to wait or waiting) + + (1) if (m_lFree.GetCount() != 0) then (m_lWaiting == 0) + (2) m_lWaiting + Semaphore count == nWaiting + + We would deadlock if + nWaiting != 0 && + m_lFree.GetCount() != 0 && + Semaphore count == 0 + + But from (1) if m_lFree.GetCount() != 0 then m_lWaiting == 0 so + from (2) Semaphore count == nWaiting (which is non-0) so the + deadlock can't happen. + */ + + HANDLE m_hSem; // For signalling + long m_lWaiting; // Waiting for a free element + long m_lCount; // how many buffers we have agreed to provide + long m_lAllocated; // how many buffers are currently allocated + long m_lSize; // agreed size of each buffer + long m_lAlignment; // agreed alignment + long m_lPrefix; // agreed prefix (preceeds GetPointer() value) + BOOL m_bChanged; // Have the buffer requirements changed + + // if true, we are decommitted and can't allocate memory + BOOL m_bCommitted; + // if true, the decommit has happened, but we haven't called Free yet + // as there are still outstanding buffers + BOOL m_bDecommitInProgress; + + // Notification interface + IMemAllocatorNotifyCallbackTemp *m_pNotify; + + BOOL m_fEnableReleaseCallback; + + // called to decommit the memory when the last buffer is freed + // pure virtual - need to override this + virtual void Free(void) PURE; + + // override to allocate the memory when commit called + virtual HRESULT Alloc(void); + +public: + + CBaseAllocator( + __in_opt LPCTSTR , __inout_opt LPUNKNOWN, __inout HRESULT *, + BOOL bEvent = TRUE, BOOL fEnableReleaseCallback = FALSE); +#ifdef UNICODE + CBaseAllocator( + __in_opt LPCSTR , __inout_opt LPUNKNOWN, __inout HRESULT *, + BOOL bEvent = TRUE, BOOL fEnableReleaseCallback = FALSE); +#endif + virtual ~CBaseAllocator(); + + DECLARE_IUNKNOWN + + // override this to publicise our interfaces + STDMETHODIMP NonDelegatingQueryInterface(REFIID riid, __deref_out void **ppv); + + STDMETHODIMP SetProperties( + __in ALLOCATOR_PROPERTIES* pRequest, + __out ALLOCATOR_PROPERTIES* pActual); + + // return the properties actually being used on this allocator + STDMETHODIMP GetProperties( + __out ALLOCATOR_PROPERTIES* pProps); + + // override Commit to allocate memory. We handle the GetBuffer + //state changes + STDMETHODIMP Commit(); + + // override this to handle the memory freeing. We handle any outstanding + // GetBuffer calls + STDMETHODIMP Decommit(); + + // get container for a sample. Blocking, synchronous call to get the + // next free buffer (as represented by an IMediaSample interface). + // on return, the time etc properties will be invalid, but the buffer + // pointer and size will be correct. The two time parameters are + // optional and either may be NULL, they may alternatively be set to + // the start and end times the sample will have attached to it + // bPrevFramesSkipped is not used (used only by the video renderer's + // allocator where it affects quality management in direct draw). + + STDMETHODIMP GetBuffer(__deref_out IMediaSample **ppBuffer, + __in_opt REFERENCE_TIME * pStartTime, + __in_opt REFERENCE_TIME * pEndTime, + DWORD dwFlags); + + // final release of a CMediaSample will call this + STDMETHODIMP ReleaseBuffer(IMediaSample *pBuffer); + // obsolete:: virtual void PutOnFreeList(CMediaSample * pSample); + + STDMETHODIMP SetNotify(IMemAllocatorNotifyCallbackTemp *pNotify); + + STDMETHODIMP GetFreeCount(__out LONG *plBuffersFree); + + // Notify that a sample is available + void NotifySample(); + + // Notify that we're waiting for a sample + void SetWaiting() { m_lWaiting++; }; +}; + + +//===================================================================== +//===================================================================== +// Defines CMemAllocator +// +// this is an allocator based on CBaseAllocator that allocates sample +// buffers in main memory (from 'new'). You must call SetProperties +// before calling Commit. +// +// we don't free the memory when going into Decommit state. The simplest +// way to implement this without complicating CBaseAllocator is to +// have a Free() function, called to go into decommit state, that does +// nothing and a ReallyFree function called from our destructor that +// actually frees the memory. +//===================================================================== +//===================================================================== + +// Make me one from quartz.dll +STDAPI CreateMemoryAllocator(__deref_out IMemAllocator **ppAllocator); + +class CMemAllocator : public CBaseAllocator +{ + +protected: + + LPBYTE m_pBuffer; // combined memory for all buffers + + // override to free the memory when decommit completes + // - we actually do nothing, and save the memory until deletion. + void Free(void); + + // called from the destructor (and from Alloc if changing size/count) to + // actually free up the memory + void ReallyFree(void); + + // overriden to allocate the memory when commit called + HRESULT Alloc(void); + +public: + /* This goes in the factory template table to create new instances */ + static CUnknown *CreateInstance(__inout_opt LPUNKNOWN, __inout HRESULT *); + + STDMETHODIMP SetProperties( + __in ALLOCATOR_PROPERTIES* pRequest, + __out ALLOCATOR_PROPERTIES* pActual); + + CMemAllocator(__in_opt LPCTSTR , __inout_opt LPUNKNOWN, __inout HRESULT *); +#ifdef UNICODE + CMemAllocator(__in_opt LPCSTR , __inout_opt LPUNKNOWN, __inout HRESULT *); +#endif + ~CMemAllocator(); +}; + +// helper used by IAMovieSetup implementation +STDAPI +AMovieSetupRegisterFilter( const AMOVIESETUP_FILTER * const psetupdata + , IFilterMapper * pIFM + , BOOL bRegister ); + + +/////////////////////////////////////////////////////////////////////////// +// ------------------------------------------------------------------------ +// ------------------------------------------------------------------------ +// ------------------------------------------------------------------------ +// ------------------------------------------------------------------------ +/////////////////////////////////////////////////////////////////////////// + +#endif /* __FILTER__ */ + +//------------------------------------------------------------------------------ +// File: Source.h +// +// Desc: DirectShow base classes - defines classes to simplify creation of +// ActiveX source filters that support continuous generation of data. +// No support is provided for IMediaControl or IMediaPosition. +// +// Copyright (c) 1992-2001 Microsoft Corporation. All rights reserved. +//------------------------------------------------------------------------------ + + +// +// Derive your source filter from CSource. +// During construction either: +// Create some CSourceStream objects to manage your pins +// Provide the user with a means of doing so eg, an IPersistFile interface. +// +// CSource provides: +// IBaseFilter interface management +// IMediaFilter interface management, via CBaseFilter +// Pin counting for CBaseFilter +// +// Derive a class from CSourceStream to manage your output pin types +// Implement GetMediaType/1 to return the type you support. If you support multiple +// types then overide GetMediaType/3, CheckMediaType and GetMediaTypeCount. +// Implement Fillbuffer() to put data into one buffer. +// +// CSourceStream provides: +// IPin management via CBaseOutputPin +// Worker thread management + +#ifndef __CSOURCE__ +#define __CSOURCE__ + +class CSourceStream; // The class that will handle each pin + + +// +// CSource +// +// Override construction to provide a means of creating +// CSourceStream derived objects - ie a way of creating pins. +class CSource : public CBaseFilter { +public: + + CSource(__in_opt LPCTSTR pName, __inout_opt LPUNKNOWN lpunk, CLSID clsid, __inout HRESULT *phr); + CSource(__in_opt LPCTSTR pName, __inout_opt LPUNKNOWN lpunk, CLSID clsid); +#ifdef UNICODE + CSource(__in_opt LPCSTR pName, __inout_opt LPUNKNOWN lpunk, CLSID clsid, __inout HRESULT *phr); + CSource(__in_opt LPCSTR pName, __inout_opt LPUNKNOWN lpunk, CLSID clsid); +#endif + ~CSource(); + + int GetPinCount(void); + CBasePin *GetPin(int n); + + // -- Utilities -- + + CCritSec* pStateLock(void) { return &m_cStateLock; } // provide our critical section + + HRESULT AddPin(__in CSourceStream *); + HRESULT RemovePin(__in CSourceStream *); + + STDMETHODIMP FindPin( + LPCWSTR Id, + __deref_out IPin ** ppPin + ); + + int FindPinNumber(__in IPin *iPin); + +protected: + + int m_iPins; // The number of pins on this filter. Updated by CSourceStream + // constructors & destructors. + CSourceStream **m_paStreams; // the pins on this filter. + + CCritSec m_cStateLock; // Lock this to serialize function accesses to the filter state + +}; + + +// +// CSourceStream +// +// Use this class to manage a stream of data that comes from a +// pin. +// Uses a worker thread to put data on the pin. +class CSourceStream : public CAMThread, public CBaseOutputPin { +public: + + CSourceStream(__in_opt LPCTSTR pObjectName, + __inout HRESULT *phr, + __inout CSource *pms, + __in_opt LPCWSTR pName); +#ifdef UNICODE + CSourceStream(__in_opt LPCSTR pObjectName, + __inout HRESULT *phr, + __inout CSource *pms, + __in_opt LPCWSTR pName); +#endif + virtual ~CSourceStream(void); // virtual destructor ensures derived class destructors are called too. + +protected: + + CSource *m_pFilter; // The parent of this stream + + // * + // * Data Source + // * + // * The following three functions: FillBuffer, OnThreadCreate/Destroy, are + // * called from within the ThreadProc. They are used in the creation of + // * the media samples this pin will provide + // * + + // Override this to provide the worker thread a means + // of processing a buffer + virtual HRESULT FillBuffer(IMediaSample *pSamp) PURE; + + // Called as the thread is created/destroyed - use to perform + // jobs such as start/stop streaming mode + // If OnThreadCreate returns an error the thread will exit. + virtual HRESULT OnThreadCreate(void) {return NOERROR;}; + virtual HRESULT OnThreadDestroy(void) {return NOERROR;}; + virtual HRESULT OnThreadStartPlay(void) {return NOERROR;}; + + // * + // * Worker Thread + // * + + HRESULT Active(void); // Starts up the worker thread + HRESULT Inactive(void); // Exits the worker thread. + +public: + // thread commands + enum Command {CMD_INIT, CMD_PAUSE, CMD_RUN, CMD_STOP, CMD_EXIT}; + HRESULT Init(void) { return CallWorker(CMD_INIT); } + HRESULT Exit(void) { return CallWorker(CMD_EXIT); } + HRESULT Run(void) { return CallWorker(CMD_RUN); } + HRESULT Pause(void) { return CallWorker(CMD_PAUSE); } + HRESULT Stop(void) { return CallWorker(CMD_STOP); } + +protected: + Command GetRequest(void) { return (Command) CAMThread::GetRequest(); } + BOOL CheckRequest(Command *pCom) { return CAMThread::CheckRequest( (DWORD *) pCom); } + + // override these if you want to add thread commands + virtual DWORD ThreadProc(void); // the thread function + + virtual HRESULT DoBufferProcessingLoop(void); // the loop executed whilst running + + + // * + // * AM_MEDIA_TYPE support + // * + + // If you support more than one media type then override these 2 functions + virtual HRESULT CheckMediaType(const CMediaType *pMediaType); + virtual HRESULT GetMediaType(int iPosition, __inout CMediaType *pMediaType); // List pos. 0-n + + // If you support only one type then override this fn. + // This will only be called by the default implementations + // of CheckMediaType and GetMediaType(int, CMediaType*) + // You must override this fn. or the above 2! + virtual HRESULT GetMediaType(__inout CMediaType *pMediaType) {return E_UNEXPECTED;} + + STDMETHODIMP QueryId( + __deref_out LPWSTR * Id + ); +}; + +#endif // __CSOURCE__ + +//------------------------------------------------------------------------------ +// File: CProp.h +// +// Desc: DirectShow base classes. +// +// Copyright (c) 1992-2001 Microsoft Corporation. All rights reserved. +//------------------------------------------------------------------------------ + +#ifndef __CPROP__ +#define __CPROP__ + +// Base property page class. Filters typically expose custom properties by +// implementing special control interfaces, examples are IDirectDrawVideo +// and IQualProp on renderers. This allows property pages to be built that +// use the given interface. Applications such as the ActiveMovie OCX query +// filters for the property pages they support and expose them to the user +// +// This class provides all the framework for a property page. A property +// page is a COM object that supports IPropertyPage. We should be created +// with a resource ID for the dialog which we will load when required. We +// should also be given in the constructor a resource ID for a title string +// we will load from the DLLs STRINGTABLE. The property page titles must be +// stored in resource files so that they can be easily internationalised +// +// We have a number of virtual methods (not PURE) that may be overriden in +// derived classes to query for interfaces and so on. These functions have +// simple implementations here that just return NOERROR. Derived classes +// will almost definately have to override the message handler method called +// OnReceiveMessage. We have a static dialog procedure that calls the method +// so that derived classes don't have to fiddle around with the this pointer + +class AM_NOVTABLE CBasePropertyPage : public IPropertyPage, public CUnknown +{ +protected: + + LPPROPERTYPAGESITE m_pPageSite; // Details for our property site + HWND m_hwnd; // Window handle for the page + HWND m_Dlg; // Actual dialog window handle + BOOL m_bDirty; // Has anything been changed + int m_TitleId; // Resource identifier for title + int m_DialogId; // Dialog resource identifier + + static INT_PTR CALLBACK DialogProc(HWND hwnd, + UINT uMsg, + WPARAM wParam, + LPARAM lParam); + +private: + BOOL m_bObjectSet ; // SetObject has been called or not. +public: + + CBasePropertyPage(__in_opt LPCTSTR pName, // Debug only name + __inout_opt LPUNKNOWN pUnk, // COM Delegator + int DialogId, // Resource ID + int TitleId); // To get tital + +#ifdef UNICODE + CBasePropertyPage(__in_opt LPCSTR pName, + __inout_opt LPUNKNOWN pUnk, + int DialogId, + int TitleId); +#endif + virtual ~CBasePropertyPage() { }; + DECLARE_IUNKNOWN + + // Override these virtual methods + + virtual HRESULT OnConnect(IUnknown *pUnknown) { return NOERROR; }; + virtual HRESULT OnDisconnect() { return NOERROR; }; + virtual HRESULT OnActivate() { return NOERROR; }; + virtual HRESULT OnDeactivate() { return NOERROR; }; + virtual HRESULT OnApplyChanges() { return NOERROR; }; + virtual INT_PTR OnReceiveMessage(HWND hwnd,UINT uMsg,WPARAM wParam,LPARAM lParam); + + // These implement an IPropertyPage interface + + STDMETHODIMP NonDelegatingQueryInterface(REFIID riid, __deref_out void **ppv); + STDMETHODIMP_(ULONG) NonDelegatingRelease(); + STDMETHODIMP_(ULONG) NonDelegatingAddRef(); + STDMETHODIMP SetPageSite(__in_opt LPPROPERTYPAGESITE pPageSite); + STDMETHODIMP Activate(HWND hwndParent, LPCRECT prect,BOOL fModal); + STDMETHODIMP Deactivate(void); + STDMETHODIMP GetPageInfo(__out LPPROPPAGEINFO pPageInfo); + STDMETHODIMP SetObjects(ULONG cObjects, __in_ecount_opt(cObjects) LPUNKNOWN *ppUnk); + STDMETHODIMP Show(UINT nCmdShow); + STDMETHODIMP Move(LPCRECT prect); + STDMETHODIMP IsPageDirty(void) { return m_bDirty ? S_OK : S_FALSE; } + STDMETHODIMP Apply(void); + STDMETHODIMP Help(LPCWSTR lpszHelpDir) { return E_NOTIMPL; } + STDMETHODIMP TranslateAccelerator(__inout LPMSG lpMsg) { return E_NOTIMPL; } +}; + +#endif // __CPROP__ diff --git a/UnityCaptureSample/.gitignore b/UnityCaptureSample/.gitignore new file mode 100644 index 0000000..00be41d --- /dev/null +++ b/UnityCaptureSample/.gitignore @@ -0,0 +1,10 @@ +Library/* +Temp/* +Packages/* +UnityPackageManager/* +obj/* +.vscode/* + +*.csproj +*.sln +*.suo diff --git a/UnityCaptureSample/Assets/CaptureTexture.cs b/UnityCaptureSample/Assets/CaptureTexture.cs new file mode 100644 index 0000000..a01931b --- /dev/null +++ b/UnityCaptureSample/Assets/CaptureTexture.cs @@ -0,0 +1,58 @@ +/* + This sample code is for demonstrating and testing the functionality + of Unity Capture, and is placed in the public domain. + + This code generates a scrolling color texture simply for the purposes of demonstration. + Other uses may include sending a video, another webcam feed or a static image to the output. +*/ + +using UnityEngine; + +public class CaptureTexture : MonoBehaviour +{ + public int width = 320; + public int height = 240; + public MeshRenderer outputRenderer; + Texture2D activeTex; + UnityCapture.Interface captureInterface; + int y = 0; + Color color = Color.red; + + void Start() + { + // Create texture and capture interface + activeTex = new Texture2D(width, height, TextureFormat.ARGB32, false); + captureInterface = new UnityCapture.Interface(UnityCapture.ECaptureDevice.CaptureDevice1); + + if (outputRenderer != null) outputRenderer.material.mainTexture = activeTex; + } + + void OnDestroy() + { + //Cleanup capture interface + captureInterface.Close(); + } + + void Update() + { + // Draw next line on texture + for (int x = 0; x < width; x++) + { + activeTex.SetPixel(x, y, color); + } + + y += 1; + if (y > height) + { + y = 0; + color = new Color(color.g, color.b, color.r); + } + + activeTex.Apply(); + + // Update the capture texture + UnityCapture.ECaptureSendResult result = captureInterface.SendTexture(activeTex); + if (result != UnityCapture.ECaptureSendResult.SUCCESS) + Debug.Log("SendTexture failed: " + result); + } +} diff --git a/UnitySample/Assets/UnityCam/Editor/UnityCamEditor.cs.meta b/UnityCaptureSample/Assets/CaptureTexture.cs.meta similarity index 70% rename from UnitySample/Assets/UnityCam/Editor/UnityCamEditor.cs.meta rename to UnityCaptureSample/Assets/CaptureTexture.cs.meta index f266433..fd7c8f4 100644 --- a/UnitySample/Assets/UnityCam/Editor/UnityCamEditor.cs.meta +++ b/UnityCaptureSample/Assets/CaptureTexture.cs.meta @@ -1,8 +1,9 @@ fileFormatVersion: 2 -guid: 74e7297b37528034ca6e2b4a1f94ef21 -timeCreated: 1463485985 +guid: c8e68187542b37846b4a604d28bd90e1 +timeCreated: 1536559205 licenseType: Free MonoImporter: + externalObjects: {} serializedVersion: 2 defaultReferences: [] executionOrder: 0 diff --git a/UnityCaptureSample/Assets/CubesSwayBeeps.cs b/UnityCaptureSample/Assets/CubesSwayBeeps.cs new file mode 100644 index 0000000..b4fc83a --- /dev/null +++ b/UnityCaptureSample/Assets/CubesSwayBeeps.cs @@ -0,0 +1,86 @@ +/* + This sample code is for demonstrating and testing the functionality + of Unity Capture, and is placed in the public domain. +*/ + +using UnityEngine; + +public class CubesSwayBeeps : MonoBehaviour +{ + public float RotationAmount = 6f, RotationSpeedX = 2.5f, RotationSpeedY = 1.75f; + public int CubeCount = 10; + public Material CubeMaterial = null; + public bool EnableSyncBeeps = true; + public float BeepDuration = 1/60f*3; + public Color[] PerFrameBackgroundColors = new Color[] { Color.gray }; + + Camera CameraComp; + Transform[] CubeTransforms; + Vector3[] CubeSpeeds; + ulong AudioPosition; + float AudioStartTime; + + void Start() + { + CameraComp = GetComponent(); + + int TotalCubeCount = CubeCount*CubeCount*CubeCount; + CubeTransforms = new Transform[TotalCubeCount]; + CubeSpeeds = new Vector3[TotalCubeCount]; + GameObject CubeHolder = new GameObject("CubeHolder"); + for (int i = 0; i < TotalCubeCount; i++) + { + int x = (i / (CubeCount * CubeCount)), y = ((i / CubeCount) % CubeCount), z = (i % CubeCount); + GameObject o = GameObject.CreatePrimitive(PrimitiveType.Cube); + o.transform.parent = CubeHolder.transform; + o.transform.position = new Vector3(5 * (x - CubeCount / 2), 5 * (y - CubeCount / 2), 5 * (z - CubeCount / 2)); + if (CubeMaterial != null) o.GetComponent().material = CubeMaterial; + CubeTransforms[i] = o.transform; + CubeSpeeds[i] = Random.insideUnitSphere * 50; + } + + if (EnableSyncBeeps) + { + AudioClip myClip = AudioClip.Create("AudioBeeps", 44100/60, 1, 44100, true, OnAudioRead); + AudioSource aud = gameObject.AddComponent(); + aud.clip = myClip; + aud.loop = true; + AudioPosition = 0; + AudioStartTime = Time.realtimeSinceStartup; + aud.Play(); + } + } + + void OnAudioRead(float[] data) + { + const float SineSpeed = 440f * Mathf.PI * 2f / 44100f; //440hz beeps + for (int count = 0; count < data.Length; AudioPosition++, count++) + { + bool SoundDoBeep = ((AudioPosition % 44100) < (44100*BeepDuration)); //beep for 1 second + data[count] = Mathf.Sign(Mathf.Sin(SineSpeed * AudioPosition)) * (SoundDoBeep ? 1f : 0f); + } + } + + void Update() + { + transform.localRotation = Quaternion.Euler(new Vector3(Mathf.Cos(Time.time * RotationSpeedX), Mathf.Sin(Time.time * RotationSpeedY)) * RotationAmount); + + for (int i = 0; i < CubeTransforms.Length; i++) + { + CubeTransforms[i].rotation = Quaternion.Euler(CubeSpeeds[i] * Time.time); + } + + CameraComp.backgroundColor = PerFrameBackgroundColors[Time.frameCount % PerFrameBackgroundColors.Length]; + + if (EnableSyncBeeps) + { + bool SoundDoBeep = (((Time.realtimeSinceStartup - AudioStartTime) % 1.0f) < BeepDuration); + if (SoundDoBeep) CameraComp.backgroundColor = Color.red; + } + } + + void OnGUI() + { + GUI.Box(new Rect(20, 20, 250, 25), "Drawing in OnGUI is not captured"); + } +} diff --git a/UnitySample/Assets/UnityCam/Example/Scripts/JitterMotion.cs.meta b/UnityCaptureSample/Assets/CubesSwayBeeps.cs.meta similarity index 100% rename from UnitySample/Assets/UnityCam/Example/Scripts/JitterMotion.cs.meta rename to UnityCaptureSample/Assets/CubesSwayBeeps.cs.meta diff --git a/UnityCaptureSample/Assets/MultiCam.cs b/UnityCaptureSample/Assets/MultiCam.cs new file mode 100644 index 0000000..5e84df1 --- /dev/null +++ b/UnityCaptureSample/Assets/MultiCam.cs @@ -0,0 +1,38 @@ +/* + This sample code is for demonstrating and testing the functionality + of Unity Capture, and is placed in the public domain. +*/ + +using UnityEngine; + +public class MultiCam : MonoBehaviour +{ + public int CaptureResolutionWidth = 1920, CaptureResolutionHeight = 1080; + public Camera CaptureCamera1, CaptureCamera2; + + void Awake() + { + Camera RenderToScreenCamera = gameObject.GetComponent(); + if (RenderToScreenCamera == null) gameObject.AddComponent(); + RenderToScreenCamera.clearFlags = CameraClearFlags.Nothing; + RenderToScreenCamera.cullingMask = 0; + RenderToScreenCamera.depth = 100; + RenderToScreenCamera.useOcclusionCulling = false; + RenderToScreenCamera.allowHDR = false; + RenderToScreenCamera.allowMSAA = false; + RenderToScreenCamera.allowDynamicResolution = false; + RenderToScreenCamera.stereoTargetEye = StereoTargetEyeMask.None; + CaptureCamera1.targetTexture = new RenderTexture(CaptureResolutionWidth, CaptureResolutionHeight, 24); + CaptureCamera2.targetTexture = new RenderTexture(CaptureResolutionWidth, CaptureResolutionHeight, 24); + } + + void OnPostRender() + { + float w = Screen.width, whalf = w/2, h = Screen.height; + GL.PushMatrix(); + GL.LoadPixelMatrix(); + Graphics.DrawTexture(new Rect( 0, h, whalf, -h), CaptureCamera1.targetTexture); + Graphics.DrawTexture(new Rect(whalf, h, whalf, -h), CaptureCamera2.targetTexture); + GL.PopMatrix(); + } +} diff --git a/UnitySample/Assets/UnityCam/Example/Scripts/Bloom.cs.meta b/UnityCaptureSample/Assets/MultiCam.cs.meta similarity index 70% rename from UnitySample/Assets/UnityCam/Example/Scripts/Bloom.cs.meta rename to UnityCaptureSample/Assets/MultiCam.cs.meta index 2dbc5f3..4ec88dd 100644 --- a/UnitySample/Assets/UnityCam/Example/Scripts/Bloom.cs.meta +++ b/UnityCaptureSample/Assets/MultiCam.cs.meta @@ -1,8 +1,9 @@ fileFormatVersion: 2 -guid: 0a06c208bba794b458de7d55f7afb205 -timeCreated: 1463487675 +guid: f7196fa938037bb46be5bc12531f7f10 +timeCreated: 1530683132 licenseType: Free MonoImporter: + externalObjects: {} serializedVersion: 2 defaultReferences: [] executionOrder: 0 diff --git a/UnitySample/Assets/AssetStoreTools.meta b/UnityCaptureSample/Assets/UnityCapture.meta similarity index 60% rename from UnitySample/Assets/AssetStoreTools.meta rename to UnityCaptureSample/Assets/UnityCapture.meta index f082271..a74d21f 100644 --- a/UnitySample/Assets/AssetStoreTools.meta +++ b/UnityCaptureSample/Assets/UnityCapture.meta @@ -1,9 +1,10 @@ fileFormatVersion: 2 -guid: 98897acf5e3f964469cb47ff54c6ba54 +guid: 64daacfb1be37bb4085e1ff8a9b4cceb folderAsset: yes -timeCreated: 1466480510 +timeCreated: 1519955760 licenseType: Free DefaultImporter: + externalObjects: {} userData: assetBundleName: assetBundleVariant: diff --git a/UnitySample/Assets/Plugins.meta b/UnityCaptureSample/Assets/UnityCapture/Plugins.meta similarity index 60% rename from UnitySample/Assets/Plugins.meta rename to UnityCaptureSample/Assets/UnityCapture/Plugins.meta index d0ebfb4..5eaae50 100644 --- a/UnitySample/Assets/Plugins.meta +++ b/UnityCaptureSample/Assets/UnityCapture/Plugins.meta @@ -1,9 +1,10 @@ fileFormatVersion: 2 -guid: dcb35e94895d1184d8a825a51d9ead28 +guid: f452a138547dbb34b9edfa5d6695c929 folderAsset: yes -timeCreated: 1460524578 +timeCreated: 1519955869 licenseType: Free DefaultImporter: + externalObjects: {} userData: assetBundleName: assetBundleVariant: diff --git a/UnitySample/Assets/Plugins/x86.meta b/UnityCaptureSample/Assets/UnityCapture/Plugins/x86.meta similarity index 60% rename from UnitySample/Assets/Plugins/x86.meta rename to UnityCaptureSample/Assets/UnityCapture/Plugins/x86.meta index 1a9613b..9f73c74 100644 --- a/UnitySample/Assets/Plugins/x86.meta +++ b/UnityCaptureSample/Assets/UnityCapture/Plugins/x86.meta @@ -1,9 +1,10 @@ fileFormatVersion: 2 -guid: 2234430ee40d8fa42a6a8a8b0f3b4a02 +guid: 9cd051131b4a37240be23bed28adaa6a folderAsset: yes -timeCreated: 1460542987 +timeCreated: 1519954762 licenseType: Free DefaultImporter: + externalObjects: {} userData: assetBundleName: assetBundleVariant: diff --git a/UnityCaptureSample/Assets/UnityCapture/Plugins/x86/UnityCapturePlugin.dll b/UnityCaptureSample/Assets/UnityCapture/Plugins/x86/UnityCapturePlugin.dll new file mode 100644 index 0000000..a2fabbe Binary files /dev/null and b/UnityCaptureSample/Assets/UnityCapture/Plugins/x86/UnityCapturePlugin.dll differ diff --git a/UnityCaptureSample/Assets/UnityCapture/Plugins/x86/UnityCapturePlugin.dll.meta b/UnityCaptureSample/Assets/UnityCapture/Plugins/x86/UnityCapturePlugin.dll.meta new file mode 100644 index 0000000..400ca6c --- /dev/null +++ b/UnityCaptureSample/Assets/UnityCapture/Plugins/x86/UnityCapturePlugin.dll.meta @@ -0,0 +1,87 @@ +fileFormatVersion: 2 +guid: 27f4f8798f88ca0459e783408e6846a1 +timeCreated: 1519954762 +licenseType: Free +PluginImporter: + externalObjects: {} + serializedVersion: 2 + iconMap: {} + executionOrder: {} + isPreloaded: 0 + isOverridable: 0 + platformData: + - first: + '': OSXIntel + second: + enabled: 1 + settings: + CPU: AnyCPU + - first: + '': OSXIntel64 + second: + enabled: 0 + settings: + CPU: None + - first: + Any: + second: + enabled: 1 + settings: {} + - first: + Editor: Editor + second: + enabled: 0 + settings: + CPU: x86 + DefaultValueInitialized: true + - first: + Facebook: Win + second: + enabled: 1 + settings: + CPU: AnyCPU + - first: + Facebook: Win64 + second: + enabled: 0 + settings: + CPU: None + - first: + Standalone: Linux + second: + enabled: 1 + settings: + CPU: x86 + - first: + Standalone: Linux64 + second: + enabled: 0 + settings: + CPU: None + - first: + Standalone: LinuxUniversal + second: + enabled: 1 + settings: + CPU: x86 + - first: + Standalone: OSXUniversal + second: + enabled: 0 + settings: + CPU: x86 + - first: + Standalone: Win + second: + enabled: 1 + settings: + CPU: AnyCPU + - first: + Standalone: Win64 + second: + enabled: 0 + settings: + CPU: None + userData: + assetBundleName: + assetBundleVariant: diff --git a/UnitySample/Assets/Plugins/x86_64.meta b/UnityCaptureSample/Assets/UnityCapture/Plugins/x86_64.meta similarity index 100% rename from UnitySample/Assets/Plugins/x86_64.meta rename to UnityCaptureSample/Assets/UnityCapture/Plugins/x86_64.meta diff --git a/UnityCaptureSample/Assets/UnityCapture/Plugins/x86_64/UnityCapturePlugin.dll b/UnityCaptureSample/Assets/UnityCapture/Plugins/x86_64/UnityCapturePlugin.dll new file mode 100644 index 0000000..adc1655 Binary files /dev/null and b/UnityCaptureSample/Assets/UnityCapture/Plugins/x86_64/UnityCapturePlugin.dll differ diff --git a/UnityCaptureSample/Assets/UnityCapture/Plugins/x86_64/UnityCapturePlugin.dll.meta b/UnityCaptureSample/Assets/UnityCapture/Plugins/x86_64/UnityCapturePlugin.dll.meta new file mode 100644 index 0000000..d626320 --- /dev/null +++ b/UnityCaptureSample/Assets/UnityCapture/Plugins/x86_64/UnityCapturePlugin.dll.meta @@ -0,0 +1,87 @@ +fileFormatVersion: 2 +guid: ec414908dccab334fb32e19ccf8879bd +timeCreated: 1519867776 +licenseType: Free +PluginImporter: + externalObjects: {} + serializedVersion: 2 + iconMap: {} + executionOrder: {} + isPreloaded: 0 + isOverridable: 0 + platformData: + - first: + '': OSXIntel + second: + enabled: 0 + settings: + CPU: None + - first: + '': OSXIntel64 + second: + enabled: 1 + settings: + CPU: AnyCPU + - first: + Any: + second: + enabled: 1 + settings: {} + - first: + Editor: Editor + second: + enabled: 0 + settings: + CPU: x86_64 + DefaultValueInitialized: true + - first: + Facebook: Win + second: + enabled: 0 + settings: + CPU: None + - first: + Facebook: Win64 + second: + enabled: 1 + settings: + CPU: AnyCPU + - first: + Standalone: Linux + second: + enabled: 0 + settings: + CPU: None + - first: + Standalone: Linux64 + second: + enabled: 1 + settings: + CPU: x86_64 + - first: + Standalone: LinuxUniversal + second: + enabled: 1 + settings: + CPU: x86_64 + - first: + Standalone: OSXUniversal + second: + enabled: 0 + settings: + CPU: x86_64 + - first: + Standalone: Win + second: + enabled: 0 + settings: + CPU: None + - first: + Standalone: Win64 + second: + enabled: 1 + settings: + CPU: AnyCPU + userData: + assetBundleName: + assetBundleVariant: diff --git a/UnityCaptureSample/Assets/UnityCapture/UnityCapture.cs b/UnityCaptureSample/Assets/UnityCapture/UnityCapture.cs new file mode 100644 index 0000000..d8cbc6e --- /dev/null +++ b/UnityCaptureSample/Assets/UnityCapture/UnityCapture.cs @@ -0,0 +1,118 @@ +/* + Unity Capture + Copyright (c) 2018 Bernhard Schelling + + Feature contributors: + Brandon J Matthews (low-level interface for custom texture capture) + + Based on UnityCam + https://github.com/mrayy/UnityCam + Copyright (c) 2016 MHD Yamen Saraiji + + This software is provided 'as-is', without any express or implied + warranty. In no event will the authors be held liable for any damages + arising from the use of this software. + + Permission is granted to anyone to use this software for any purpose, + including commercial applications, and to alter it and redistribute it + freely, subject to the following restrictions: + + 1. The origin of this software must not be misrepresented; you must not + claim that you wrote the original software. If you use this software + in a product, an acknowledgment in the product documentation would be + appreciated but is not required. + 2. Altered source versions must be plainly marked as such, and must not be + misrepresented as being the original software. + 3. This notice may not be removed or altered from any source distribution. +*/ + +using UnityEngine; + +[RequireComponent(typeof(Camera))] +public class UnityCapture : MonoBehaviour +{ + public enum ECaptureDevice { CaptureDevice1 = 0, CaptureDevice2 = 1, CaptureDevice3 = 2, CaptureDevice4 = 3, CaptureDevice5 = 4, CaptureDevice6 = 5, CaptureDevice7 = 6, CaptureDevice8 = 7, CaptureDevice9 = 8, CaptureDevice10 = 9 } + public enum EResizeMode { Disabled = 0, LinearResize = 1 } + public enum EMirrorMode { Disabled = 0, MirrorHorizontally = 1 } + public enum ECaptureSendResult { SUCCESS = 0, WARNING_FRAMESKIP = 1, WARNING_CAPTUREINACTIVE = 2, ERROR_UNSUPPORTEDGRAPHICSDEVICE = 100, ERROR_PARAMETER = 101, ERROR_TOOLARGERESOLUTION = 102, ERROR_TEXTUREFORMAT = 103, ERROR_READTEXTURE = 104, ERROR_INVALIDCAPTUREINSTANCEPTR = 200 }; + + [SerializeField] [Tooltip("Capture device index")] public ECaptureDevice CaptureDevice = ECaptureDevice.CaptureDevice1; + [SerializeField] [Tooltip("Scale image if Unity and capture resolution don't match (can introduce frame dropping, not recommended)")] public EResizeMode ResizeMode = EResizeMode.Disabled; + [SerializeField] [Tooltip("How many milliseconds to wait for a new frame until sending is considered to be stopped")] public int Timeout = 1000; + [SerializeField] [Tooltip("Mirror captured output image")] public EMirrorMode MirrorMode = EMirrorMode.Disabled; + [SerializeField] [Tooltip("Introduce a frame of latency in favor of frame rate")] public bool DoubleBuffering = false; + [SerializeField] [Tooltip("Check to enable VSync during capturing")] public bool EnableVSync = false; + [SerializeField] [Tooltip("Set the desired render target frame rate")] public int TargetFrameRate = 60; + [SerializeField] [Tooltip("Check to disable output of warnings")] public bool HideWarnings = false; + + Interface CaptureInterface; + + void Awake() + { + QualitySettings.vSyncCount = (EnableVSync ? 1 : 0); + Application.targetFrameRate = TargetFrameRate; + + if (Application.runInBackground == false) + { + Debug.LogWarning("Application.runInBackground switched to enabled for capture streaming"); + Application.runInBackground = true; + } + } + + void Start() + { + CaptureInterface = new Interface(CaptureDevice); + } + + void OnDestroy() + { + CaptureInterface.Close(); + } + + void OnRenderImage(RenderTexture source, RenderTexture destination) + { + Graphics.Blit(source, destination); + switch (CaptureInterface.SendTexture(source, Timeout, DoubleBuffering, ResizeMode, MirrorMode)) + { + case ECaptureSendResult.SUCCESS: break; + case ECaptureSendResult.WARNING_FRAMESKIP: if (!HideWarnings) Debug.LogWarning("[UnityCapture] Capture device did skip a frame read, capture frame rate will not match render frame rate."); break; + case ECaptureSendResult.WARNING_CAPTUREINACTIVE: if (!HideWarnings) Debug.LogWarning("[UnityCapture] Capture device is inactive"); break; + case ECaptureSendResult.ERROR_UNSUPPORTEDGRAPHICSDEVICE: Debug.LogError("[UnityCapture] Unsupported graphics device (only D3D11 supported)"); break; + case ECaptureSendResult.ERROR_PARAMETER: Debug.LogError("[UnityCapture] Input parameter error"); break; + case ECaptureSendResult.ERROR_TOOLARGERESOLUTION: Debug.LogError("[UnityCapture] Render resolution is too large to send to capture device"); break; + case ECaptureSendResult.ERROR_TEXTUREFORMAT: Debug.LogError("[UnityCapture] Render texture format is unsupported (only basic non-HDR (ARGB32) and HDR (FP16/ARGB Half) formats are supported)"); break; + case ECaptureSendResult.ERROR_READTEXTURE: Debug.LogError("[UnityCapture] Error while reading texture image data"); break; + case ECaptureSendResult.ERROR_INVALIDCAPTUREINSTANCEPTR: Debug.LogError("[UnityCapture] Invalid Capture Instance Pointer"); break; + } + } + + public class Interface + { + [System.Runtime.InteropServices.DllImport("UnityCapturePlugin")] extern static System.IntPtr CaptureCreateInstance(int CapNum); + [System.Runtime.InteropServices.DllImport("UnityCapturePlugin")] extern static void CaptureDeleteInstance(System.IntPtr instance); + [System.Runtime.InteropServices.DllImport("UnityCapturePlugin")] extern static ECaptureSendResult CaptureSendTexture(System.IntPtr instance, System.IntPtr nativetexture, int Timeout, bool UseDoubleBuffering, EResizeMode ResizeMode, EMirrorMode MirrorMode, bool IsLinearColorSpace); + System.IntPtr CaptureInstance; + + public Interface(ECaptureDevice CaptureDevice) + { + CaptureInstance = CaptureCreateInstance((int)CaptureDevice); + } + + ~Interface() + { + Close(); + } + + public void Close() + { + if (CaptureInstance != System.IntPtr.Zero) CaptureDeleteInstance(CaptureInstance); + CaptureInstance = System.IntPtr.Zero; + } + + public ECaptureSendResult SendTexture(Texture Source, int Timeout = 1000, bool DoubleBuffering = false, EResizeMode ResizeMode = EResizeMode.Disabled, EMirrorMode MirrorMode = EMirrorMode.Disabled) + { + if (CaptureInstance == System.IntPtr.Zero) return ECaptureSendResult.ERROR_INVALIDCAPTUREINSTANCEPTR; + return CaptureSendTexture(CaptureInstance, Source.GetNativeTexturePtr(), Timeout, DoubleBuffering, ResizeMode, MirrorMode, QualitySettings.activeColorSpace == ColorSpace.Linear); + } + } +} diff --git a/UnitySample/Assets/UnityCam/Scripts/UnityCam.cs.meta b/UnityCaptureSample/Assets/UnityCapture/UnityCapture.cs.meta similarity index 100% rename from UnitySample/Assets/UnityCam/Scripts/UnityCam.cs.meta rename to UnityCaptureSample/Assets/UnityCapture/UnityCapture.cs.meta diff --git a/UnityCaptureSample/Assets/UnityCaptureExample.unity b/UnityCaptureSample/Assets/UnityCaptureExample.unity new file mode 100644 index 0000000..c7addf0 --- /dev/null +++ b/UnityCaptureSample/Assets/UnityCaptureExample.unity @@ -0,0 +1,289 @@ +%YAML 1.1 +%TAG !u! tag:unity3d.com,2011: +--- !u!29 &1 +OcclusionCullingSettings: + m_ObjectHideFlags: 0 + serializedVersion: 2 + m_OcclusionBakeSettings: + smallestOccluder: 5 + smallestHole: 0.25 + backfaceThreshold: 100 + m_SceneGUID: 00000000000000000000000000000000 + m_OcclusionCullingData: {fileID: 0} +--- !u!104 &2 +RenderSettings: + m_ObjectHideFlags: 0 + serializedVersion: 8 + m_Fog: 0 + m_FogColor: {r: 0.5, g: 0.5, b: 0.5, a: 1} + m_FogMode: 3 + m_FogDensity: 0.01 + m_LinearFogStart: 0 + m_LinearFogEnd: 300 + m_AmbientSkyColor: {r: 0.212, g: 0.227, b: 0.259, a: 1} + m_AmbientEquatorColor: {r: 0.114, g: 0.125, b: 0.133, a: 1} + m_AmbientGroundColor: {r: 0.047, g: 0.043, b: 0.035, a: 1} + m_AmbientIntensity: 1 + m_AmbientMode: 0 + m_SubtractiveShadowColor: {r: 0.42, g: 0.478, b: 0.627, a: 1} + m_SkyboxMaterial: {fileID: 10304, guid: 0000000000000000f000000000000000, type: 0} + m_HaloStrength: 0.5 + m_FlareStrength: 1 + m_FlareFadeSpeed: 3 + m_HaloTexture: {fileID: 0} + m_SpotCookie: {fileID: 10001, guid: 0000000000000000e000000000000000, type: 0} + m_DefaultReflectionMode: 0 + m_DefaultReflectionResolution: 128 + m_ReflectionBounces: 1 + m_ReflectionIntensity: 1 + m_CustomReflection: {fileID: 0} + m_Sun: {fileID: 0} + m_IndirectSpecularColor: {r: 0.44657898, g: 0.4964133, b: 0.5748178, a: 1} +--- !u!157 &3 +LightmapSettings: + m_ObjectHideFlags: 0 + serializedVersion: 11 + m_GIWorkflowMode: 0 + m_GISettings: + serializedVersion: 2 + m_BounceScale: 1 + m_IndirectOutputScale: 1 + m_AlbedoBoost: 1 + m_TemporalCoherenceThreshold: 1 + m_EnvironmentLightingMode: 0 + m_EnableBakedLightmaps: 1 + m_EnableRealtimeLightmaps: 1 + m_LightmapEditorSettings: + serializedVersion: 9 + m_Resolution: 2 + m_BakeResolution: 40 + m_TextureWidth: 1024 + m_TextureHeight: 1024 + m_AO: 0 + m_AOMaxDistance: 1 + m_CompAOExponent: 0 + m_CompAOExponentDirect: 0 + m_Padding: 2 + m_LightmapParameters: {fileID: 0} + m_LightmapsBakeMode: 1 + m_TextureCompression: 1 + m_FinalGather: 0 + m_FinalGatherFiltering: 1 + m_FinalGatherRayCount: 1024 + m_ReflectionCompression: 2 + m_MixedBakeMode: 1 + m_BakeBackend: 0 + m_PVRSampling: 1 + m_PVRDirectSampleCount: 32 + m_PVRSampleCount: 500 + m_PVRBounces: 2 + m_PVRFilterTypeDirect: 0 + m_PVRFilterTypeIndirect: 0 + m_PVRFilterTypeAO: 0 + m_PVRFilteringMode: 0 + m_PVRCulling: 1 + m_PVRFilteringGaussRadiusDirect: 1 + m_PVRFilteringGaussRadiusIndirect: 5 + m_PVRFilteringGaussRadiusAO: 2 + m_PVRFilteringAtrousPositionSigmaDirect: 0.5 + m_PVRFilteringAtrousPositionSigmaIndirect: 2 + m_PVRFilteringAtrousPositionSigmaAO: 1 + m_ShowResolutionOverlay: 1 + m_LightingDataAsset: {fileID: 0} + m_UseShadowmask: 0 +--- !u!196 &4 +NavMeshSettings: + serializedVersion: 2 + m_ObjectHideFlags: 0 + m_BuildSettings: + serializedVersion: 2 + agentTypeID: 0 + agentRadius: 0.5 + agentHeight: 2 + agentSlope: 45 + agentClimb: 0.4 + ledgeDropHeight: 0 + maxJumpAcrossDistance: 0 + minRegionArea: 2 + manualCellSize: 0 + cellSize: 0.16666667 + manualTileSize: 0 + tileSize: 256 + accuratePlacement: 0 + debug: + m_Flags: 0 + m_NavMeshData: {fileID: 0} +--- !u!1 &1126630849 +GameObject: + m_ObjectHideFlags: 0 + m_PrefabParentObject: {fileID: 0} + m_PrefabInternal: {fileID: 0} + serializedVersion: 5 + m_Component: + - component: {fileID: 1126630855} + - component: {fileID: 1126630854} + - component: {fileID: 1126630853} + - component: {fileID: 1126630851} + - component: {fileID: 1126630852} + - component: {fileID: 1126630850} + m_Layer: 0 + m_Name: Camera + m_TagString: Untagged + m_Icon: {fileID: 0} + m_NavMeshLayer: 0 + m_StaticEditorFlags: 0 + m_IsActive: 1 +--- !u!114 &1126630850 +MonoBehaviour: + m_ObjectHideFlags: 0 + m_PrefabParentObject: {fileID: 0} + m_PrefabInternal: {fileID: 0} + m_GameObject: {fileID: 1126630849} + m_Enabled: 1 + m_EditorHideFlags: 0 + m_Script: {fileID: 11500000, guid: 5f1106d3744ef824496276c8274506b2, type: 3} + m_Name: + m_EditorClassIdentifier: + ResizeMode: 0 + MirrorMode: 0 +--- !u!81 &1126630851 +AudioListener: + m_ObjectHideFlags: 0 + m_PrefabParentObject: {fileID: 0} + m_PrefabInternal: {fileID: 0} + m_GameObject: {fileID: 1126630849} + m_Enabled: 1 +--- !u!114 &1126630852 +MonoBehaviour: + m_ObjectHideFlags: 0 + m_PrefabParentObject: {fileID: 0} + m_PrefabInternal: {fileID: 0} + m_GameObject: {fileID: 1126630849} + m_Enabled: 1 + m_EditorHideFlags: 0 + m_Script: {fileID: 11500000, guid: 70cec3f0490dff14fbf273abb6a3a72d, type: 3} + m_Name: + m_EditorClassIdentifier: + CubeMaterial: {fileID: 10303, guid: 0000000000000000f000000000000000, type: 0} + EnableSyncBeeps: false +--- !u!124 &1126630853 +Behaviour: + m_ObjectHideFlags: 0 + m_PrefabParentObject: {fileID: 0} + m_PrefabInternal: {fileID: 0} + m_GameObject: {fileID: 1126630849} + m_Enabled: 1 +--- !u!20 &1126630854 +Camera: + m_ObjectHideFlags: 0 + m_PrefabParentObject: {fileID: 0} + m_PrefabInternal: {fileID: 0} + m_GameObject: {fileID: 1126630849} + m_Enabled: 1 + serializedVersion: 2 + m_ClearFlags: 2 + m_BackGroundColor: {r: 0.19215687, g: 0.3019608, b: 0.4745098, a: 0} + m_NormalizedViewPortRect: + serializedVersion: 2 + x: 0 + y: 0 + width: 1 + height: 1 + near clip plane: 0.3 + far clip plane: 1000 + field of view: 60 + orthographic: 0 + orthographic size: 5 + m_Depth: 0 + m_CullingMask: + serializedVersion: 2 + m_Bits: 4294967295 + m_RenderingPath: -1 + m_TargetTexture: {fileID: 0} + m_TargetDisplay: 0 + m_TargetEye: 3 + m_HDR: 0 + m_AllowMSAA: 1 + m_AllowDynamicResolution: 0 + m_ForceIntoRT: 0 + m_OcclusionCulling: 1 + m_StereoConvergence: 10 + m_StereoSeparation: 0.022 +--- !u!4 &1126630855 +Transform: + m_ObjectHideFlags: 0 + m_PrefabParentObject: {fileID: 0} + m_PrefabInternal: {fileID: 0} + m_GameObject: {fileID: 1126630849} + m_LocalRotation: {x: 0, y: 0, z: 0, w: 1} + m_LocalPosition: {x: -6.91, y: -2.4, z: 0} + m_LocalScale: {x: 1, y: 1, z: 1} + m_Children: [] + m_Father: {fileID: 0} + m_RootOrder: 1 + m_LocalEulerAnglesHint: {x: 0, y: 0, z: 0} +--- !u!1 &1251162945 +GameObject: + m_ObjectHideFlags: 0 + m_PrefabParentObject: {fileID: 0} + m_PrefabInternal: {fileID: 0} + serializedVersion: 5 + m_Component: + - component: {fileID: 1251162947} + - component: {fileID: 1251162946} + m_Layer: 0 + m_Name: Directional Light + m_TagString: Untagged + m_Icon: {fileID: 0} + m_NavMeshLayer: 0 + m_StaticEditorFlags: 0 + m_IsActive: 1 +--- !u!108 &1251162946 +Light: + m_ObjectHideFlags: 0 + m_PrefabParentObject: {fileID: 0} + m_PrefabInternal: {fileID: 0} + m_GameObject: {fileID: 1251162945} + m_Enabled: 1 + serializedVersion: 8 + m_Type: 1 + m_Color: {r: 1, g: 0.95686275, b: 0.8392157, a: 1} + m_Intensity: 1 + m_Range: 10 + m_SpotAngle: 30 + m_CookieSize: 10 + m_Shadows: + m_Type: 2 + m_Resolution: -1 + m_CustomResolution: -1 + m_Strength: 1 + m_Bias: 0.05 + m_NormalBias: 0.4 + m_NearPlane: 0.2 + m_Cookie: {fileID: 0} + m_DrawHalo: 0 + m_Flare: {fileID: 0} + m_RenderMode: 0 + m_CullingMask: + serializedVersion: 2 + m_Bits: 4294967295 + m_Lightmapping: 4 + m_AreaSize: {x: 1, y: 1} + m_BounceIntensity: 1 + m_ColorTemperature: 6570 + m_UseColorTemperature: 0 + m_ShadowRadius: 0 + m_ShadowAngle: 0 +--- !u!4 &1251162947 +Transform: + m_ObjectHideFlags: 0 + m_PrefabParentObject: {fileID: 0} + m_PrefabInternal: {fileID: 0} + m_GameObject: {fileID: 1251162945} + m_LocalRotation: {x: 0.40821797, y: -0.23456974, z: 0.10938168, w: 0.8754261} + m_LocalPosition: {x: 0, y: 3, z: 0} + m_LocalScale: {x: 1, y: 1, z: 1} + m_Children: [] + m_Father: {fileID: 0} + m_RootOrder: 0 + m_LocalEulerAnglesHint: {x: 0, y: 0, z: 0} diff --git a/UnitySample/Assets/UnityCam/Example/CubesScene.unity.meta b/UnityCaptureSample/Assets/UnityCaptureExample.unity.meta similarity index 100% rename from UnitySample/Assets/UnityCam/Example/CubesScene.unity.meta rename to UnityCaptureSample/Assets/UnityCaptureExample.unity.meta diff --git a/UnityCaptureSample/Assets/UnityCaptureMultiCam.unity b/UnityCaptureSample/Assets/UnityCaptureMultiCam.unity new file mode 100644 index 0000000..bdda056 --- /dev/null +++ b/UnityCaptureSample/Assets/UnityCaptureMultiCam.unity @@ -0,0 +1,690 @@ +%YAML 1.1 +%TAG !u! tag:unity3d.com,2011: +--- !u!29 &1 +OcclusionCullingSettings: + m_ObjectHideFlags: 0 + serializedVersion: 2 + m_OcclusionBakeSettings: + smallestOccluder: 5 + smallestHole: 0.25 + backfaceThreshold: 100 + m_SceneGUID: 00000000000000000000000000000000 + m_OcclusionCullingData: {fileID: 0} +--- !u!104 &2 +RenderSettings: + m_ObjectHideFlags: 0 + serializedVersion: 8 + m_Fog: 0 + m_FogColor: {r: 0.5, g: 0.5, b: 0.5, a: 1} + m_FogMode: 3 + m_FogDensity: 0.01 + m_LinearFogStart: 0 + m_LinearFogEnd: 300 + m_AmbientSkyColor: {r: 0.212, g: 0.227, b: 0.259, a: 1} + m_AmbientEquatorColor: {r: 0.114, g: 0.125, b: 0.133, a: 1} + m_AmbientGroundColor: {r: 0.047, g: 0.043, b: 0.035, a: 1} + m_AmbientIntensity: 1 + m_AmbientMode: 0 + m_SubtractiveShadowColor: {r: 0.42, g: 0.478, b: 0.627, a: 1} + m_SkyboxMaterial: {fileID: 10304, guid: 0000000000000000f000000000000000, type: 0} + m_HaloStrength: 0.5 + m_FlareStrength: 1 + m_FlareFadeSpeed: 3 + m_HaloTexture: {fileID: 0} + m_SpotCookie: {fileID: 10001, guid: 0000000000000000e000000000000000, type: 0} + m_DefaultReflectionMode: 0 + m_DefaultReflectionResolution: 128 + m_ReflectionBounces: 1 + m_ReflectionIntensity: 1 + m_CustomReflection: {fileID: 0} + m_Sun: {fileID: 0} + m_IndirectSpecularColor: {r: 0.44657898, g: 0.4964133, b: 0.5748178, a: 1} +--- !u!157 &3 +LightmapSettings: + m_ObjectHideFlags: 0 + serializedVersion: 11 + m_GIWorkflowMode: 0 + m_GISettings: + serializedVersion: 2 + m_BounceScale: 1 + m_IndirectOutputScale: 1 + m_AlbedoBoost: 1 + m_TemporalCoherenceThreshold: 1 + m_EnvironmentLightingMode: 0 + m_EnableBakedLightmaps: 1 + m_EnableRealtimeLightmaps: 1 + m_LightmapEditorSettings: + serializedVersion: 9 + m_Resolution: 2 + m_BakeResolution: 40 + m_TextureWidth: 1024 + m_TextureHeight: 1024 + m_AO: 0 + m_AOMaxDistance: 1 + m_CompAOExponent: 1 + m_CompAOExponentDirect: 0 + m_Padding: 2 + m_LightmapParameters: {fileID: 0} + m_LightmapsBakeMode: 1 + m_TextureCompression: 1 + m_FinalGather: 0 + m_FinalGatherFiltering: 1 + m_FinalGatherRayCount: 256 + m_ReflectionCompression: 2 + m_MixedBakeMode: 2 + m_BakeBackend: 0 + m_PVRSampling: 1 + m_PVRDirectSampleCount: 32 + m_PVRSampleCount: 500 + m_PVRBounces: 2 + m_PVRFilterTypeDirect: 0 + m_PVRFilterTypeIndirect: 0 + m_PVRFilterTypeAO: 0 + m_PVRFilteringMode: 1 + m_PVRCulling: 1 + m_PVRFilteringGaussRadiusDirect: 1 + m_PVRFilteringGaussRadiusIndirect: 5 + m_PVRFilteringGaussRadiusAO: 2 + m_PVRFilteringAtrousPositionSigmaDirect: 0.5 + m_PVRFilteringAtrousPositionSigmaIndirect: 2 + m_PVRFilteringAtrousPositionSigmaAO: 1 + m_ShowResolutionOverlay: 1 + m_LightingDataAsset: {fileID: 0} + m_UseShadowmask: 1 +--- !u!196 &4 +NavMeshSettings: + serializedVersion: 2 + m_ObjectHideFlags: 0 + m_BuildSettings: + serializedVersion: 2 + agentTypeID: 0 + agentRadius: 0.5 + agentHeight: 2 + agentSlope: 45 + agentClimb: 0.4 + ledgeDropHeight: 0 + maxJumpAcrossDistance: 0 + minRegionArea: 2 + manualCellSize: 0 + cellSize: 0.16666667 + manualTileSize: 0 + tileSize: 256 + accuratePlacement: 0 + debug: + m_Flags: 0 + m_NavMeshData: {fileID: 0} +--- !u!1 &592828463 +GameObject: + m_ObjectHideFlags: 0 + m_PrefabParentObject: {fileID: 0} + m_PrefabInternal: {fileID: 0} + serializedVersion: 5 + m_Component: + - component: {fileID: 592828467} + - component: {fileID: 592828466} + - component: {fileID: 592828465} + - component: {fileID: 592828464} + m_Layer: 0 + m_Name: Sphere + m_TagString: Untagged + m_Icon: {fileID: 0} + m_NavMeshLayer: 0 + m_StaticEditorFlags: 0 + m_IsActive: 1 +--- !u!23 &592828464 +MeshRenderer: + m_ObjectHideFlags: 0 + m_PrefabParentObject: {fileID: 0} + m_PrefabInternal: {fileID: 0} + m_GameObject: {fileID: 592828463} + m_Enabled: 1 + m_CastShadows: 1 + m_ReceiveShadows: 1 + m_DynamicOccludee: 1 + m_MotionVectors: 1 + m_LightProbeUsage: 1 + m_ReflectionProbeUsage: 1 + m_Materials: + - {fileID: 10303, guid: 0000000000000000f000000000000000, type: 0} + m_StaticBatchInfo: + firstSubMesh: 0 + subMeshCount: 0 + m_StaticBatchRoot: {fileID: 0} + m_ProbeAnchor: {fileID: 0} + m_LightProbeVolumeOverride: {fileID: 0} + m_ScaleInLightmap: 1 + m_PreserveUVs: 1 + m_IgnoreNormalsForChartDetection: 0 + m_ImportantGI: 0 + m_StitchLightmapSeams: 0 + m_SelectedEditorRenderState: 3 + m_MinimumChartSize: 4 + m_AutoUVMaxDistance: 0.5 + m_AutoUVMaxAngle: 89 + m_LightmapParameters: {fileID: 0} + m_SortingLayerID: 0 + m_SortingLayer: 0 + m_SortingOrder: 0 +--- !u!135 &592828465 +SphereCollider: + m_ObjectHideFlags: 0 + m_PrefabParentObject: {fileID: 0} + m_PrefabInternal: {fileID: 0} + m_GameObject: {fileID: 592828463} + m_Material: {fileID: 0} + m_IsTrigger: 0 + m_Enabled: 1 + serializedVersion: 2 + m_Radius: 0.5 + m_Center: {x: 0, y: 0, z: 0} +--- !u!33 &592828466 +MeshFilter: + m_ObjectHideFlags: 0 + m_PrefabParentObject: {fileID: 0} + m_PrefabInternal: {fileID: 0} + m_GameObject: {fileID: 592828463} + m_Mesh: {fileID: 10207, guid: 0000000000000000e000000000000000, type: 0} +--- !u!4 &592828467 +Transform: + m_ObjectHideFlags: 0 + m_PrefabParentObject: {fileID: 0} + m_PrefabInternal: {fileID: 0} + m_GameObject: {fileID: 592828463} + m_LocalRotation: {x: 0, y: 0, z: 0, w: 1} + m_LocalPosition: {x: 0.6, y: 0, z: 0} + m_LocalScale: {x: 1, y: 1, z: 1} + m_Children: [] + m_Father: {fileID: 0} + m_RootOrder: 6 + m_LocalEulerAnglesHint: {x: 0, y: 0, z: 0} +--- !u!1 &658370335 +GameObject: + m_ObjectHideFlags: 0 + m_PrefabParentObject: {fileID: 0} + m_PrefabInternal: {fileID: 0} + serializedVersion: 5 + m_Component: + - component: {fileID: 658370339} + - component: {fileID: 658370338} + - component: {fileID: 658370336} + - component: {fileID: 658370337} + m_Layer: 0 + m_Name: DisplayCamera + m_TagString: MainCamera + m_Icon: {fileID: 0} + m_NavMeshLayer: 0 + m_StaticEditorFlags: 0 + m_IsActive: 1 +--- !u!81 &658370336 +AudioListener: + m_ObjectHideFlags: 0 + m_PrefabParentObject: {fileID: 0} + m_PrefabInternal: {fileID: 0} + m_GameObject: {fileID: 658370335} + m_Enabled: 1 +--- !u!114 &658370337 +MonoBehaviour: + m_ObjectHideFlags: 0 + m_PrefabParentObject: {fileID: 0} + m_PrefabInternal: {fileID: 0} + m_GameObject: {fileID: 658370335} + m_Enabled: 1 + m_EditorHideFlags: 0 + m_Script: {fileID: 11500000, guid: f7196fa938037bb46be5bc12531f7f10, type: 3} + m_Name: + m_EditorClassIdentifier: + CaptureResolutionWidth: 1920 + CaptureResolutionHeight: 1080 + CaptureCamera1: {fileID: 1989115845} + CaptureCamera2: {fileID: 1198875011} +--- !u!20 &658370338 +Camera: + m_ObjectHideFlags: 0 + m_PrefabParentObject: {fileID: 0} + m_PrefabInternal: {fileID: 0} + m_GameObject: {fileID: 658370335} + m_Enabled: 1 + serializedVersion: 2 + m_ClearFlags: 1 + m_BackGroundColor: {r: 0.19215687, g: 0.3019608, b: 0.4745098, a: 0} + m_NormalizedViewPortRect: + serializedVersion: 2 + x: 0 + y: 0 + width: 1 + height: 1 + near clip plane: 0.3 + far clip plane: 1000 + field of view: 60 + orthographic: 0 + orthographic size: 5 + m_Depth: 0 + m_CullingMask: + serializedVersion: 2 + m_Bits: 4294967295 + m_RenderingPath: -1 + m_TargetTexture: {fileID: 0} + m_TargetDisplay: 0 + m_TargetEye: 3 + m_HDR: 1 + m_AllowMSAA: 1 + m_AllowDynamicResolution: 0 + m_ForceIntoRT: 0 + m_OcclusionCulling: 1 + m_StereoConvergence: 10 + m_StereoSeparation: 0.022 +--- !u!4 &658370339 +Transform: + m_ObjectHideFlags: 0 + m_PrefabParentObject: {fileID: 0} + m_PrefabInternal: {fileID: 0} + m_GameObject: {fileID: 658370335} + m_LocalRotation: {x: 0, y: 0, z: 0, w: 1} + m_LocalPosition: {x: 0, y: 0, z: 0} + m_LocalScale: {x: 1, y: 1, z: 1} + m_Children: [] + m_Father: {fileID: 0} + m_RootOrder: 1 + m_LocalEulerAnglesHint: {x: 0, y: 0, z: 0} +--- !u!1 &1095384612 +GameObject: + m_ObjectHideFlags: 0 + m_PrefabParentObject: {fileID: 0} + m_PrefabInternal: {fileID: 0} + serializedVersion: 5 + m_Component: + - component: {fileID: 1095384614} + - component: {fileID: 1095384613} + m_Layer: 0 + m_Name: Directional Light + m_TagString: Untagged + m_Icon: {fileID: 0} + m_NavMeshLayer: 0 + m_StaticEditorFlags: 0 + m_IsActive: 1 +--- !u!108 &1095384613 +Light: + m_ObjectHideFlags: 0 + m_PrefabParentObject: {fileID: 0} + m_PrefabInternal: {fileID: 0} + m_GameObject: {fileID: 1095384612} + m_Enabled: 1 + serializedVersion: 8 + m_Type: 1 + m_Color: {r: 1, g: 0.95686275, b: 0.8392157, a: 1} + m_Intensity: 1 + m_Range: 10 + m_SpotAngle: 30 + m_CookieSize: 10 + m_Shadows: + m_Type: 2 + m_Resolution: -1 + m_CustomResolution: -1 + m_Strength: 1 + m_Bias: 0.05 + m_NormalBias: 0.4 + m_NearPlane: 0.2 + m_Cookie: {fileID: 0} + m_DrawHalo: 0 + m_Flare: {fileID: 0} + m_RenderMode: 0 + m_CullingMask: + serializedVersion: 2 + m_Bits: 4294967295 + m_Lightmapping: 4 + m_AreaSize: {x: 1, y: 1} + m_BounceIntensity: 1 + m_ColorTemperature: 6570 + m_UseColorTemperature: 0 + m_ShadowRadius: 0 + m_ShadowAngle: 0 +--- !u!4 &1095384614 +Transform: + m_ObjectHideFlags: 0 + m_PrefabParentObject: {fileID: 0} + m_PrefabInternal: {fileID: 0} + m_GameObject: {fileID: 1095384612} + m_LocalRotation: {x: 0.40821788, y: -0.23456968, z: 0.10938163, w: 0.8754261} + m_LocalPosition: {x: 0, y: 3, z: 0} + m_LocalScale: {x: 1, y: 1, z: 1} + m_Children: [] + m_Father: {fileID: 0} + m_RootOrder: 0 + m_LocalEulerAnglesHint: {x: 50, y: -30, z: 0} +--- !u!1 &1198875009 +GameObject: + m_ObjectHideFlags: 0 + m_PrefabParentObject: {fileID: 0} + m_PrefabInternal: {fileID: 0} + serializedVersion: 5 + m_Component: + - component: {fileID: 1198875012} + - component: {fileID: 1198875011} + - component: {fileID: 1198875010} + m_Layer: 0 + m_Name: CaptureCamera2 + m_TagString: Untagged + m_Icon: {fileID: 0} + m_NavMeshLayer: 0 + m_StaticEditorFlags: 0 + m_IsActive: 1 +--- !u!114 &1198875010 +MonoBehaviour: + m_ObjectHideFlags: 0 + m_PrefabParentObject: {fileID: 0} + m_PrefabInternal: {fileID: 0} + m_GameObject: {fileID: 1198875009} + m_Enabled: 1 + m_EditorHideFlags: 0 + m_Script: {fileID: 11500000, guid: 5f1106d3744ef824496276c8274506b2, type: 3} + m_Name: + m_EditorClassIdentifier: + CaptureDevice: 1 + ResizeMode: 0 + MirrorMode: 0 + DoubleBuffering: 0 + EnableVSync: 0 + TargetFrameRate: 60 + HideWarnings: 0 +--- !u!20 &1198875011 +Camera: + m_ObjectHideFlags: 0 + m_PrefabParentObject: {fileID: 0} + m_PrefabInternal: {fileID: 0} + m_GameObject: {fileID: 1198875009} + m_Enabled: 1 + serializedVersion: 2 + m_ClearFlags: 1 + m_BackGroundColor: {r: 0.19215687, g: 0.3019608, b: 0.4745098, a: 0} + m_NormalizedViewPortRect: + serializedVersion: 2 + x: 0 + y: 0 + width: 1 + height: 1 + near clip plane: 0.3 + far clip plane: 1000 + field of view: 15 + orthographic: 0 + orthographic size: 5 + m_Depth: 0 + m_CullingMask: + serializedVersion: 2 + m_Bits: 4294967295 + m_RenderingPath: -1 + m_TargetTexture: {fileID: 0} + m_TargetDisplay: 0 + m_TargetEye: 3 + m_HDR: 1 + m_AllowMSAA: 1 + m_AllowDynamicResolution: 0 + m_ForceIntoRT: 0 + m_OcclusionCulling: 1 + m_StereoConvergence: 10 + m_StereoSeparation: 0.022 +--- !u!4 &1198875012 +Transform: + m_ObjectHideFlags: 0 + m_PrefabParentObject: {fileID: 0} + m_PrefabInternal: {fileID: 0} + m_GameObject: {fileID: 1198875009} + m_LocalRotation: {x: 0.3050128, y: -0.26139337, z: 0.087460995, w: 0.91158724} + m_LocalPosition: {x: 4.5, y: 7, z: -7} + m_LocalScale: {x: 1, y: 1, z: 1} + m_Children: [] + m_Father: {fileID: 0} + m_RootOrder: 3 + m_LocalEulerAnglesHint: {x: 37, y: -32, z: 0} +--- !u!1 &1785607102 +GameObject: + m_ObjectHideFlags: 0 + m_PrefabParentObject: {fileID: 0} + m_PrefabInternal: {fileID: 0} + serializedVersion: 5 + m_Component: + - component: {fileID: 1785607106} + - component: {fileID: 1785607105} + - component: {fileID: 1785607104} + - component: {fileID: 1785607103} + m_Layer: 0 + m_Name: Cylinder + m_TagString: Untagged + m_Icon: {fileID: 0} + m_NavMeshLayer: 0 + m_StaticEditorFlags: 0 + m_IsActive: 1 +--- !u!23 &1785607103 +MeshRenderer: + m_ObjectHideFlags: 0 + m_PrefabParentObject: {fileID: 0} + m_PrefabInternal: {fileID: 0} + m_GameObject: {fileID: 1785607102} + m_Enabled: 1 + m_CastShadows: 1 + m_ReceiveShadows: 1 + m_DynamicOccludee: 1 + m_MotionVectors: 1 + m_LightProbeUsage: 1 + m_ReflectionProbeUsage: 1 + m_Materials: + - {fileID: 10303, guid: 0000000000000000f000000000000000, type: 0} + m_StaticBatchInfo: + firstSubMesh: 0 + subMeshCount: 0 + m_StaticBatchRoot: {fileID: 0} + m_ProbeAnchor: {fileID: 0} + m_LightProbeVolumeOverride: {fileID: 0} + m_ScaleInLightmap: 1 + m_PreserveUVs: 1 + m_IgnoreNormalsForChartDetection: 0 + m_ImportantGI: 0 + m_StitchLightmapSeams: 0 + m_SelectedEditorRenderState: 3 + m_MinimumChartSize: 4 + m_AutoUVMaxDistance: 0.5 + m_AutoUVMaxAngle: 89 + m_LightmapParameters: {fileID: 0} + m_SortingLayerID: 0 + m_SortingLayer: 0 + m_SortingOrder: 0 +--- !u!136 &1785607104 +CapsuleCollider: + m_ObjectHideFlags: 0 + m_PrefabParentObject: {fileID: 0} + m_PrefabInternal: {fileID: 0} + m_GameObject: {fileID: 1785607102} + m_Material: {fileID: 0} + m_IsTrigger: 0 + m_Enabled: 1 + m_Radius: 0.5 + m_Height: 2 + m_Direction: 1 + m_Center: {x: 0, y: 0, z: 0} +--- !u!33 &1785607105 +MeshFilter: + m_ObjectHideFlags: 0 + m_PrefabParentObject: {fileID: 0} + m_PrefabInternal: {fileID: 0} + m_GameObject: {fileID: 1785607102} + m_Mesh: {fileID: 10206, guid: 0000000000000000e000000000000000, type: 0} +--- !u!4 &1785607106 +Transform: + m_ObjectHideFlags: 0 + m_PrefabParentObject: {fileID: 0} + m_PrefabInternal: {fileID: 0} + m_GameObject: {fileID: 1785607102} + m_LocalRotation: {x: -0, y: -0, z: -0, w: 1} + m_LocalPosition: {x: 0.01999998, y: 0, z: 1.7} + m_LocalScale: {x: 1, y: 1, z: 1} + m_Children: [] + m_Father: {fileID: 0} + m_RootOrder: 5 + m_LocalEulerAnglesHint: {x: 0, y: 0, z: 0} +--- !u!1 &1989115843 +GameObject: + m_ObjectHideFlags: 0 + m_PrefabParentObject: {fileID: 0} + m_PrefabInternal: {fileID: 0} + serializedVersion: 5 + m_Component: + - component: {fileID: 1989115846} + - component: {fileID: 1989115845} + - component: {fileID: 1989115844} + m_Layer: 0 + m_Name: CaptureCamera1 + m_TagString: Untagged + m_Icon: {fileID: 0} + m_NavMeshLayer: 0 + m_StaticEditorFlags: 0 + m_IsActive: 1 +--- !u!114 &1989115844 +MonoBehaviour: + m_ObjectHideFlags: 0 + m_PrefabParentObject: {fileID: 0} + m_PrefabInternal: {fileID: 0} + m_GameObject: {fileID: 1989115843} + m_Enabled: 1 + m_EditorHideFlags: 0 + m_Script: {fileID: 11500000, guid: 5f1106d3744ef824496276c8274506b2, type: 3} + m_Name: + m_EditorClassIdentifier: + CaptureDevice: 0 + ResizeMode: 0 + MirrorMode: 0 + DoubleBuffering: 0 + EnableVSync: 0 + TargetFrameRate: 60 + HideWarnings: 0 +--- !u!20 &1989115845 +Camera: + m_ObjectHideFlags: 0 + m_PrefabParentObject: {fileID: 0} + m_PrefabInternal: {fileID: 0} + m_GameObject: {fileID: 1989115843} + m_Enabled: 1 + serializedVersion: 2 + m_ClearFlags: 1 + m_BackGroundColor: {r: 0.19215687, g: 0.3019608, b: 0.4745098, a: 0} + m_NormalizedViewPortRect: + serializedVersion: 2 + x: 0 + y: 0 + width: 1 + height: 1 + near clip plane: 0.3 + far clip plane: 1000 + field of view: 60 + orthographic: 0 + orthographic size: 5 + m_Depth: 0 + m_CullingMask: + serializedVersion: 2 + m_Bits: 4294967295 + m_RenderingPath: -1 + m_TargetTexture: {fileID: 0} + m_TargetDisplay: 0 + m_TargetEye: 3 + m_HDR: 1 + m_AllowMSAA: 1 + m_AllowDynamicResolution: 0 + m_ForceIntoRT: 0 + m_OcclusionCulling: 1 + m_StereoConvergence: 10 + m_StereoSeparation: 0.022 +--- !u!4 &1989115846 +Transform: + m_ObjectHideFlags: 0 + m_PrefabParentObject: {fileID: 0} + m_PrefabInternal: {fileID: 0} + m_GameObject: {fileID: 1989115843} + m_LocalRotation: {x: 0.12378104, y: 0.31459007, z: -0.041416556, w: 0.94021064} + m_LocalPosition: {x: -2.6, y: 1, z: -3} + m_LocalScale: {x: 1, y: 1, z: 1} + m_Children: [] + m_Father: {fileID: 0} + m_RootOrder: 2 + m_LocalEulerAnglesHint: {x: 15, y: 37, z: 0} +--- !u!1 &2109363506 +GameObject: + m_ObjectHideFlags: 0 + m_PrefabParentObject: {fileID: 0} + m_PrefabInternal: {fileID: 0} + serializedVersion: 5 + m_Component: + - component: {fileID: 2109363510} + - component: {fileID: 2109363509} + - component: {fileID: 2109363508} + - component: {fileID: 2109363507} + m_Layer: 0 + m_Name: Cube + m_TagString: Untagged + m_Icon: {fileID: 0} + m_NavMeshLayer: 0 + m_StaticEditorFlags: 0 + m_IsActive: 1 +--- !u!23 &2109363507 +MeshRenderer: + m_ObjectHideFlags: 0 + m_PrefabParentObject: {fileID: 0} + m_PrefabInternal: {fileID: 0} + m_GameObject: {fileID: 2109363506} + m_Enabled: 1 + m_CastShadows: 1 + m_ReceiveShadows: 1 + m_DynamicOccludee: 1 + m_MotionVectors: 1 + m_LightProbeUsage: 1 + m_ReflectionProbeUsage: 1 + m_Materials: + - {fileID: 10303, guid: 0000000000000000f000000000000000, type: 0} + m_StaticBatchInfo: + firstSubMesh: 0 + subMeshCount: 0 + m_StaticBatchRoot: {fileID: 0} + m_ProbeAnchor: {fileID: 0} + m_LightProbeVolumeOverride: {fileID: 0} + m_ScaleInLightmap: 1 + m_PreserveUVs: 1 + m_IgnoreNormalsForChartDetection: 0 + m_ImportantGI: 0 + m_StitchLightmapSeams: 0 + m_SelectedEditorRenderState: 3 + m_MinimumChartSize: 4 + m_AutoUVMaxDistance: 0.5 + m_AutoUVMaxAngle: 89 + m_LightmapParameters: {fileID: 0} + m_SortingLayerID: 0 + m_SortingLayer: 0 + m_SortingOrder: 0 +--- !u!65 &2109363508 +BoxCollider: + m_ObjectHideFlags: 0 + m_PrefabParentObject: {fileID: 0} + m_PrefabInternal: {fileID: 0} + m_GameObject: {fileID: 2109363506} + m_Material: {fileID: 0} + m_IsTrigger: 0 + m_Enabled: 1 + serializedVersion: 2 + m_Size: {x: 1, y: 1, z: 1} + m_Center: {x: 0, y: 0, z: 0} +--- !u!33 &2109363509 +MeshFilter: + m_ObjectHideFlags: 0 + m_PrefabParentObject: {fileID: 0} + m_PrefabInternal: {fileID: 0} + m_GameObject: {fileID: 2109363506} + m_Mesh: {fileID: 10202, guid: 0000000000000000e000000000000000, type: 0} +--- !u!4 &2109363510 +Transform: + m_ObjectHideFlags: 0 + m_PrefabParentObject: {fileID: 0} + m_PrefabInternal: {fileID: 0} + m_GameObject: {fileID: 2109363506} + m_LocalRotation: {x: 0, y: 0, z: 0, w: 1} + m_LocalPosition: {x: -0.6, y: 0, z: 0} + m_LocalScale: {x: 1, y: 1, z: 1} + m_Children: [] + m_Father: {fileID: 0} + m_RootOrder: 4 + m_LocalEulerAnglesHint: {x: 0, y: 0, z: 0} diff --git a/UnitySample/Assets/AssetStoreTools/Editor.meta b/UnityCaptureSample/Assets/UnityCaptureMultiCam.unity.meta similarity index 56% rename from UnitySample/Assets/AssetStoreTools/Editor.meta rename to UnityCaptureSample/Assets/UnityCaptureMultiCam.unity.meta index f803147..614101b 100644 --- a/UnitySample/Assets/AssetStoreTools/Editor.meta +++ b/UnityCaptureSample/Assets/UnityCaptureMultiCam.unity.meta @@ -1,9 +1,9 @@ fileFormatVersion: 2 -guid: 16ece4bf80bd6ef4da872382bd3ebcfa -folderAsset: yes -timeCreated: 1466480510 +guid: 11a64de95dd5931409a8adddd311a26d +timeCreated: 1530682853 licenseType: Free DefaultImporter: + externalObjects: {} userData: assetBundleName: assetBundleVariant: diff --git a/UnityCaptureSample/Assets/UnityCaptureTextureExample.unity b/UnityCaptureSample/Assets/UnityCaptureTextureExample.unity new file mode 100644 index 0000000..c92efc4 --- /dev/null +++ b/UnityCaptureSample/Assets/UnityCaptureTextureExample.unity @@ -0,0 +1,390 @@ +%YAML 1.1 +%TAG !u! tag:unity3d.com,2011: +--- !u!29 &1 +OcclusionCullingSettings: + m_ObjectHideFlags: 0 + serializedVersion: 2 + m_OcclusionBakeSettings: + smallestOccluder: 5 + smallestHole: 0.25 + backfaceThreshold: 100 + m_SceneGUID: 00000000000000000000000000000000 + m_OcclusionCullingData: {fileID: 0} +--- !u!104 &2 +RenderSettings: + m_ObjectHideFlags: 0 + serializedVersion: 8 + m_Fog: 0 + m_FogColor: {r: 0.5, g: 0.5, b: 0.5, a: 1} + m_FogMode: 3 + m_FogDensity: 0.01 + m_LinearFogStart: 0 + m_LinearFogEnd: 300 + m_AmbientSkyColor: {r: 0.212, g: 0.227, b: 0.259, a: 1} + m_AmbientEquatorColor: {r: 0.114, g: 0.125, b: 0.133, a: 1} + m_AmbientGroundColor: {r: 0.047, g: 0.043, b: 0.035, a: 1} + m_AmbientIntensity: 1 + m_AmbientMode: 0 + m_SubtractiveShadowColor: {r: 0.42, g: 0.478, b: 0.627, a: 1} + m_SkyboxMaterial: {fileID: 10304, guid: 0000000000000000f000000000000000, type: 0} + m_HaloStrength: 0.5 + m_FlareStrength: 1 + m_FlareFadeSpeed: 3 + m_HaloTexture: {fileID: 0} + m_SpotCookie: {fileID: 10001, guid: 0000000000000000e000000000000000, type: 0} + m_DefaultReflectionMode: 0 + m_DefaultReflectionResolution: 128 + m_ReflectionBounces: 1 + m_ReflectionIntensity: 1 + m_CustomReflection: {fileID: 0} + m_Sun: {fileID: 0} + m_IndirectSpecularColor: {r: 0.44657898, g: 0.4964133, b: 0.5748178, a: 1} +--- !u!157 &3 +LightmapSettings: + m_ObjectHideFlags: 0 + serializedVersion: 11 + m_GIWorkflowMode: 0 + m_GISettings: + serializedVersion: 2 + m_BounceScale: 1 + m_IndirectOutputScale: 1 + m_AlbedoBoost: 1 + m_TemporalCoherenceThreshold: 1 + m_EnvironmentLightingMode: 0 + m_EnableBakedLightmaps: 1 + m_EnableRealtimeLightmaps: 1 + m_LightmapEditorSettings: + serializedVersion: 9 + m_Resolution: 2 + m_BakeResolution: 40 + m_TextureWidth: 1024 + m_TextureHeight: 1024 + m_AO: 0 + m_AOMaxDistance: 1 + m_CompAOExponent: 0 + m_CompAOExponentDirect: 0 + m_Padding: 2 + m_LightmapParameters: {fileID: 0} + m_LightmapsBakeMode: 1 + m_TextureCompression: 1 + m_FinalGather: 0 + m_FinalGatherFiltering: 1 + m_FinalGatherRayCount: 1024 + m_ReflectionCompression: 2 + m_MixedBakeMode: 1 + m_BakeBackend: 0 + m_PVRSampling: 1 + m_PVRDirectSampleCount: 32 + m_PVRSampleCount: 500 + m_PVRBounces: 2 + m_PVRFilterTypeDirect: 0 + m_PVRFilterTypeIndirect: 0 + m_PVRFilterTypeAO: 0 + m_PVRFilteringMode: 0 + m_PVRCulling: 1 + m_PVRFilteringGaussRadiusDirect: 1 + m_PVRFilteringGaussRadiusIndirect: 5 + m_PVRFilteringGaussRadiusAO: 2 + m_PVRFilteringAtrousPositionSigmaDirect: 0.5 + m_PVRFilteringAtrousPositionSigmaIndirect: 2 + m_PVRFilteringAtrousPositionSigmaAO: 1 + m_ShowResolutionOverlay: 1 + m_LightingDataAsset: {fileID: 0} + m_UseShadowmask: 0 +--- !u!196 &4 +NavMeshSettings: + serializedVersion: 2 + m_ObjectHideFlags: 0 + m_BuildSettings: + serializedVersion: 2 + agentTypeID: 0 + agentRadius: 0.5 + agentHeight: 2 + agentSlope: 45 + agentClimb: 0.4 + ledgeDropHeight: 0 + maxJumpAcrossDistance: 0 + minRegionArea: 2 + manualCellSize: 0 + cellSize: 0.16666667 + manualTileSize: 0 + tileSize: 256 + accuratePlacement: 0 + debug: + m_Flags: 0 + m_NavMeshData: {fileID: 0} +--- !u!1 &922515556 +GameObject: + m_ObjectHideFlags: 0 + m_PrefabParentObject: {fileID: 0} + m_PrefabInternal: {fileID: 0} + serializedVersion: 5 + m_Component: + - component: {fileID: 922515559} + - component: {fileID: 922515557} + m_Layer: 0 + m_Name: Capturer + m_TagString: Untagged + m_Icon: {fileID: 0} + m_NavMeshLayer: 0 + m_StaticEditorFlags: 0 + m_IsActive: 1 +--- !u!114 &922515557 +MonoBehaviour: + m_ObjectHideFlags: 0 + m_PrefabParentObject: {fileID: 0} + m_PrefabInternal: {fileID: 0} + m_GameObject: {fileID: 922515556} + m_Enabled: 1 + m_EditorHideFlags: 0 + m_Script: {fileID: 11500000, guid: c8e68187542b37846b4a604d28bd90e1, type: 3} + m_Name: + m_EditorClassIdentifier: + width: 320 + height: 240 + outputRenderer: {fileID: 1893059143} +--- !u!4 &922515559 +Transform: + m_ObjectHideFlags: 0 + m_PrefabParentObject: {fileID: 0} + m_PrefabInternal: {fileID: 0} + m_GameObject: {fileID: 922515556} + m_LocalRotation: {x: -0, y: -0, z: -0, w: 1} + m_LocalPosition: {x: -6.91, y: -2.4, z: 0} + m_LocalScale: {x: 1, y: 1, z: 1} + m_Children: [] + m_Father: {fileID: 0} + m_RootOrder: 2 + m_LocalEulerAnglesHint: {x: 0, y: 0, z: 0} +--- !u!1 &1251162945 +GameObject: + m_ObjectHideFlags: 0 + m_PrefabParentObject: {fileID: 0} + m_PrefabInternal: {fileID: 0} + serializedVersion: 5 + m_Component: + - component: {fileID: 1251162947} + - component: {fileID: 1251162946} + m_Layer: 0 + m_Name: Directional Light + m_TagString: Untagged + m_Icon: {fileID: 0} + m_NavMeshLayer: 0 + m_StaticEditorFlags: 0 + m_IsActive: 1 +--- !u!108 &1251162946 +Light: + m_ObjectHideFlags: 0 + m_PrefabParentObject: {fileID: 0} + m_PrefabInternal: {fileID: 0} + m_GameObject: {fileID: 1251162945} + m_Enabled: 1 + serializedVersion: 8 + m_Type: 1 + m_Color: {r: 1, g: 0.95686275, b: 0.8392157, a: 1} + m_Intensity: 1 + m_Range: 10 + m_SpotAngle: 30 + m_CookieSize: 10 + m_Shadows: + m_Type: 2 + m_Resolution: -1 + m_CustomResolution: -1 + m_Strength: 1 + m_Bias: 0.05 + m_NormalBias: 0.4 + m_NearPlane: 0.2 + m_Cookie: {fileID: 0} + m_DrawHalo: 0 + m_Flare: {fileID: 0} + m_RenderMode: 0 + m_CullingMask: + serializedVersion: 2 + m_Bits: 4294967295 + m_Lightmapping: 4 + m_AreaSize: {x: 1, y: 1} + m_BounceIntensity: 1 + m_ColorTemperature: 6570 + m_UseColorTemperature: 0 + m_ShadowRadius: 0 + m_ShadowAngle: 0 +--- !u!4 &1251162947 +Transform: + m_ObjectHideFlags: 0 + m_PrefabParentObject: {fileID: 0} + m_PrefabInternal: {fileID: 0} + m_GameObject: {fileID: 1251162945} + m_LocalRotation: {x: 0.40821797, y: -0.23456974, z: 0.10938168, w: 0.8754261} + m_LocalPosition: {x: 0, y: 3, z: 0} + m_LocalScale: {x: 1, y: 1, z: 1} + m_Children: [] + m_Father: {fileID: 0} + m_RootOrder: 0 + m_LocalEulerAnglesHint: {x: 0, y: 0, z: 0} +--- !u!1 &1776439397 +GameObject: + m_ObjectHideFlags: 0 + m_PrefabParentObject: {fileID: 0} + m_PrefabInternal: {fileID: 0} + serializedVersion: 5 + m_Component: + - component: {fileID: 1776439401} + - component: {fileID: 1776439400} + - component: {fileID: 1776439399} + - component: {fileID: 1776439398} + m_Layer: 0 + m_Name: Camera + m_TagString: Untagged + m_Icon: {fileID: 0} + m_NavMeshLayer: 0 + m_StaticEditorFlags: 0 + m_IsActive: 1 +--- !u!81 &1776439398 +AudioListener: + m_ObjectHideFlags: 0 + m_PrefabParentObject: {fileID: 0} + m_PrefabInternal: {fileID: 0} + m_GameObject: {fileID: 1776439397} + m_Enabled: 1 +--- !u!124 &1776439399 +Behaviour: + m_ObjectHideFlags: 0 + m_PrefabParentObject: {fileID: 0} + m_PrefabInternal: {fileID: 0} + m_GameObject: {fileID: 1776439397} + m_Enabled: 1 +--- !u!20 &1776439400 +Camera: + m_ObjectHideFlags: 0 + m_PrefabParentObject: {fileID: 0} + m_PrefabInternal: {fileID: 0} + m_GameObject: {fileID: 1776439397} + m_Enabled: 1 + serializedVersion: 2 + m_ClearFlags: 1 + m_BackGroundColor: {r: 0.19215687, g: 0.3019608, b: 0.4745098, a: 0} + m_NormalizedViewPortRect: + serializedVersion: 2 + x: 0 + y: 0 + width: 1 + height: 1 + near clip plane: 0.3 + far clip plane: 1000 + field of view: 60 + orthographic: 0 + orthographic size: 5 + m_Depth: 0 + m_CullingMask: + serializedVersion: 2 + m_Bits: 4294967295 + m_RenderingPath: -1 + m_TargetTexture: {fileID: 0} + m_TargetDisplay: 0 + m_TargetEye: 3 + m_HDR: 1 + m_AllowMSAA: 1 + m_AllowDynamicResolution: 0 + m_ForceIntoRT: 0 + m_OcclusionCulling: 1 + m_StereoConvergence: 10 + m_StereoSeparation: 0.022 +--- !u!4 &1776439401 +Transform: + m_ObjectHideFlags: 0 + m_PrefabParentObject: {fileID: 0} + m_PrefabInternal: {fileID: 0} + m_GameObject: {fileID: 1776439397} + m_LocalRotation: {x: -0, y: -0, z: -0, w: 1} + m_LocalPosition: {x: -6.91, y: -2.4, z: 0} + m_LocalScale: {x: 1, y: 1, z: 1} + m_Children: [] + m_Father: {fileID: 0} + m_RootOrder: 1 + m_LocalEulerAnglesHint: {x: 0, y: 0, z: 0} +--- !u!1 &1893059142 +GameObject: + m_ObjectHideFlags: 0 + m_PrefabParentObject: {fileID: 0} + m_PrefabInternal: {fileID: 0} + serializedVersion: 5 + m_Component: + - component: {fileID: 1893059146} + - component: {fileID: 1893059145} + - component: {fileID: 1893059144} + - component: {fileID: 1893059143} + m_Layer: 0 + m_Name: Quad + m_TagString: Untagged + m_Icon: {fileID: 0} + m_NavMeshLayer: 0 + m_StaticEditorFlags: 0 + m_IsActive: 1 +--- !u!23 &1893059143 +MeshRenderer: + m_ObjectHideFlags: 0 + m_PrefabParentObject: {fileID: 0} + m_PrefabInternal: {fileID: 0} + m_GameObject: {fileID: 1893059142} + m_Enabled: 1 + m_CastShadows: 1 + m_ReceiveShadows: 1 + m_DynamicOccludee: 1 + m_MotionVectors: 1 + m_LightProbeUsage: 1 + m_ReflectionProbeUsage: 1 + m_Materials: + - {fileID: 2100000, guid: 07c56e3f5854b144bb9eca95eacc0425, type: 2} + m_StaticBatchInfo: + firstSubMesh: 0 + subMeshCount: 0 + m_StaticBatchRoot: {fileID: 0} + m_ProbeAnchor: {fileID: 0} + m_LightProbeVolumeOverride: {fileID: 0} + m_ScaleInLightmap: 1 + m_PreserveUVs: 1 + m_IgnoreNormalsForChartDetection: 0 + m_ImportantGI: 0 + m_StitchLightmapSeams: 0 + m_SelectedEditorRenderState: 3 + m_MinimumChartSize: 4 + m_AutoUVMaxDistance: 0.5 + m_AutoUVMaxAngle: 89 + m_LightmapParameters: {fileID: 0} + m_SortingLayerID: 0 + m_SortingLayer: 0 + m_SortingOrder: 0 +--- !u!64 &1893059144 +MeshCollider: + m_ObjectHideFlags: 0 + m_PrefabParentObject: {fileID: 0} + m_PrefabInternal: {fileID: 0} + m_GameObject: {fileID: 1893059142} + m_Material: {fileID: 0} + m_IsTrigger: 0 + m_Enabled: 1 + serializedVersion: 3 + m_Convex: 0 + m_CookingOptions: 14 + m_SkinWidth: 0.01 + m_Mesh: {fileID: 10210, guid: 0000000000000000e000000000000000, type: 0} +--- !u!33 &1893059145 +MeshFilter: + m_ObjectHideFlags: 0 + m_PrefabParentObject: {fileID: 0} + m_PrefabInternal: {fileID: 0} + m_GameObject: {fileID: 1893059142} + m_Mesh: {fileID: 10210, guid: 0000000000000000e000000000000000, type: 0} +--- !u!4 &1893059146 +Transform: + m_ObjectHideFlags: 0 + m_PrefabParentObject: {fileID: 0} + m_PrefabInternal: {fileID: 0} + m_GameObject: {fileID: 1893059142} + m_LocalRotation: {x: -0, y: -0, z: -0, w: 1} + m_LocalPosition: {x: -6.91, y: -2.4, z: 1.41} + m_LocalScale: {x: 1, y: 1, z: 1} + m_Children: [] + m_Father: {fileID: 0} + m_RootOrder: 3 + m_LocalEulerAnglesHint: {x: 0, y: 0, z: 0} diff --git a/UnityCaptureSample/Assets/UnityCaptureTextureExample.unity.meta b/UnityCaptureSample/Assets/UnityCaptureTextureExample.unity.meta new file mode 100644 index 0000000..5f4a98c --- /dev/null +++ b/UnityCaptureSample/Assets/UnityCaptureTextureExample.unity.meta @@ -0,0 +1,9 @@ +fileFormatVersion: 2 +guid: 0e5521c3918e4e94e896eb15f27dcde5 +timeCreated: 1536023064 +licenseType: Free +DefaultImporter: + externalObjects: {} + userData: + assetBundleName: + assetBundleVariant: diff --git a/UnityCaptureSample/ProjectSettings/AudioManager.asset b/UnityCaptureSample/ProjectSettings/AudioManager.asset new file mode 100644 index 0000000..da61125 --- /dev/null +++ b/UnityCaptureSample/ProjectSettings/AudioManager.asset @@ -0,0 +1,17 @@ +%YAML 1.1 +%TAG !u! tag:unity3d.com,2011: +--- !u!11 &1 +AudioManager: + m_ObjectHideFlags: 0 + m_Volume: 1 + Rolloff Scale: 1 + Doppler Factor: 1 + Default Speaker Mode: 2 + m_SampleRate: 0 + m_DSPBufferSize: 0 + m_VirtualVoiceCount: 512 + m_RealVoiceCount: 32 + m_SpatializerPlugin: + m_AmbisonicDecoderPlugin: + m_DisableAudio: 0 + m_VirtualizeEffects: 1 diff --git a/UnityCaptureSample/ProjectSettings/ClusterInputManager.asset b/UnityCaptureSample/ProjectSettings/ClusterInputManager.asset new file mode 100644 index 0000000..e7886b2 --- /dev/null +++ b/UnityCaptureSample/ProjectSettings/ClusterInputManager.asset @@ -0,0 +1,6 @@ +%YAML 1.1 +%TAG !u! tag:unity3d.com,2011: +--- !u!236 &1 +ClusterInputManager: + m_ObjectHideFlags: 0 + m_Inputs: [] diff --git a/UnityCaptureSample/ProjectSettings/DynamicsManager.asset b/UnityCaptureSample/ProjectSettings/DynamicsManager.asset new file mode 100644 index 0000000..78992f0 --- /dev/null +++ b/UnityCaptureSample/ProjectSettings/DynamicsManager.asset @@ -0,0 +1,29 @@ +%YAML 1.1 +%TAG !u! tag:unity3d.com,2011: +--- !u!55 &1 +PhysicsManager: + m_ObjectHideFlags: 0 + serializedVersion: 7 + m_Gravity: {x: 0, y: -9.81, z: 0} + m_DefaultMaterial: {fileID: 0} + m_BounceThreshold: 2 + m_SleepThreshold: 0.005 + m_DefaultContactOffset: 0.01 + m_DefaultSolverIterations: 6 + m_DefaultSolverVelocityIterations: 1 + m_QueriesHitBackfaces: 0 + m_QueriesHitTriggers: 1 + m_EnableAdaptiveForce: 0 + m_ClothInterCollisionDistance: 0 + m_ClothInterCollisionStiffness: 0 + m_ContactsGeneration: 1 + m_LayerCollisionMatrix: ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff + m_AutoSimulation: 1 + m_AutoSyncTransforms: 1 + m_ClothInterCollisionSettingsToggle: 0 + m_ContactPairsMode: 0 + m_BroadphaseType: 0 + m_WorldBounds: + m_Center: {x: 0, y: 0, z: 0} + m_Extent: {x: 250, y: 250, z: 250} + m_WorldSubdivisions: 8 diff --git a/UnityCaptureSample/ProjectSettings/EditorBuildSettings.asset b/UnityCaptureSample/ProjectSettings/EditorBuildSettings.asset new file mode 100644 index 0000000..50aa740 --- /dev/null +++ b/UnityCaptureSample/ProjectSettings/EditorBuildSettings.asset @@ -0,0 +1,10 @@ +%YAML 1.1 +%TAG !u! tag:unity3d.com,2011: +--- !u!1045 &1 +EditorBuildSettings: + m_ObjectHideFlags: 0 + serializedVersion: 2 + m_Scenes: + - enabled: 1 + path: Assets/UnityCam/Example/CubesScene.unity + guid: 91da01314302a514aa3176f8a4ad8536 diff --git a/UnityCaptureSample/ProjectSettings/EditorSettings.asset b/UnityCaptureSample/ProjectSettings/EditorSettings.asset new file mode 100644 index 0000000..607ff5d --- /dev/null +++ b/UnityCaptureSample/ProjectSettings/EditorSettings.asset @@ -0,0 +1,21 @@ +%YAML 1.1 +%TAG !u! tag:unity3d.com,2011: +--- !u!159 &1 +EditorSettings: + m_ObjectHideFlags: 0 + serializedVersion: 7 + m_ExternalVersionControlSupport: Visible Meta Files + m_SerializationMode: 2 + m_LineEndingsForNewScripts: 2 + m_DefaultBehaviorMode: 0 + m_SpritePackerMode: 0 + m_SpritePackerPaddingPower: 1 + m_EtcTextureCompressorBehavior: 1 + m_EtcTextureFastCompressor: 1 + m_EtcTextureNormalCompressor: 2 + m_EtcTextureBestCompressor: 4 + m_ProjectGenerationIncludedExtensions: txt;xml;fnt;cd;asmdef;rsp + m_ProjectGenerationRootNamespace: + m_UserGeneratedProjectSuffix: + m_CollabEditorSettings: + inProgressEnabled: 1 diff --git a/UnityCaptureSample/ProjectSettings/GraphicsSettings.asset b/UnityCaptureSample/ProjectSettings/GraphicsSettings.asset new file mode 100644 index 0000000..9e432d1 --- /dev/null +++ b/UnityCaptureSample/ProjectSettings/GraphicsSettings.asset @@ -0,0 +1,63 @@ +%YAML 1.1 +%TAG !u! tag:unity3d.com,2011: +--- !u!30 &1 +GraphicsSettings: + m_ObjectHideFlags: 0 + serializedVersion: 12 + m_Deferred: + m_Mode: 1 + m_Shader: {fileID: 69, guid: 0000000000000000f000000000000000, type: 0} + m_DeferredReflections: + m_Mode: 1 + m_Shader: {fileID: 74, guid: 0000000000000000f000000000000000, type: 0} + m_ScreenSpaceShadows: + m_Mode: 1 + m_Shader: {fileID: 64, guid: 0000000000000000f000000000000000, type: 0} + m_LegacyDeferred: + m_Mode: 1 + m_Shader: {fileID: 63, guid: 0000000000000000f000000000000000, type: 0} + m_DepthNormals: + m_Mode: 1 + m_Shader: {fileID: 62, guid: 0000000000000000f000000000000000, type: 0} + m_MotionVectors: + m_Mode: 1 + m_Shader: {fileID: 75, guid: 0000000000000000f000000000000000, type: 0} + m_LightHalo: + m_Mode: 1 + m_Shader: {fileID: 105, guid: 0000000000000000f000000000000000, type: 0} + m_LensFlare: + m_Mode: 1 + m_Shader: {fileID: 102, guid: 0000000000000000f000000000000000, type: 0} + m_AlwaysIncludedShaders: + - {fileID: 7, guid: 0000000000000000f000000000000000, type: 0} + - {fileID: 15104, guid: 0000000000000000f000000000000000, type: 0} + - {fileID: 15105, guid: 0000000000000000f000000000000000, type: 0} + - {fileID: 15106, guid: 0000000000000000f000000000000000, type: 0} + - {fileID: 10753, guid: 0000000000000000f000000000000000, type: 0} + - {fileID: 10770, guid: 0000000000000000f000000000000000, type: 0} + - {fileID: 17000, guid: 0000000000000000f000000000000000, type: 0} + - {fileID: 16000, guid: 0000000000000000f000000000000000, type: 0} + m_PreloadedShaders: [] + m_SpritesDefaultMaterial: {fileID: 10754, guid: 0000000000000000f000000000000000, + type: 0} + m_CustomRenderPipeline: {fileID: 0} + m_TransparencySortMode: 0 + m_TransparencySortAxis: {x: 0, y: 0, z: 1} + m_DefaultRenderingPath: 1 + m_DefaultMobileRenderingPath: 1 + m_TierSettings: [] + m_LightmapStripping: 0 + m_FogStripping: 0 + m_InstancingStripping: 0 + m_LightmapKeepPlain: 1 + m_LightmapKeepDirCombined: 1 + m_LightmapKeepDynamicPlain: 1 + m_LightmapKeepDynamicDirCombined: 1 + m_LightmapKeepShadowMask: 1 + m_LightmapKeepSubtractive: 1 + m_FogKeepLinear: 1 + m_FogKeepExp: 1 + m_FogKeepExp2: 1 + m_AlbedoSwatchInfos: [] + m_LightsUseLinearIntensity: 0 + m_LightsUseColorTemperature: 0 diff --git a/UnityCaptureSample/ProjectSettings/InputManager.asset b/UnityCaptureSample/ProjectSettings/InputManager.asset new file mode 100644 index 0000000..17c8f53 --- /dev/null +++ b/UnityCaptureSample/ProjectSettings/InputManager.asset @@ -0,0 +1,295 @@ +%YAML 1.1 +%TAG !u! tag:unity3d.com,2011: +--- !u!13 &1 +InputManager: + m_ObjectHideFlags: 0 + serializedVersion: 2 + m_Axes: + - serializedVersion: 3 + m_Name: Horizontal + descriptiveName: + descriptiveNegativeName: + negativeButton: left + positiveButton: right + altNegativeButton: a + altPositiveButton: d + gravity: 3 + dead: 0.001 + sensitivity: 3 + snap: 1 + invert: 0 + type: 0 + axis: 0 + joyNum: 0 + - serializedVersion: 3 + m_Name: Vertical + descriptiveName: + descriptiveNegativeName: + negativeButton: down + positiveButton: up + altNegativeButton: s + altPositiveButton: w + gravity: 3 + dead: 0.001 + sensitivity: 3 + snap: 1 + invert: 0 + type: 0 + axis: 0 + joyNum: 0 + - serializedVersion: 3 + m_Name: Fire1 + descriptiveName: + descriptiveNegativeName: + negativeButton: + positiveButton: left ctrl + altNegativeButton: + altPositiveButton: mouse 0 + gravity: 1000 + dead: 0.001 + sensitivity: 1000 + snap: 0 + invert: 0 + type: 0 + axis: 0 + joyNum: 0 + - serializedVersion: 3 + m_Name: Fire2 + descriptiveName: + descriptiveNegativeName: + negativeButton: + positiveButton: left alt + altNegativeButton: + altPositiveButton: mouse 1 + gravity: 1000 + dead: 0.001 + sensitivity: 1000 + snap: 0 + invert: 0 + type: 0 + axis: 0 + joyNum: 0 + - serializedVersion: 3 + m_Name: Fire3 + descriptiveName: + descriptiveNegativeName: + negativeButton: + positiveButton: left shift + altNegativeButton: + altPositiveButton: mouse 2 + gravity: 1000 + dead: 0.001 + sensitivity: 1000 + snap: 0 + invert: 0 + type: 0 + axis: 0 + joyNum: 0 + - serializedVersion: 3 + m_Name: Jump + descriptiveName: + descriptiveNegativeName: + negativeButton: + positiveButton: space + altNegativeButton: + altPositiveButton: + gravity: 1000 + dead: 0.001 + sensitivity: 1000 + snap: 0 + invert: 0 + type: 0 + axis: 0 + joyNum: 0 + - serializedVersion: 3 + m_Name: Mouse X + descriptiveName: + descriptiveNegativeName: + negativeButton: + positiveButton: + altNegativeButton: + altPositiveButton: + gravity: 0 + dead: 0 + sensitivity: 0.1 + snap: 0 + invert: 0 + type: 1 + axis: 0 + joyNum: 0 + - serializedVersion: 3 + m_Name: Mouse Y + descriptiveName: + descriptiveNegativeName: + negativeButton: + positiveButton: + altNegativeButton: + altPositiveButton: + gravity: 0 + dead: 0 + sensitivity: 0.1 + snap: 0 + invert: 0 + type: 1 + axis: 1 + joyNum: 0 + - serializedVersion: 3 + m_Name: Mouse ScrollWheel + descriptiveName: + descriptiveNegativeName: + negativeButton: + positiveButton: + altNegativeButton: + altPositiveButton: + gravity: 0 + dead: 0 + sensitivity: 0.1 + snap: 0 + invert: 0 + type: 1 + axis: 2 + joyNum: 0 + - serializedVersion: 3 + m_Name: Horizontal + descriptiveName: + descriptiveNegativeName: + negativeButton: + positiveButton: + altNegativeButton: + altPositiveButton: + gravity: 0 + dead: 0.19 + sensitivity: 1 + snap: 0 + invert: 0 + type: 2 + axis: 0 + joyNum: 0 + - serializedVersion: 3 + m_Name: Vertical + descriptiveName: + descriptiveNegativeName: + negativeButton: + positiveButton: + altNegativeButton: + altPositiveButton: + gravity: 0 + dead: 0.19 + sensitivity: 1 + snap: 0 + invert: 1 + type: 2 + axis: 1 + joyNum: 0 + - serializedVersion: 3 + m_Name: Fire1 + descriptiveName: + descriptiveNegativeName: + negativeButton: + positiveButton: joystick button 0 + altNegativeButton: + altPositiveButton: + gravity: 1000 + dead: 0.001 + sensitivity: 1000 + snap: 0 + invert: 0 + type: 0 + axis: 0 + joyNum: 0 + - serializedVersion: 3 + m_Name: Fire2 + descriptiveName: + descriptiveNegativeName: + negativeButton: + positiveButton: joystick button 1 + altNegativeButton: + altPositiveButton: + gravity: 1000 + dead: 0.001 + sensitivity: 1000 + snap: 0 + invert: 0 + type: 0 + axis: 0 + joyNum: 0 + - serializedVersion: 3 + m_Name: Fire3 + descriptiveName: + descriptiveNegativeName: + negativeButton: + positiveButton: joystick button 2 + altNegativeButton: + altPositiveButton: + gravity: 1000 + dead: 0.001 + sensitivity: 1000 + snap: 0 + invert: 0 + type: 0 + axis: 0 + joyNum: 0 + - serializedVersion: 3 + m_Name: Jump + descriptiveName: + descriptiveNegativeName: + negativeButton: + positiveButton: joystick button 3 + altNegativeButton: + altPositiveButton: + gravity: 1000 + dead: 0.001 + sensitivity: 1000 + snap: 0 + invert: 0 + type: 0 + axis: 0 + joyNum: 0 + - serializedVersion: 3 + m_Name: Submit + descriptiveName: + descriptiveNegativeName: + negativeButton: + positiveButton: return + altNegativeButton: + altPositiveButton: joystick button 0 + gravity: 1000 + dead: 0.001 + sensitivity: 1000 + snap: 0 + invert: 0 + type: 0 + axis: 0 + joyNum: 0 + - serializedVersion: 3 + m_Name: Submit + descriptiveName: + descriptiveNegativeName: + negativeButton: + positiveButton: enter + altNegativeButton: + altPositiveButton: space + gravity: 1000 + dead: 0.001 + sensitivity: 1000 + snap: 0 + invert: 0 + type: 0 + axis: 0 + joyNum: 0 + - serializedVersion: 3 + m_Name: Cancel + descriptiveName: + descriptiveNegativeName: + negativeButton: + positiveButton: escape + altNegativeButton: + altPositiveButton: joystick button 1 + gravity: 1000 + dead: 0.001 + sensitivity: 1000 + snap: 0 + invert: 0 + type: 0 + axis: 0 + joyNum: 0 diff --git a/UnityCaptureSample/ProjectSettings/NavMeshAreas.asset b/UnityCaptureSample/ProjectSettings/NavMeshAreas.asset new file mode 100644 index 0000000..3b0b7c3 --- /dev/null +++ b/UnityCaptureSample/ProjectSettings/NavMeshAreas.asset @@ -0,0 +1,91 @@ +%YAML 1.1 +%TAG !u! tag:unity3d.com,2011: +--- !u!126 &1 +NavMeshProjectSettings: + m_ObjectHideFlags: 0 + serializedVersion: 2 + areas: + - name: Walkable + cost: 1 + - name: Not Walkable + cost: 1 + - name: Jump + cost: 2 + - name: + cost: 1 + - name: + cost: 1 + - name: + cost: 1 + - name: + cost: 1 + - name: + cost: 1 + - name: + cost: 1 + - name: + cost: 1 + - name: + cost: 1 + - name: + cost: 1 + - name: + cost: 1 + - name: + cost: 1 + - name: + cost: 1 + - name: + cost: 1 + - name: + cost: 1 + - name: + cost: 1 + - name: + cost: 1 + - name: + cost: 1 + - name: + cost: 1 + - name: + cost: 1 + - name: + cost: 1 + - name: + cost: 1 + - name: + cost: 1 + - name: + cost: 1 + - name: + cost: 1 + - name: + cost: 1 + - name: + cost: 1 + - name: + cost: 1 + - name: + cost: 1 + - name: + cost: 1 + m_LastAgentTypeID: -887442657 + m_Settings: + - serializedVersion: 2 + agentTypeID: 0 + agentRadius: 0.5 + agentHeight: 2 + agentSlope: 45 + agentClimb: 0.75 + ledgeDropHeight: 0 + maxJumpAcrossDistance: 0 + minRegionArea: 2 + manualCellSize: 0 + cellSize: 0.16666667 + manualTileSize: 0 + tileSize: 256 + accuratePlacement: 0 + debug: + m_Flags: 0 + m_SettingNames: + - Humanoid diff --git a/UnityCaptureSample/ProjectSettings/NetworkManager.asset b/UnityCaptureSample/ProjectSettings/NetworkManager.asset new file mode 100644 index 0000000..5dc6a83 --- /dev/null +++ b/UnityCaptureSample/ProjectSettings/NetworkManager.asset @@ -0,0 +1,8 @@ +%YAML 1.1 +%TAG !u! tag:unity3d.com,2011: +--- !u!149 &1 +NetworkManager: + m_ObjectHideFlags: 0 + m_DebugLevel: 0 + m_Sendrate: 15 + m_AssetToPrefab: {} diff --git a/UnityCaptureSample/ProjectSettings/Physics2DSettings.asset b/UnityCaptureSample/ProjectSettings/Physics2DSettings.asset new file mode 100644 index 0000000..132ee6b --- /dev/null +++ b/UnityCaptureSample/ProjectSettings/Physics2DSettings.asset @@ -0,0 +1,37 @@ +%YAML 1.1 +%TAG !u! tag:unity3d.com,2011: +--- !u!19 &1 +Physics2DSettings: + m_ObjectHideFlags: 0 + serializedVersion: 3 + m_Gravity: {x: 0, y: -9.81} + m_DefaultMaterial: {fileID: 0} + m_VelocityIterations: 8 + m_PositionIterations: 3 + m_VelocityThreshold: 1 + m_MaxLinearCorrection: 0.2 + m_MaxAngularCorrection: 8 + m_MaxTranslationSpeed: 100 + m_MaxRotationSpeed: 360 + m_BaumgarteScale: 0.2 + m_BaumgarteTimeOfImpactScale: 0.75 + m_TimeToSleep: 0.5 + m_LinearSleepTolerance: 0.01 + m_AngularSleepTolerance: 2 + m_DefaultContactOffset: 0.01 + m_AutoSimulation: 1 + m_QueriesHitTriggers: 1 + m_QueriesStartInColliders: 1 + m_ChangeStopsCallbacks: 0 + m_CallbacksOnDisable: 1 + m_AutoSyncTransforms: 1 + m_AlwaysShowColliders: 0 + m_ShowColliderSleep: 1 + m_ShowColliderContacts: 0 + m_ShowColliderAABB: 0 + m_ContactArrowScale: 0.2 + m_ColliderAwakeColor: {r: 0.5686275, g: 0.95686275, b: 0.54509807, a: 0.7529412} + m_ColliderAsleepColor: {r: 0.5686275, g: 0.95686275, b: 0.54509807, a: 0.36078432} + m_ColliderContactColor: {r: 1, g: 0, b: 1, a: 0.6862745} + m_ColliderAABBColor: {r: 1, g: 1, b: 0, a: 0.2509804} + m_LayerCollisionMatrix: ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff diff --git a/UnityCaptureSample/ProjectSettings/ProjectSettings.asset b/UnityCaptureSample/ProjectSettings/ProjectSettings.asset new file mode 100644 index 0000000..94f84c7 --- /dev/null +++ b/UnityCaptureSample/ProjectSettings/ProjectSettings.asset @@ -0,0 +1,639 @@ +%YAML 1.1 +%TAG !u! tag:unity3d.com,2011: +--- !u!129 &1 +PlayerSettings: + m_ObjectHideFlags: 0 + serializedVersion: 14 + productGUID: 25ebdaf9f91a03340a849d4e2b2c5542 + AndroidProfiler: 0 + AndroidFilterTouchesWhenObscured: 0 + defaultScreenOrientation: 4 + targetDevice: 2 + useOnDemandResources: 0 + accelerometerFrequency: 60 + companyName: DefaultCompany + productName: UnityCaptureSample + defaultCursor: {fileID: 0} + cursorHotspot: {x: 0, y: 0} + m_SplashScreenBackgroundColor: {r: 0.13725491, g: 0.12156863, b: 0.1254902, a: 1} + m_ShowUnitySplashScreen: 1 + m_ShowUnitySplashLogo: 1 + m_SplashScreenOverlayOpacity: 1 + m_SplashScreenAnimation: 1 + m_SplashScreenLogoStyle: 1 + m_SplashScreenDrawMode: 0 + m_SplashScreenBackgroundAnimationZoom: 1 + m_SplashScreenLogoAnimationZoom: 1 + m_SplashScreenBackgroundLandscapeAspect: 1 + m_SplashScreenBackgroundPortraitAspect: 1 + m_SplashScreenBackgroundLandscapeUvs: + serializedVersion: 2 + x: 0 + y: 0 + width: 1 + height: 1 + m_SplashScreenBackgroundPortraitUvs: + serializedVersion: 2 + x: 0 + y: 0 + width: 1 + height: 1 + m_SplashScreenLogos: [] + m_VirtualRealitySplashScreen: {fileID: 0} + m_HolographicTrackingLossScreen: {fileID: 0} + defaultScreenWidth: 1024 + defaultScreenHeight: 768 + defaultScreenWidthWeb: 960 + defaultScreenHeightWeb: 600 + m_StereoRenderingPath: 0 + m_ActiveColorSpace: 0 + m_MTRendering: 1 + m_StackTraceTypes: 010000000100000001000000010000000100000001000000 + iosShowActivityIndicatorOnLoading: -1 + androidShowActivityIndicatorOnLoading: -1 + tizenShowActivityIndicatorOnLoading: -1 + iosAppInBackgroundBehavior: 0 + displayResolutionDialog: 1 + iosAllowHTTPDownload: 1 + allowedAutorotateToPortrait: 1 + allowedAutorotateToPortraitUpsideDown: 1 + allowedAutorotateToLandscapeRight: 1 + allowedAutorotateToLandscapeLeft: 1 + useOSAutorotation: 1 + use32BitDisplayBuffer: 1 + preserveFramebufferAlpha: 0 + disableDepthAndStencilBuffers: 0 + androidBlitType: 0 + defaultIsFullScreen: 1 + defaultIsNativeResolution: 1 + macRetinaSupport: 1 + runInBackground: 1 + captureSingleScreen: 0 + muteOtherAudioSources: 0 + Prepare IOS For Recording: 0 + Force IOS Speakers When Recording: 0 + deferSystemGesturesMode: 0 + hideHomeButton: 0 + submitAnalytics: 1 + usePlayerLog: 1 + bakeCollisionMeshes: 0 + forceSingleInstance: 0 + resizableWindow: 0 + useMacAppStoreValidation: 0 + macAppStoreCategory: public.app-category.games + gpuSkinning: 0 + graphicsJobs: 0 + xboxPIXTextureCapture: 0 + xboxEnableAvatar: 0 + xboxEnableKinect: 0 + xboxEnableKinectAutoTracking: 0 + xboxEnableFitness: 0 + visibleInBackground: 1 + allowFullscreenSwitch: 1 + graphicsJobMode: 0 + macFullscreenMode: 2 + d3d11FullscreenMode: 1 + xboxSpeechDB: 0 + xboxEnableHeadOrientation: 0 + xboxEnableGuest: 0 + xboxEnablePIXSampling: 0 + metalFramebufferOnly: 0 + n3dsDisableStereoscopicView: 0 + n3dsEnableSharedListOpt: 1 + n3dsEnableVSync: 0 + xboxOneResolution: 0 + xboxOneSResolution: 0 + xboxOneXResolution: 3 + xboxOneMonoLoggingLevel: 0 + xboxOneLoggingLevel: 1 + xboxOneDisableEsram: 0 + xboxOnePresentImmediateThreshold: 0 + videoMemoryForVertexBuffers: 0 + psp2PowerMode: 0 + psp2AcquireBGM: 1 + wiiUTVResolution: 0 + wiiUGamePadMSAA: 1 + wiiUSupportsNunchuk: 0 + wiiUSupportsClassicController: 0 + wiiUSupportsBalanceBoard: 0 + wiiUSupportsMotionPlus: 0 + wiiUSupportsProController: 0 + wiiUAllowScreenCapture: 1 + wiiUControllerCount: 0 + m_SupportedAspectRatios: + 4:3: 1 + 5:4: 1 + 16:10: 1 + 16:9: 1 + Others: 1 + bundleVersion: 1.0 + preloadedAssets: [] + metroInputSource: 0 + wsaTransparentSwapchain: 0 + m_HolographicPauseOnTrackingLoss: 1 + xboxOneDisableKinectGpuReservation: 0 + xboxOneEnable7thCore: 0 + vrSettings: + cardboard: + depthFormat: 0 + enableTransitionView: 0 + daydream: + depthFormat: 0 + useSustainedPerformanceMode: 0 + enableVideoLayer: 0 + useProtectedVideoMemory: 0 + minimumSupportedHeadTracking: 0 + maximumSupportedHeadTracking: 1 + hololens: + depthFormat: 1 + depthBufferSharingEnabled: 0 + oculus: + sharedDepthBuffer: 0 + dashSupport: 0 + protectGraphicsMemory: 0 + useHDRDisplay: 0 + m_ColorGamuts: 00000000 + targetPixelDensity: 30 + resolutionScalingMode: 0 + androidSupportedAspectRatio: 1 + androidMaxAspectRatio: 2.1 + applicationIdentifier: {} + buildNumber: {} + AndroidBundleVersionCode: 1 + AndroidMinSdkVersion: 16 + AndroidTargetSdkVersion: 0 + AndroidPreferredInstallLocation: 1 + aotOptions: + stripEngineCode: 1 + iPhoneStrippingLevel: 0 + iPhoneScriptCallOptimization: 0 + ForceInternetPermission: 0 + ForceSDCardPermission: 0 + CreateWallpaper: 0 + APKExpansionFiles: 0 + keepLoadedShadersAlive: 0 + StripUnusedMeshComponents: 0 + VertexChannelCompressionMask: + serializedVersion: 2 + m_Bits: 238 + iPhoneSdkVersion: 988 + iOSTargetOSVersionString: 7.0 + tvOSSdkVersion: 0 + tvOSRequireExtendedGameController: 0 + tvOSTargetOSVersionString: 9.0 + uIPrerenderedIcon: 0 + uIRequiresPersistentWiFi: 0 + uIRequiresFullScreen: 1 + uIStatusBarHidden: 1 + uIExitOnSuspend: 0 + uIStatusBarStyle: 0 + iPhoneSplashScreen: {fileID: 0} + iPhoneHighResSplashScreen: {fileID: 0} + iPhoneTallHighResSplashScreen: {fileID: 0} + iPhone47inSplashScreen: {fileID: 0} + iPhone55inPortraitSplashScreen: {fileID: 0} + iPhone55inLandscapeSplashScreen: {fileID: 0} + iPhone58inPortraitSplashScreen: {fileID: 0} + iPhone58inLandscapeSplashScreen: {fileID: 0} + iPadPortraitSplashScreen: {fileID: 0} + iPadHighResPortraitSplashScreen: {fileID: 0} + iPadLandscapeSplashScreen: {fileID: 0} + iPadHighResLandscapeSplashScreen: {fileID: 0} + appleTVSplashScreen: {fileID: 0} + appleTVSplashScreen2x: {fileID: 0} + tvOSSmallIconLayers: [] + tvOSSmallIconLayers2x: [] + tvOSLargeIconLayers: [] + tvOSTopShelfImageLayers: [] + tvOSTopShelfImageLayers2x: [] + tvOSTopShelfImageWideLayers: [] + tvOSTopShelfImageWideLayers2x: [] + iOSLaunchScreenType: 0 + iOSLaunchScreenPortrait: {fileID: 0} + iOSLaunchScreenLandscape: {fileID: 0} + iOSLaunchScreenBackgroundColor: + serializedVersion: 2 + rgba: 0 + iOSLaunchScreenFillPct: 100 + iOSLaunchScreenSize: 100 + iOSLaunchScreenCustomXibPath: + iOSLaunchScreeniPadType: 0 + iOSLaunchScreeniPadImage: {fileID: 0} + iOSLaunchScreeniPadBackgroundColor: + serializedVersion: 2 + rgba: 0 + iOSLaunchScreeniPadFillPct: 100 + iOSLaunchScreeniPadSize: 100 + iOSLaunchScreeniPadCustomXibPath: + iOSUseLaunchScreenStoryboard: 0 + iOSLaunchScreenCustomStoryboardPath: + iOSDeviceRequirements: [] + iOSURLSchemes: [] + iOSBackgroundModes: 0 + iOSMetalForceHardShadows: 0 + metalEditorSupport: 1 + metalAPIValidation: 1 + iOSRenderExtraFrameOnPause: 0 + appleDeveloperTeamID: + iOSManualSigningProvisioningProfileID: + tvOSManualSigningProvisioningProfileID: + appleEnableAutomaticSigning: 0 + clonedFromGUID: 00000000000000000000000000000000 + AndroidTargetDevice: 0 + AndroidSplashScreenScale: 0 + androidSplashScreen: {fileID: 0} + AndroidKeystoreName: + AndroidKeyaliasName: + AndroidTVCompatibility: 1 + AndroidIsGame: 1 + AndroidEnableTango: 0 + androidEnableBanner: 1 + androidUseLowAccuracyLocation: 0 + m_AndroidBanners: + - width: 320 + height: 180 + banner: {fileID: 0} + androidGamepadSupportLevel: 0 + resolutionDialogBanner: {fileID: 0} + m_BuildTargetIcons: [] + m_BuildTargetBatching: [] + m_BuildTargetGraphicsAPIs: [] + m_BuildTargetVRSettings: [] + m_BuildTargetEnableVuforiaSettings: [] + openGLRequireES31: 0 + openGLRequireES31AEP: 0 + m_TemplateCustomTags: {} + mobileMTRendering: + iPhone: 1 + tvOS: 1 + m_BuildTargetGroupLightmapEncodingQuality: [] + wiiUTitleID: 0005000011000000 + wiiUGroupID: 00010000 + wiiUCommonSaveSize: 4096 + wiiUAccountSaveSize: 2048 + wiiUOlvAccessKey: 0 + wiiUTinCode: 0 + wiiUJoinGameId: 0 + wiiUJoinGameModeMask: 0000000000000000 + wiiUCommonBossSize: 0 + wiiUAccountBossSize: 0 + wiiUAddOnUniqueIDs: [] + wiiUMainThreadStackSize: 3072 + wiiULoaderThreadStackSize: 1024 + wiiUSystemHeapSize: 128 + wiiUTVStartupScreen: {fileID: 0} + wiiUGamePadStartupScreen: {fileID: 0} + wiiUDrcBufferDisabled: 0 + wiiUProfilerLibPath: + playModeTestRunnerEnabled: 0 + actionOnDotNetUnhandledException: 1 + enableInternalProfiler: 0 + logObjCUncaughtExceptions: 1 + enableCrashReportAPI: 0 + cameraUsageDescription: + locationUsageDescription: + microphoneUsageDescription: + switchNetLibKey: + switchSocketMemoryPoolSize: 6144 + switchSocketAllocatorPoolSize: 128 + switchSocketConcurrencyLimit: 14 + switchScreenResolutionBehavior: 2 + switchUseCPUProfiler: 0 + switchApplicationID: 0x01004b9000490000 + switchNSODependencies: + switchTitleNames_0: + switchTitleNames_1: + switchTitleNames_2: + switchTitleNames_3: + switchTitleNames_4: + switchTitleNames_5: + switchTitleNames_6: + switchTitleNames_7: + switchTitleNames_8: + switchTitleNames_9: + switchTitleNames_10: + switchTitleNames_11: + switchTitleNames_12: + switchTitleNames_13: + switchTitleNames_14: + switchPublisherNames_0: + switchPublisherNames_1: + switchPublisherNames_2: + switchPublisherNames_3: + switchPublisherNames_4: + switchPublisherNames_5: + switchPublisherNames_6: + switchPublisherNames_7: + switchPublisherNames_8: + switchPublisherNames_9: + switchPublisherNames_10: + switchPublisherNames_11: + switchPublisherNames_12: + switchPublisherNames_13: + switchPublisherNames_14: + switchIcons_0: {fileID: 0} + switchIcons_1: {fileID: 0} + switchIcons_2: {fileID: 0} + switchIcons_3: {fileID: 0} + switchIcons_4: {fileID: 0} + switchIcons_5: {fileID: 0} + switchIcons_6: {fileID: 0} + switchIcons_7: {fileID: 0} + switchIcons_8: {fileID: 0} + switchIcons_9: {fileID: 0} + switchIcons_10: {fileID: 0} + switchIcons_11: {fileID: 0} + switchIcons_12: {fileID: 0} + switchIcons_13: {fileID: 0} + switchIcons_14: {fileID: 0} + switchSmallIcons_0: {fileID: 0} + switchSmallIcons_1: {fileID: 0} + switchSmallIcons_2: {fileID: 0} + switchSmallIcons_3: {fileID: 0} + switchSmallIcons_4: {fileID: 0} + switchSmallIcons_5: {fileID: 0} + switchSmallIcons_6: {fileID: 0} + switchSmallIcons_7: {fileID: 0} + switchSmallIcons_8: {fileID: 0} + switchSmallIcons_9: {fileID: 0} + switchSmallIcons_10: {fileID: 0} + switchSmallIcons_11: {fileID: 0} + switchSmallIcons_12: {fileID: 0} + switchSmallIcons_13: {fileID: 0} + switchSmallIcons_14: {fileID: 0} + switchManualHTML: + switchAccessibleURLs: + switchLegalInformation: + switchMainThreadStackSize: 1048576 + switchPresenceGroupId: + switchLogoHandling: 0 + switchReleaseVersion: 0 + switchDisplayVersion: 1.0.0 + switchStartupUserAccount: 0 + switchTouchScreenUsage: 0 + switchSupportedLanguagesMask: 0 + switchLogoType: 0 + switchApplicationErrorCodeCategory: + switchUserAccountSaveDataSize: 0 + switchUserAccountSaveDataJournalSize: 0 + switchApplicationAttribute: 0 + switchCardSpecSize: -1 + switchCardSpecClock: -1 + switchRatingsMask: 0 + switchRatingsInt_0: 0 + switchRatingsInt_1: 0 + switchRatingsInt_2: 0 + switchRatingsInt_3: 0 + switchRatingsInt_4: 0 + switchRatingsInt_5: 0 + switchRatingsInt_6: 0 + switchRatingsInt_7: 0 + switchRatingsInt_8: 0 + switchRatingsInt_9: 0 + switchRatingsInt_10: 0 + switchRatingsInt_11: 0 + switchLocalCommunicationIds_0: + switchLocalCommunicationIds_1: + switchLocalCommunicationIds_2: + switchLocalCommunicationIds_3: + switchLocalCommunicationIds_4: + switchLocalCommunicationIds_5: + switchLocalCommunicationIds_6: + switchLocalCommunicationIds_7: + switchParentalControl: 0 + switchAllowsScreenshot: 1 + switchAllowsVideoCapturing: 1 + switchAllowsRuntimeAddOnContentInstall: 0 + switchDataLossConfirmation: 0 + switchSupportedNpadStyles: 3 + switchSocketConfigEnabled: 0 + switchTcpInitialSendBufferSize: 32 + switchTcpInitialReceiveBufferSize: 64 + switchTcpAutoSendBufferSizeMax: 256 + switchTcpAutoReceiveBufferSizeMax: 256 + switchUdpSendBufferSize: 9 + switchUdpReceiveBufferSize: 42 + switchSocketBufferEfficiency: 4 + switchSocketInitializeEnabled: 1 + switchNetworkInterfaceManagerInitializeEnabled: 1 + switchPlayerConnectionEnabled: 1 + ps4NPAgeRating: 12 + ps4NPTitleSecret: + ps4NPTrophyPackPath: + ps4ParentalLevel: 11 + ps4ContentID: ED1633-NPXX51362_00-0000000000000000 + ps4Category: 0 + ps4MasterVersion: 01.00 + ps4AppVersion: 01.00 + ps4AppType: 0 + ps4ParamSfxPath: + ps4VideoOutPixelFormat: 0 + ps4VideoOutInitialWidth: 1920 + ps4VideoOutBaseModeInitialWidth: 1920 + ps4VideoOutReprojectionRate: 60 + ps4PronunciationXMLPath: + ps4PronunciationSIGPath: + ps4BackgroundImagePath: + ps4StartupImagePath: + ps4StartupImagesFolder: + ps4IconImagesFolder: + ps4SaveDataImagePath: + ps4SdkOverride: + ps4BGMPath: + ps4ShareFilePath: + ps4ShareOverlayImagePath: + ps4PrivacyGuardImagePath: + ps4NPtitleDatPath: + ps4RemotePlayKeyAssignment: -1 + ps4RemotePlayKeyMappingDir: + ps4PlayTogetherPlayerCount: 0 + ps4EnterButtonAssignment: 1 + ps4ApplicationParam1: 0 + ps4ApplicationParam2: 0 + ps4ApplicationParam3: 0 + ps4ApplicationParam4: 0 + ps4DownloadDataSize: 0 + ps4GarlicHeapSize: 2048 + ps4ProGarlicHeapSize: 2560 + ps4Passcode: frAQBc8Wsa1xVPfvJcrgRYwTiizs2trQ + ps4pnSessions: 1 + ps4pnPresence: 1 + ps4pnFriends: 1 + ps4pnGameCustomData: 1 + playerPrefsSupport: 0 + restrictedAudioUsageRights: 0 + ps4UseResolutionFallback: 0 + ps4ReprojectionSupport: 0 + ps4UseAudio3dBackend: 0 + ps4SocialScreenEnabled: 0 + ps4ScriptOptimizationLevel: 0 + ps4Audio3dVirtualSpeakerCount: 14 + ps4attribCpuUsage: 0 + ps4PatchPkgPath: + ps4PatchLatestPkgPath: + ps4PatchChangeinfoPath: + ps4PatchDayOne: 0 + ps4attribUserManagement: 0 + ps4attribMoveSupport: 0 + ps4attrib3DSupport: 0 + ps4attribShareSupport: 0 + ps4attribExclusiveVR: 0 + ps4disableAutoHideSplash: 0 + ps4videoRecordingFeaturesUsed: 0 + ps4contentSearchFeaturesUsed: 0 + ps4attribEyeToEyeDistanceSettingVR: 0 + ps4IncludedModules: [] + monoEnv: + psp2Splashimage: {fileID: 0} + psp2NPTrophyPackPath: + psp2NPSupportGBMorGJP: 0 + psp2NPAgeRating: 12 + psp2NPTitleDatPath: + psp2NPCommsID: + psp2NPCommunicationsID: + psp2NPCommsPassphrase: + psp2NPCommsSig: + psp2ParamSfxPath: + psp2ManualPath: + psp2LiveAreaGatePath: + psp2LiveAreaBackroundPath: + psp2LiveAreaPath: + psp2LiveAreaTrialPath: + psp2PatchChangeInfoPath: + psp2PatchOriginalPackage: + psp2PackagePassword: F69AzBlax3CF3EDNhm3soLBPh71Yexui + psp2KeystoneFile: + psp2MemoryExpansionMode: 0 + psp2DRMType: 0 + psp2StorageType: 0 + psp2MediaCapacity: 0 + psp2DLCConfigPath: + psp2ThumbnailPath: + psp2BackgroundPath: + psp2SoundPath: + psp2TrophyCommId: + psp2TrophyPackagePath: + psp2PackagedResourcesPath: + psp2SaveDataQuota: 10240 + psp2ParentalLevel: 1 + psp2ShortTitle: Not Set + psp2ContentID: IV0000-ABCD12345_00-0123456789ABCDEF + psp2Category: 0 + psp2MasterVersion: 01.00 + psp2AppVersion: 01.00 + psp2TVBootMode: 0 + psp2EnterButtonAssignment: 2 + psp2TVDisableEmu: 0 + psp2AllowTwitterDialog: 1 + psp2Upgradable: 0 + psp2HealthWarning: 0 + psp2UseLibLocation: 0 + psp2InfoBarOnStartup: 0 + psp2InfoBarColor: 0 + psp2ScriptOptimizationLevel: 0 + psmSplashimage: {fileID: 0} + splashScreenBackgroundSourceLandscape: {fileID: 0} + splashScreenBackgroundSourcePortrait: {fileID: 0} + spritePackerPolicy: + webGLMemorySize: 256 + webGLExceptionSupport: 1 + webGLNameFilesAsHashes: 0 + webGLDataCaching: 0 + webGLDebugSymbols: 0 + webGLEmscriptenArgs: + webGLModulesDirectory: + webGLTemplate: APPLICATION:Default + webGLAnalyzeBuildSize: 0 + webGLUseEmbeddedResources: 0 + webGLUseWasm: 0 + webGLCompressionFormat: 1 + scriptingDefineSymbols: {} + platformArchitecture: {} + scriptingBackend: {} + incrementalIl2cppBuild: {} + additionalIl2CppArgs: + scriptingRuntimeVersion: 0 + apiCompatibilityLevelPerPlatform: {} + m_RenderingPath: 1 + m_MobileRenderingPath: 1 + metroPackageName: UnityCaptureSample + metroPackageVersion: + metroCertificatePath: + metroCertificatePassword: + metroCertificateSubject: + metroCertificateIssuer: + metroCertificateNotAfter: 0000000000000000 + metroApplicationDescription: UnityCaptureSample + wsaImages: {} + metroTileShortName: + metroCommandLineArgsFile: + metroTileShowName: 0 + metroMediumTileShowName: 0 + metroLargeTileShowName: 0 + metroWideTileShowName: 0 + metroDefaultTileSize: 1 + metroTileForegroundText: 2 + metroTileBackgroundColor: {r: 0.13333334, g: 0.17254902, b: 0.21568628, a: 0} + metroSplashScreenBackgroundColor: {r: 0.12941177, g: 0.17254902, b: 0.21568628, + a: 1} + metroSplashScreenUseBackgroundColor: 0 + platformCapabilities: {} + metroFTAName: + metroFTAFileTypes: [] + metroProtocolName: + metroCompilationOverrides: 1 + tizenProductDescription: + tizenProductURL: + tizenSigningProfileName: + tizenGPSPermissions: 0 + tizenMicrophonePermissions: 0 + tizenDeploymentTarget: + tizenDeploymentTargetType: -1 + tizenMinOSVersion: 1 + n3dsUseExtSaveData: 0 + n3dsCompressStaticMem: 1 + n3dsExtSaveDataNumber: 0x12345 + n3dsStackSize: 131072 + n3dsTargetPlatform: 2 + n3dsRegion: 7 + n3dsMediaSize: 0 + n3dsLogoStyle: 3 + n3dsTitle: GameName + n3dsProductCode: + n3dsApplicationId: 0xFF3FF + XboxOneProductId: + XboxOneUpdateKey: + XboxOneSandboxId: + XboxOneContentId: + XboxOneTitleId: + XboxOneSCId: + XboxOneGameOsOverridePath: + XboxOnePackagingOverridePath: + XboxOneAppManifestOverridePath: + XboxOnePackageEncryption: 0 + XboxOnePackageUpdateGranularity: 2 + XboxOneDescription: + XboxOneLanguage: + - enus + XboxOneCapability: [] + XboxOneGameRating: {} + XboxOneIsContentPackage: 0 + XboxOneEnableGPUVariability: 0 + XboxOneSockets: {} + XboxOneSplashScreen: {fileID: 0} + XboxOneAllowedProductIds: [] + XboxOnePersistentLocalStorageSize: 0 + xboxOneScriptCompiler: 0 + vrEditorSettings: + daydream: + daydreamIconForeground: {fileID: 0} + daydreamIconBackground: {fileID: 0} + cloudServicesEnabled: {} + facebookSdkVersion: 7.9.4 + apiCompatibilityLevel: 2 + cloudProjectId: + projectName: + organizationId: + cloudEnabled: 0 + enableNativePlatformBackendsForNewInputSystem: 0 + disableOldInputManagerSupport: 0 diff --git a/UnityCaptureSample/ProjectSettings/ProjectVersion.txt b/UnityCaptureSample/ProjectSettings/ProjectVersion.txt new file mode 100644 index 0000000..fe370fd --- /dev/null +++ b/UnityCaptureSample/ProjectSettings/ProjectVersion.txt @@ -0,0 +1 @@ +m_EditorVersion: 2017.3.1p1 diff --git a/UnityCaptureSample/ProjectSettings/QualitySettings.asset b/UnityCaptureSample/ProjectSettings/QualitySettings.asset new file mode 100644 index 0000000..05daac3 --- /dev/null +++ b/UnityCaptureSample/ProjectSettings/QualitySettings.asset @@ -0,0 +1,191 @@ +%YAML 1.1 +%TAG !u! tag:unity3d.com,2011: +--- !u!47 &1 +QualitySettings: + m_ObjectHideFlags: 0 + serializedVersion: 5 + m_CurrentQuality: 5 + m_QualitySettings: + - serializedVersion: 2 + name: Very Low + pixelLightCount: 0 + shadows: 0 + shadowResolution: 0 + shadowProjection: 1 + shadowCascades: 1 + shadowDistance: 15 + shadowNearPlaneOffset: 3 + shadowCascade2Split: 0.33333334 + shadowCascade4Split: {x: 0.06666667, y: 0.2, z: 0.46666667} + shadowmaskMode: 0 + blendWeights: 1 + textureQuality: 1 + anisotropicTextures: 0 + antiAliasing: 0 + softParticles: 0 + softVegetation: 0 + realtimeReflectionProbes: 0 + billboardsFaceCameraPosition: 0 + vSyncCount: 0 + lodBias: 0.3 + maximumLODLevel: 0 + particleRaycastBudget: 4 + asyncUploadTimeSlice: 2 + asyncUploadBufferSize: 4 + resolutionScalingFixedDPIFactor: 1 + excludedTargetPlatforms: [] + - serializedVersion: 2 + name: Low + pixelLightCount: 0 + shadows: 0 + shadowResolution: 0 + shadowProjection: 1 + shadowCascades: 1 + shadowDistance: 20 + shadowNearPlaneOffset: 3 + shadowCascade2Split: 0.33333334 + shadowCascade4Split: {x: 0.06666667, y: 0.2, z: 0.46666667} + shadowmaskMode: 0 + blendWeights: 2 + textureQuality: 0 + anisotropicTextures: 0 + antiAliasing: 0 + softParticles: 0 + softVegetation: 0 + realtimeReflectionProbes: 0 + billboardsFaceCameraPosition: 0 + vSyncCount: 0 + lodBias: 0.4 + maximumLODLevel: 0 + particleRaycastBudget: 16 + asyncUploadTimeSlice: 2 + asyncUploadBufferSize: 4 + resolutionScalingFixedDPIFactor: 1 + excludedTargetPlatforms: [] + - serializedVersion: 2 + name: Medium + pixelLightCount: 1 + shadows: 1 + shadowResolution: 0 + shadowProjection: 1 + shadowCascades: 1 + shadowDistance: 20 + shadowNearPlaneOffset: 3 + shadowCascade2Split: 0.33333334 + shadowCascade4Split: {x: 0.06666667, y: 0.2, z: 0.46666667} + shadowmaskMode: 0 + blendWeights: 2 + textureQuality: 0 + anisotropicTextures: 1 + antiAliasing: 0 + softParticles: 0 + softVegetation: 0 + realtimeReflectionProbes: 0 + billboardsFaceCameraPosition: 0 + vSyncCount: 1 + lodBias: 0.7 + maximumLODLevel: 0 + particleRaycastBudget: 64 + asyncUploadTimeSlice: 2 + asyncUploadBufferSize: 4 + resolutionScalingFixedDPIFactor: 1 + excludedTargetPlatforms: [] + - serializedVersion: 2 + name: High + pixelLightCount: 2 + shadows: 2 + shadowResolution: 1 + shadowProjection: 1 + shadowCascades: 2 + shadowDistance: 40 + shadowNearPlaneOffset: 3 + shadowCascade2Split: 0.33333334 + shadowCascade4Split: {x: 0.06666667, y: 0.2, z: 0.46666667} + shadowmaskMode: 1 + blendWeights: 2 + textureQuality: 0 + anisotropicTextures: 1 + antiAliasing: 0 + softParticles: 0 + softVegetation: 1 + realtimeReflectionProbes: 1 + billboardsFaceCameraPosition: 1 + vSyncCount: 1 + lodBias: 1 + maximumLODLevel: 0 + particleRaycastBudget: 256 + asyncUploadTimeSlice: 2 + asyncUploadBufferSize: 4 + resolutionScalingFixedDPIFactor: 1 + excludedTargetPlatforms: [] + - serializedVersion: 2 + name: Very High + pixelLightCount: 3 + shadows: 2 + shadowResolution: 2 + shadowProjection: 1 + shadowCascades: 2 + shadowDistance: 70 + shadowNearPlaneOffset: 3 + shadowCascade2Split: 0.33333334 + shadowCascade4Split: {x: 0.06666667, y: 0.2, z: 0.46666667} + shadowmaskMode: 1 + blendWeights: 4 + textureQuality: 0 + anisotropicTextures: 2 + antiAliasing: 2 + softParticles: 1 + softVegetation: 1 + realtimeReflectionProbes: 1 + billboardsFaceCameraPosition: 1 + vSyncCount: 1 + lodBias: 1.5 + maximumLODLevel: 0 + particleRaycastBudget: 1024 + asyncUploadTimeSlice: 2 + asyncUploadBufferSize: 4 + resolutionScalingFixedDPIFactor: 1 + excludedTargetPlatforms: [] + - serializedVersion: 2 + name: Ultra + pixelLightCount: 4 + shadows: 2 + shadowResolution: 2 + shadowProjection: 1 + shadowCascades: 4 + shadowDistance: 150 + shadowNearPlaneOffset: 3 + shadowCascade2Split: 0.33333334 + shadowCascade4Split: {x: 0.06666667, y: 0.2, z: 0.46666667} + shadowmaskMode: 1 + blendWeights: 4 + textureQuality: 0 + anisotropicTextures: 2 + antiAliasing: 2 + softParticles: 1 + softVegetation: 1 + realtimeReflectionProbes: 1 + billboardsFaceCameraPosition: 1 + vSyncCount: 1 + lodBias: 2 + maximumLODLevel: 0 + particleRaycastBudget: 4096 + asyncUploadTimeSlice: 2 + asyncUploadBufferSize: 4 + resolutionScalingFixedDPIFactor: 1 + excludedTargetPlatforms: [] + m_PerPlatformDefaultQuality: + Android: 2 + Nintendo 3DS: 5 + Nintendo Switch: 5 + PS4: 5 + PSM: 5 + PSP2: 2 + Standalone: 5 + Tizen: 2 + WebGL: 3 + WiiU: 5 + Windows Store Apps: 5 + XboxOne: 5 + iPhone: 2 + tvOS: 2 diff --git a/UnityCaptureSample/ProjectSettings/TagManager.asset b/UnityCaptureSample/ProjectSettings/TagManager.asset new file mode 100644 index 0000000..1c92a78 --- /dev/null +++ b/UnityCaptureSample/ProjectSettings/TagManager.asset @@ -0,0 +1,43 @@ +%YAML 1.1 +%TAG !u! tag:unity3d.com,2011: +--- !u!78 &1 +TagManager: + serializedVersion: 2 + tags: [] + layers: + - Default + - TransparentFX + - Ignore Raycast + - + - Water + - UI + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + m_SortingLayers: + - name: Default + uniqueID: 0 + locked: 0 diff --git a/UnityCaptureSample/ProjectSettings/TimeManager.asset b/UnityCaptureSample/ProjectSettings/TimeManager.asset new file mode 100644 index 0000000..558a017 --- /dev/null +++ b/UnityCaptureSample/ProjectSettings/TimeManager.asset @@ -0,0 +1,9 @@ +%YAML 1.1 +%TAG !u! tag:unity3d.com,2011: +--- !u!5 &1 +TimeManager: + m_ObjectHideFlags: 0 + Fixed Timestep: 0.02 + Maximum Allowed Timestep: 0.33333334 + m_TimeScale: 1 + Maximum Particle Timestep: 0.03 diff --git a/UnityCaptureSample/ProjectSettings/UnityConnectSettings.asset b/UnityCaptureSample/ProjectSettings/UnityConnectSettings.asset new file mode 100644 index 0000000..3da14d5 --- /dev/null +++ b/UnityCaptureSample/ProjectSettings/UnityConnectSettings.asset @@ -0,0 +1,34 @@ +%YAML 1.1 +%TAG !u! tag:unity3d.com,2011: +--- !u!310 &1 +UnityConnectSettings: + m_ObjectHideFlags: 0 + m_Enabled: 0 + m_TestMode: 0 + m_TestEventUrl: + m_TestConfigUrl: + m_TestInitMode: 0 + CrashReportingSettings: + m_EventUrl: https://perf-events.cloud.unity3d.com/api/events/crashes + m_NativeEventUrl: https://perf-events.cloud.unity3d.com/symbolicate + m_Enabled: 0 + m_CaptureEditorExceptions: 1 + UnityPurchasingSettings: + m_Enabled: 0 + m_TestMode: 0 + UnityAnalyticsSettings: + m_Enabled: 0 + m_InitializeOnStartup: 1 + m_TestMode: 0 + m_TestEventUrl: + m_TestConfigUrl: + UnityAdsSettings: + m_Enabled: 0 + m_InitializeOnStartup: 1 + m_TestMode: 0 + m_IosGameId: + m_AndroidGameId: + m_GameIds: {} + m_GameId: + PerformanceReportingSettings: + m_Enabled: 0 diff --git a/UnitySample/.gitignore b/UnitySample/.gitignore deleted file mode 100644 index ae62a0c..0000000 --- a/UnitySample/.gitignore +++ /dev/null @@ -1,2 +0,0 @@ -Library/* -Temp/* \ No newline at end of file diff --git a/UnitySample/Assembly-CSharp-Editor.csproj b/UnitySample/Assembly-CSharp-Editor.csproj deleted file mode 100644 index 08202d4..0000000 --- a/UnitySample/Assembly-CSharp-Editor.csproj +++ /dev/null @@ -1,126 +0,0 @@ - - - - Debug - AnyCPU - 10.0.20506 - 2.0 - - {9C21D318-2030-5359-A548-3B6B7BE01728} - Library - Properties - Assembly-CSharp-Editor - v3.5 - 512 - Assets - - - true - full - false - Temp\bin\Debug\ - DEBUG;TRACE;UNITY_5_3_OR_NEWER;UNITY_5_4_OR_NEWER;UNITY_5_5_OR_NEWER;UNITY_5_5_1;UNITY_5_5;UNITY_5;ENABLE_AUDIO;ENABLE_CACHING;ENABLE_CLOTH;ENABLE_DUCK_TYPING;ENABLE_GENERICS;ENABLE_MICROPHONE;ENABLE_MULTIPLE_DISPLAYS;ENABLE_PHYSICS;ENABLE_SPRITERENDERER_FLIPPING;ENABLE_SPRITES;ENABLE_TERRAIN;ENABLE_RAKNET;ENABLE_UNET;ENABLE_LZMA;ENABLE_UNITYEVENTS;ENABLE_WEBCAM;ENABLE_WWW;ENABLE_CLOUD_SERVICES_COLLAB;ENABLE_CLOUD_SERVICES_ADS;ENABLE_CLOUD_HUB;ENABLE_CLOUD_PROJECT_ID;ENABLE_CLOUD_SERVICES_UNET;ENABLE_CLOUD_SERVICES_BUILD;ENABLE_CLOUD_LICENSE;ENABLE_EDITOR_METRICS;ENABLE_EDITOR_METRICS_CACHING;INCLUDE_DYNAMIC_GI;INCLUDE_GI;PLATFORM_SUPPORTS_MONO;RENDER_SOFTWARE_CURSOR;INCLUDE_PUBNUB;ENABLE_PLAYMODE_TESTS_RUNNER;ENABLE_SCRIPTING_NEW_CSHARP_COMPILER;UNITY_STANDALONE_WIN;UNITY_STANDALONE;ENABLE_SUBSTANCE;ENABLE_RUNTIME_GI;ENABLE_MOVIES;ENABLE_NETWORK;ENABLE_CRUNCH_TEXTURE_COMPRESSION;ENABLE_UNITYWEBREQUEST;ENABLE_CLOUD_SERVICES;ENABLE_CLOUD_SERVICES_ANALYTICS;ENABLE_CLOUD_SERVICES_PURCHASING;ENABLE_CLOUD_SERVICES_CRASH_REPORTING;ENABLE_EVENT_QUEUE;ENABLE_CLUSTERINPUT;ENABLE_VIDEO;ENABLE_VR;ENABLE_WEBSOCKET_HOST;ENABLE_MONO;ENABLE_PROFILER;UNITY_ASSERTIONS;UNITY_EDITOR;UNITY_EDITOR_64;UNITY_EDITOR_WIN;UNITY_TEAM_LICENSE - prompt - 4 - 0169 - - - pdbonly - true - Temp\bin\Release\ - prompt - 4 - 0169 - - - - - - - - - C:/Program Files/Unity/Editor/Data/Managed/UnityEngine.dll - - - C:/Program Files/Unity/Editor/Data/Managed/UnityEditor.dll - - - - - - - - C:/Program Files/Unity/Editor/Data/UnityExtensions/Unity/Advertisements/Editor/UnityEditor.Advertisements.dll - - - C:/Program Files/Unity/Editor/Data/UnityExtensions/Unity/EditorTestsRunner/Editor/nunit.framework.dll - - - C:/Program Files/Unity/Editor/Data/UnityExtensions/Unity/EditorTestsRunner/Editor/UnityEditor.EditorTestsRunner.dll - - - C:/Program Files/Unity/Editor/Data/UnityExtensions/Unity/GUISystem/UnityEngine.UI.dll - - - C:/Program Files/Unity/Editor/Data/UnityExtensions/Unity/GUISystem/Editor/UnityEditor.UI.dll - - - C:/Program Files/Unity/Editor/Data/UnityExtensions/Unity/Networking/UnityEngine.Networking.dll - - - C:/Program Files/Unity/Editor/Data/UnityExtensions/Unity/Networking/Editor/UnityEditor.Networking.dll - - - C:/Program Files/Unity/Editor/Data/UnityExtensions/Unity/PlaymodeTestsRunner/Editor/UnityEditor.PlaymodeTestsRunner.dll - - - C:/Program Files/Unity/Editor/Data/UnityExtensions/Unity/PlaymodeTestsRunner/UnityEngine.PlaymodeTestsRunner.dll - - - C:/Program Files/Unity/Editor/Data/UnityExtensions/Unity/TreeEditor/Editor/UnityEditor.TreeEditor.dll - - - C:/Program Files/Unity/Editor/Data/UnityExtensions/Unity/UnityAnalytics/UnityEngine.Analytics.dll - - - C:/Program Files/Unity/Editor/Data/UnityExtensions/Unity/UnityAnalytics/Editor/UnityEditor.Analytics.dll - - - C:/Program Files/Unity/Editor/Data/UnityExtensions/Unity/UnityHoloLens/Editor/UnityEditor.HoloLens.dll - - - C:/Program Files/Unity/Editor/Data/UnityExtensions/Unity/UnityHoloLens/RuntimeEditor/UnityEngine.HoloLens.dll - - - C:/Program Files/Unity/Editor/Data/UnityExtensions/Unity/UnityVR/Editor/UnityEditor.VR.dll - - - C:/Program Files/Unity/Editor/Data/UnityExtensions/Unity/UnityVR/RuntimeEditor/UnityEngine.VR.dll - - - D:/Development/GitRepos/UnityCam/UnitySample/Assets/AssetStoreTools/Editor/AssetStoreTools.dll - - - D:/Development/GitRepos/UnityCam/UnitySample/Assets/AssetStoreTools/Editor/AssetStoreToolsExtra.dll - - - C:/Program Files/Unity/Editor/Data/Managed/UnityEditor.Graphs.dll - - - C:/Program Files/Unity/Editor/Data/PlaybackEngines/windowsstandalonesupport/UnityEditor.WindowsStandalone.Extensions.dll - - - - - {8CA90CBA-908E-E48D-E4F6-89E98795426A} Assembly-CSharp - - - - - diff --git a/UnitySample/Assembly-CSharp-firstpass.csproj b/UnitySample/Assembly-CSharp-firstpass.csproj deleted file mode 100644 index 12072ef..0000000 --- a/UnitySample/Assembly-CSharp-firstpass.csproj +++ /dev/null @@ -1,184 +0,0 @@ - - - - Debug - AnyCPU - 10.0.20506 - 2.0 - - {17D86F22-6A80-78B5-D20B-83606EA7742E} - Library - Properties - Assembly-CSharp-firstpass - v3.5 - 512 - Assets - - - true - full - false - Temp\bin\Debug\ - DEBUG;TRACE;UNITY_5_3_3;UNITY_5_3;UNITY_5;ENABLE_NEW_BUGREPORTER;ENABLE_AUDIO;ENABLE_CACHING;ENABLE_CLOTH;ENABLE_DUCK_TYPING;ENABLE_FRAME_DEBUGGER;ENABLE_GENERICS;ENABLE_HOME_SCREEN;ENABLE_IMAGEEFFECTS;ENABLE_LIGHT_PROBES_LEGACY;ENABLE_MICROPHONE;ENABLE_MULTIPLE_DISPLAYS;ENABLE_PHYSICS;ENABLE_PLUGIN_INSPECTOR;ENABLE_SHADOWS;ENABLE_SINGLE_INSTANCE_BUILD_SETTING;ENABLE_SPRITERENDERER_FLIPPING;ENABLE_SPRITES;ENABLE_SPRITE_POLYGON;ENABLE_TERRAIN;ENABLE_RAKNET;ENABLE_UNET;ENABLE_UNITYEVENTS;ENABLE_WEBCAM;ENABLE_WWW;ENABLE_CLOUD_SERVICES;ENABLE_CLOUD_SERVICES_ADS;ENABLE_CLOUD_HUB;ENABLE_CLOUD_PROJECT_ID;ENABLE_CLOUD_SERVICES_PURCHASING;ENABLE_CLOUD_SERVICES_ANALYTICS;ENABLE_CLOUD_SERVICES_UNET;ENABLE_CLOUD_SERVICES_BUILD;ENABLE_CLOUD_LICENSE;ENABLE_EDITOR_METRICS;ENABLE_EDITOR_METRICS_CACHING;INCLUDE_DYNAMIC_GI;INCLUDE_GI;INCLUDE_IL2CPP;INCLUDE_DIRECTX12;PLATFORM_SUPPORTS_MONO;RENDER_SOFTWARE_CURSOR;ENABLE_LOCALIZATION;ENABLE_ANDROID_ATLAS_ETC1_COMPRESSION;ENABLE_EDITOR_TESTS_RUNNER;UNITY_WEBPLAYER;ENABLE_SUBSTANCE;WEBPLUG;ENABLE_TEXTUREID_MAP;ENABLE_RUNTIME_GI;ENABLE_MOVIES;ENABLE_NETWORK;ENABLE_CRUNCH_TEXTURE_COMPRESSION;ENABLE_MONO;ENABLE_PROFILER;UNITY_ASSERTIONS;UNITY_EDITOR;UNITY_EDITOR_64;UNITY_EDITOR_WIN - prompt - 4 - 0169 - - - pdbonly - true - Temp\bin\Release\ - prompt - 4 - 0169 - - - - - - - - C:/Program Files/Unity/Editor/Data/Managed/UnityEngine.dll - - - C:/Program Files/Unity/Editor/Data/Managed/UnityEditor.dll - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - C:/Program Files/Unity/Editor/Data/UnityExtensions/Unity/GUISystem/UnityEngine.UI.dll - - - C:/Program Files/Unity/Editor/Data/UnityExtensions/Unity/Networking/UnityEngine.Networking.dll - - - - - - diff --git a/UnitySample/Assembly-CSharp.csproj b/UnitySample/Assembly-CSharp.csproj deleted file mode 100644 index 2cf998c..0000000 --- a/UnitySample/Assembly-CSharp.csproj +++ /dev/null @@ -1,91 +0,0 @@ - - - - Debug - AnyCPU - 10.0.20506 - 2.0 - - {8CA90CBA-908E-E48D-E4F6-89E98795426A} - Library - Properties - Assembly-CSharp - v3.5 - 512 - Assets - - - true - full - false - Temp\bin\Debug\ - DEBUG;TRACE;UNITY_5_3_OR_NEWER;UNITY_5_4_OR_NEWER;UNITY_5_5_OR_NEWER;UNITY_5_5_1;UNITY_5_5;UNITY_5;ENABLE_AUDIO;ENABLE_CACHING;ENABLE_CLOTH;ENABLE_DUCK_TYPING;ENABLE_GENERICS;ENABLE_MICROPHONE;ENABLE_MULTIPLE_DISPLAYS;ENABLE_PHYSICS;ENABLE_SPRITERENDERER_FLIPPING;ENABLE_SPRITES;ENABLE_TERRAIN;ENABLE_RAKNET;ENABLE_UNET;ENABLE_LZMA;ENABLE_UNITYEVENTS;ENABLE_WEBCAM;ENABLE_WWW;ENABLE_CLOUD_SERVICES_COLLAB;ENABLE_CLOUD_SERVICES_ADS;ENABLE_CLOUD_HUB;ENABLE_CLOUD_PROJECT_ID;ENABLE_CLOUD_SERVICES_UNET;ENABLE_CLOUD_SERVICES_BUILD;ENABLE_CLOUD_LICENSE;ENABLE_EDITOR_METRICS;ENABLE_EDITOR_METRICS_CACHING;INCLUDE_DYNAMIC_GI;INCLUDE_GI;PLATFORM_SUPPORTS_MONO;RENDER_SOFTWARE_CURSOR;INCLUDE_PUBNUB;ENABLE_PLAYMODE_TESTS_RUNNER;ENABLE_SCRIPTING_NEW_CSHARP_COMPILER;UNITY_STANDALONE_WIN;UNITY_STANDALONE;ENABLE_SUBSTANCE;ENABLE_RUNTIME_GI;ENABLE_MOVIES;ENABLE_NETWORK;ENABLE_CRUNCH_TEXTURE_COMPRESSION;ENABLE_UNITYWEBREQUEST;ENABLE_CLOUD_SERVICES;ENABLE_CLOUD_SERVICES_ANALYTICS;ENABLE_CLOUD_SERVICES_PURCHASING;ENABLE_CLOUD_SERVICES_CRASH_REPORTING;ENABLE_EVENT_QUEUE;ENABLE_CLUSTERINPUT;ENABLE_VIDEO;ENABLE_VR;ENABLE_WEBSOCKET_HOST;ENABLE_MONO;ENABLE_PROFILER;UNITY_ASSERTIONS;UNITY_EDITOR;UNITY_EDITOR_64;UNITY_EDITOR_WIN;UNITY_TEAM_LICENSE - prompt - 4 - 0169 - - - pdbonly - true - Temp\bin\Release\ - prompt - 4 - 0169 - - - - - - - - - C:/Program Files/Unity/Editor/Data/Managed/UnityEngine.dll - - - C:/Program Files/Unity/Editor/Data/Managed/UnityEditor.dll - - - - - - - - - - - - - - - - - - - C:/Program Files/Unity/Editor/Data/UnityExtensions/Unity/GUISystem/UnityEngine.UI.dll - - - C:/Program Files/Unity/Editor/Data/UnityExtensions/Unity/Networking/UnityEngine.Networking.dll - - - C:/Program Files/Unity/Editor/Data/UnityExtensions/Unity/PlaymodeTestsRunner/UnityEngine.PlaymodeTestsRunner.dll - - - C:/Program Files/Unity/Editor/Data/UnityExtensions/Unity/UnityAnalytics/UnityEngine.Analytics.dll - - - C:/Program Files/Unity/Editor/Data/UnityExtensions/Unity/UnityHoloLens/RuntimeEditor/UnityEngine.HoloLens.dll - - - C:/Program Files/Unity/Editor/Data/UnityExtensions/Unity/UnityVR/RuntimeEditor/UnityEngine.VR.dll - - - - - - diff --git a/UnitySample/Assets/AssetStoreTools/Editor/AssetStoreTools.dll b/UnitySample/Assets/AssetStoreTools/Editor/AssetStoreTools.dll deleted file mode 100644 index 3b58af6..0000000 Binary files a/UnitySample/Assets/AssetStoreTools/Editor/AssetStoreTools.dll and /dev/null differ diff --git a/UnitySample/Assets/AssetStoreTools/Editor/AssetStoreTools.dll.meta b/UnitySample/Assets/AssetStoreTools/Editor/AssetStoreTools.dll.meta deleted file mode 100644 index b47b9a7..0000000 --- a/UnitySample/Assets/AssetStoreTools/Editor/AssetStoreTools.dll.meta +++ /dev/null @@ -1,23 +0,0 @@ -fileFormatVersion: 2 -guid: f02b3fe0a866fca419671914a860554a -PluginImporter: - serializedVersion: 1 - iconMap: {} - executionOrder: {} - isPreloaded: 0 - isOverridable: 0 - platformData: - Any: - enabled: 0 - settings: {} - Editor: - enabled: 1 - settings: - DefaultValueInitialized: true - WindowsStoreApps: - enabled: 0 - settings: - CPU: AnyCPU - userData: - assetBundleName: - assetBundleVariant: diff --git a/UnitySample/Assets/AssetStoreTools/Editor/AssetStoreToolsExtra.dll b/UnitySample/Assets/AssetStoreTools/Editor/AssetStoreToolsExtra.dll deleted file mode 100644 index 6310640..0000000 Binary files a/UnitySample/Assets/AssetStoreTools/Editor/AssetStoreToolsExtra.dll and /dev/null differ diff --git a/UnitySample/Assets/AssetStoreTools/Editor/AssetStoreToolsExtra.dll.meta b/UnitySample/Assets/AssetStoreTools/Editor/AssetStoreToolsExtra.dll.meta deleted file mode 100644 index 3913b4c..0000000 --- a/UnitySample/Assets/AssetStoreTools/Editor/AssetStoreToolsExtra.dll.meta +++ /dev/null @@ -1,23 +0,0 @@ -fileFormatVersion: 2 -guid: 07e97bd03b7bdeb40bbc176326cd8d7a -PluginImporter: - serializedVersion: 1 - iconMap: {} - executionOrder: {} - isPreloaded: 0 - isOverridable: 0 - platformData: - Any: - enabled: 0 - settings: {} - Editor: - enabled: 1 - settings: - DefaultValueInitialized: true - WindowsStoreApps: - enabled: 0 - settings: - CPU: AnyCPU - userData: - assetBundleName: - assetBundleVariant: diff --git a/UnitySample/Assets/AssetStoreTools/Editor/DroidSansMono.ttf b/UnitySample/Assets/AssetStoreTools/Editor/DroidSansMono.ttf deleted file mode 100644 index 6e79dad..0000000 Binary files a/UnitySample/Assets/AssetStoreTools/Editor/DroidSansMono.ttf and /dev/null differ diff --git a/UnitySample/Assets/AssetStoreTools/Editor/DroidSansMono.ttf.meta b/UnitySample/Assets/AssetStoreTools/Editor/DroidSansMono.ttf.meta deleted file mode 100644 index f56ac09..0000000 --- a/UnitySample/Assets/AssetStoreTools/Editor/DroidSansMono.ttf.meta +++ /dev/null @@ -1,19 +0,0 @@ -fileFormatVersion: 2 -guid: 928f503de488e44408a8625d75d54c61 -TrueTypeFontImporter: - serializedVersion: 4 - fontSize: 16 - forceTextureCase: -2 - characterSpacing: 0 - characterPadding: 1 - includeFontData: 1 - fontName: Droid Sans Mono - fontNames: - - Droid Sans Mono - fallbackFontReferences: [] - customCharacters: - fontRenderingMode: 0 - ascentCalculationMode: 1 - userData: - assetBundleName: - assetBundleVariant: diff --git a/UnitySample/Assets/AssetStoreTools/Editor/icon.png b/UnitySample/Assets/AssetStoreTools/Editor/icon.png deleted file mode 100644 index 0269610..0000000 Binary files a/UnitySample/Assets/AssetStoreTools/Editor/icon.png and /dev/null differ diff --git a/UnitySample/Assets/AssetStoreTools/Editor/icon.png.meta b/UnitySample/Assets/AssetStoreTools/Editor/icon.png.meta deleted file mode 100644 index 47a83d1..0000000 --- a/UnitySample/Assets/AssetStoreTools/Editor/icon.png.meta +++ /dev/null @@ -1,66 +0,0 @@ -fileFormatVersion: 2 -guid: 3ef5b3d0acd79c3499f502f1b991678a -TextureImporter: - fileIDToRecycleName: {} - serializedVersion: 4 - mipmaps: - mipMapMode: 0 - enableMipMap: 1 - sRGBTexture: 1 - linearTexture: 0 - fadeOut: 0 - borderMipMap: 0 - mipMapFadeDistanceStart: 1 - mipMapFadeDistanceEnd: 3 - bumpmap: - convertToNormalMap: 0 - externalNormalMap: 0 - heightScale: 0.25 - normalMapFilter: 0 - isReadable: 0 - grayScaleToAlpha: 0 - generateCubemap: 6 - cubemapConvolution: 0 - seamlessCubemap: 0 - textureFormat: -1 - maxTextureSize: 1024 - textureSettings: - filterMode: -1 - aniso: -1 - mipBias: -1 - wrapMode: -1 - nPOTScale: 1 - lightmap: 0 - compressionQuality: 50 - spriteMode: 0 - spriteExtrude: 1 - spriteMeshType: 1 - alignment: 0 - spritePivot: {x: 0.5, y: 0.5} - spriteBorder: {x: 0, y: 0, z: 0, w: 0} - spritePixelsToUnits: 100 - alphaUsage: 1 - alphaIsTransparency: 0 - spriteTessellationDetail: -1 - textureType: 0 - textureShape: 1 - maxTextureSizeSet: 0 - compressionQualitySet: 0 - textureFormatSet: 0 - platformSettings: - - buildTarget: DefaultTexturePlatform - maxTextureSize: 1024 - textureFormat: -1 - textureCompression: 1 - compressionQuality: 50 - crunchedCompression: 0 - allowsAlphaSplitting: 0 - overridden: 0 - spriteSheet: - serializedVersion: 2 - sprites: [] - outline: [] - spritePackingTag: - userData: - assetBundleName: - assetBundleVariant: diff --git a/UnitySample/Assets/Plugins/x86/UnityWebcam.dll b/UnitySample/Assets/Plugins/x86/UnityWebcam.dll deleted file mode 100644 index 81301aa..0000000 Binary files a/UnitySample/Assets/Plugins/x86/UnityWebcam.dll and /dev/null differ diff --git a/UnitySample/Assets/Plugins/x86/UnityWebcam.dll.meta b/UnitySample/Assets/Plugins/x86/UnityWebcam.dll.meta deleted file mode 100644 index 645954e..0000000 --- a/UnitySample/Assets/Plugins/x86/UnityWebcam.dll.meta +++ /dev/null @@ -1,54 +0,0 @@ -fileFormatVersion: 2 -guid: 5dfe342e81d6f834ab0fcf36e32bf0e1 -timeCreated: 1460543009 -licenseType: Free -PluginImporter: - serializedVersion: 1 - iconMap: {} - executionOrder: {} - isPreloaded: 0 - isOverridable: 0 - platformData: - Any: - enabled: 1 - settings: {} - Editor: - enabled: 0 - settings: - CPU: x86 - DefaultValueInitialized: true - Linux: - enabled: 1 - settings: - CPU: x86 - Linux64: - enabled: 0 - settings: - CPU: None - LinuxUniversal: - enabled: 1 - settings: - CPU: x86 - OSXIntel: - enabled: 1 - settings: - CPU: AnyCPU - OSXIntel64: - enabled: 0 - settings: - CPU: None - OSXUniversal: - enabled: 0 - settings: - CPU: x86 - Win: - enabled: 1 - settings: - CPU: AnyCPU - Win64: - enabled: 0 - settings: - CPU: None - userData: - assetBundleName: - assetBundleVariant: diff --git a/UnitySample/Assets/Plugins/x86_64/UnityWebcam.dll b/UnitySample/Assets/Plugins/x86_64/UnityWebcam.dll deleted file mode 100644 index 218eb2b..0000000 Binary files a/UnitySample/Assets/Plugins/x86_64/UnityWebcam.dll and /dev/null differ diff --git a/UnitySample/Assets/Plugins/x86_64/UnityWebcam.dll.meta b/UnitySample/Assets/Plugins/x86_64/UnityWebcam.dll.meta deleted file mode 100644 index 51118ca..0000000 --- a/UnitySample/Assets/Plugins/x86_64/UnityWebcam.dll.meta +++ /dev/null @@ -1,54 +0,0 @@ -fileFormatVersion: 2 -guid: a01ad84b3f2ea09488282d1823c27ce3 -timeCreated: 1461074627 -licenseType: Free -PluginImporter: - serializedVersion: 1 - iconMap: {} - executionOrder: {} - isPreloaded: 0 - isOverridable: 0 - platformData: - Any: - enabled: 1 - settings: {} - Editor: - enabled: 0 - settings: - CPU: x86_64 - DefaultValueInitialized: true - Linux: - enabled: 0 - settings: - CPU: None - Linux64: - enabled: 1 - settings: - CPU: x86_64 - LinuxUniversal: - enabled: 1 - settings: - CPU: x86_64 - OSXIntel: - enabled: 0 - settings: - CPU: None - OSXIntel64: - enabled: 1 - settings: - CPU: AnyCPU - OSXUniversal: - enabled: 0 - settings: - CPU: x86_64 - Win: - enabled: 0 - settings: - CPU: None - Win64: - enabled: 1 - settings: - CPU: AnyCPU - userData: - assetBundleName: - assetBundleVariant: diff --git a/UnitySample/Assets/UnityCam.meta b/UnitySample/Assets/UnityCam.meta deleted file mode 100644 index c1b4617..0000000 --- a/UnitySample/Assets/UnityCam.meta +++ /dev/null @@ -1,9 +0,0 @@ -fileFormatVersion: 2 -guid: 11bc0272cf6b30c409e55356b2a31f74 -folderAsset: yes -timeCreated: 1464330761 -licenseType: Free -DefaultImporter: - userData: - assetBundleName: - assetBundleVariant: diff --git a/UnitySample/Assets/UnityCam/Editor.meta b/UnitySample/Assets/UnityCam/Editor.meta deleted file mode 100644 index 27845d3..0000000 --- a/UnitySample/Assets/UnityCam/Editor.meta +++ /dev/null @@ -1,9 +0,0 @@ -fileFormatVersion: 2 -guid: 71524bf0a7afefe4995b59d487b2f1b0 -folderAsset: yes -timeCreated: 1463485971 -licenseType: Free -DefaultImporter: - userData: - assetBundleName: - assetBundleVariant: diff --git a/UnitySample/Assets/UnityCam/Editor/UnityCamEditor.cs b/UnitySample/Assets/UnityCam/Editor/UnityCamEditor.cs deleted file mode 100644 index 14c288a..0000000 --- a/UnitySample/Assets/UnityCam/Editor/UnityCamEditor.cs +++ /dev/null @@ -1,26 +0,0 @@ -using UnityEngine; -using System.Collections; -using UnityEditor; - -[CustomEditor(typeof(UnityCam))] -public class HUGVRCamEditor : Editor -{ - - SerializedProperty _flipImage; - SerializedProperty _blitLocaly; - void OnEnable() - { - _flipImage=serializedObject.FindProperty("Flip"); - _blitLocaly=serializedObject.FindProperty("BlitLocaly"); - } - - - public override void OnInspectorGUI() - { - serializedObject.Update(); - EditorGUILayout.PropertyField(_flipImage); - EditorGUILayout.PropertyField(_blitLocaly); - - serializedObject.ApplyModifiedProperties(); - } -} diff --git a/UnitySample/Assets/UnityCam/Example.meta b/UnitySample/Assets/UnityCam/Example.meta deleted file mode 100644 index 4e989b7..0000000 --- a/UnitySample/Assets/UnityCam/Example.meta +++ /dev/null @@ -1,9 +0,0 @@ -fileFormatVersion: 2 -guid: d30e3bb44b753ec46b992d5227228b87 -folderAsset: yes -timeCreated: 1461153190 -licenseType: Free -DefaultImporter: - userData: - assetBundleName: - assetBundleVariant: diff --git a/UnitySample/Assets/UnityCam/Example/CubesScene.unity b/UnitySample/Assets/UnityCam/Example/CubesScene.unity deleted file mode 100644 index 250f2ba..0000000 Binary files a/UnitySample/Assets/UnityCam/Example/CubesScene.unity and /dev/null differ diff --git a/UnitySample/Assets/UnityCam/Example/Resources.meta b/UnitySample/Assets/UnityCam/Example/Resources.meta deleted file mode 100644 index d6f0a38..0000000 --- a/UnitySample/Assets/UnityCam/Example/Resources.meta +++ /dev/null @@ -1,9 +0,0 @@ -fileFormatVersion: 2 -guid: 430868f81c19643439a91fb9a4f7cca9 -folderAsset: yes -timeCreated: 1463487675 -licenseType: Free -DefaultImporter: - userData: - assetBundleName: - assetBundleVariant: diff --git a/UnitySample/Assets/UnityCam/Example/Resources/MotionBlur.shader b/UnitySample/Assets/UnityCam/Example/Resources/MotionBlur.shader deleted file mode 100644 index e00e988..0000000 --- a/UnitySample/Assets/UnityCam/Example/Resources/MotionBlur.shader +++ /dev/null @@ -1,120 +0,0 @@ -Shader "Hidden/MotionBlur" { -Properties { - _MainTex ("Base (RGB)", 2D) = "white" {} - _AccumOrig("AccumOrig", Float) = 0.65 -} - - SubShader { - ZTest Always Cull Off ZWrite Off - Pass { - Blend SrcAlpha OneMinusSrcAlpha - ColorMask RGB - BindChannels { - Bind "vertex", vertex - Bind "texcoord", texcoord - } - - CGPROGRAM - #pragma vertex vert - #pragma fragment frag - - #include "UnityCG.cginc" - - struct appdata_t { - float4 vertex : POSITION; - float2 texcoord : TEXCOORD; - }; - - struct v2f { - float4 vertex : SV_POSITION; - float2 texcoord : TEXCOORD; - }; - - float4 _MainTex_ST; - float _AccumOrig; - - v2f vert (appdata_t v) - { - v2f o; - o.vertex = mul(UNITY_MATRIX_MVP, v.vertex); - o.texcoord = TRANSFORM_TEX(v.texcoord, _MainTex); - return o; - } - - sampler2D _MainTex; - - half4 frag (v2f i) : SV_Target - { - return half4(tex2D(_MainTex, i.texcoord).rgb, _AccumOrig ); - } - ENDCG - } - - Pass { - Blend One Zero - ColorMask A - - BindChannels { - Bind "vertex", vertex - Bind "texcoord", texcoord - } - - CGPROGRAM - #pragma vertex vert - #pragma fragment frag - - #include "UnityCG.cginc" - - struct appdata_t { - float4 vertex : POSITION; - float2 texcoord : TEXCOORD; - }; - - struct v2f { - float4 vertex : SV_POSITION; - float2 texcoord : TEXCOORD; - }; - - float4 _MainTex_ST; - - v2f vert (appdata_t v) - { - v2f o; - o.vertex = mul(UNITY_MATRIX_MVP, v.vertex); - o.texcoord = TRANSFORM_TEX(v.texcoord, _MainTex); - return o; - } - - sampler2D _MainTex; - - half4 frag (v2f i) : SV_Target - { - return tex2D(_MainTex, i.texcoord); - } - ENDCG - } - - } - -SubShader { - ZTest Always Cull Off ZWrite Off - Pass { - Blend SrcAlpha OneMinusSrcAlpha - ColorMask RGB - SetTexture [_MainTex] { - ConstantColor (0,0,0,[_AccumOrig]) - Combine texture, constant - } - } - Pass { - Blend One Zero - ColorMask A - SetTexture [_MainTex] { - Combine texture - } - } -} - -Fallback off - -} diff --git a/UnitySample/Assets/UnityCam/Example/Resources/MotionBlur.shader.meta b/UnitySample/Assets/UnityCam/Example/Resources/MotionBlur.shader.meta deleted file mode 100644 index 3b72a30..0000000 --- a/UnitySample/Assets/UnityCam/Example/Resources/MotionBlur.shader.meta +++ /dev/null @@ -1,9 +0,0 @@ -fileFormatVersion: 2 -guid: d3616e8270cb31a48a0b58247a2135ec -timeCreated: 1463487676 -licenseType: Free -ShaderImporter: - defaultTextures: [] - userData: - assetBundleName: - assetBundleVariant: diff --git a/UnitySample/Assets/UnityCam/Example/Scripts.meta b/UnitySample/Assets/UnityCam/Example/Scripts.meta deleted file mode 100644 index d4049d2..0000000 --- a/UnitySample/Assets/UnityCam/Example/Scripts.meta +++ /dev/null @@ -1,9 +0,0 @@ -fileFormatVersion: 2 -guid: 4feb8952c8397084d95ea3124ceb8053 -folderAsset: yes -timeCreated: 1461154325 -licenseType: Free -DefaultImporter: - userData: - assetBundleName: - assetBundleVariant: diff --git a/UnitySample/Assets/UnityCam/Example/Scripts/Bloom.cs b/UnitySample/Assets/UnityCam/Example/Scripts/Bloom.cs deleted file mode 100644 index d5fd7a6..0000000 --- a/UnitySample/Assets/UnityCam/Example/Scripts/Bloom.cs +++ /dev/null @@ -1,358 +0,0 @@ -using System; -using UnityEngine; - -namespace UnityStandardAssets.ImageEffects -{ - [ExecuteInEditMode] - [RequireComponent (typeof(Camera))] - [AddComponentMenu ("Image Effects/Bloom and Glow/Bloom")] - public class Bloom : PostEffectsBase - { - public enum LensFlareStyle - { - Ghosting = 0, - Anamorphic = 1, - Combined = 2, - } - - public enum TweakMode - { - Basic = 0, - Complex = 1, - } - - public enum HDRBloomMode - { - Auto = 0, - On = 1, - Off = 2, - } - - public enum BloomScreenBlendMode - { - Screen = 0, - Add = 1, - } - - public enum BloomQuality - { - Cheap = 0, - High = 1, - } - - public TweakMode tweakMode = 0; - public BloomScreenBlendMode screenBlendMode = BloomScreenBlendMode.Add; - - public HDRBloomMode hdr = HDRBloomMode.Auto; - private bool doHdr = false; - public float sepBlurSpread = 2.5f; - - public BloomQuality quality = BloomQuality.High; - - public float bloomIntensity = 0.5f; - public float bloomThreshold = 0.5f; - public Color bloomThresholdColor = Color.white; - public int bloomBlurIterations = 2; - - public int hollywoodFlareBlurIterations = 2; - public float flareRotation = 0.0f; - public LensFlareStyle lensflareMode = (LensFlareStyle) 1; - public float hollyStretchWidth = 2.5f; - public float lensflareIntensity = 0.0f; - public float lensflareThreshold = 0.3f; - public float lensFlareSaturation = 0.75f; - public Color flareColorA = new Color (0.4f, 0.4f, 0.8f, 0.75f); - public Color flareColorB = new Color (0.4f, 0.8f, 0.8f, 0.75f); - public Color flareColorC = new Color (0.8f, 0.4f, 0.8f, 0.75f); - public Color flareColorD = new Color (0.8f, 0.4f, 0.0f, 0.75f); - public Texture2D lensFlareVignetteMask; - - public Shader lensFlareShader; - private Material lensFlareMaterial; - - public Shader screenBlendShader; - private Material screenBlend; - - public Shader blurAndFlaresShader; - private Material blurAndFlaresMaterial; - - public Shader brightPassFilterShader; - private Material brightPassFilterMaterial; - - - public override bool CheckResources () - { - CheckSupport (false); - - screenBlend = CheckShaderAndCreateMaterial (screenBlendShader, screenBlend); - lensFlareMaterial = CheckShaderAndCreateMaterial(lensFlareShader,lensFlareMaterial); - blurAndFlaresMaterial = CheckShaderAndCreateMaterial (blurAndFlaresShader, blurAndFlaresMaterial); - brightPassFilterMaterial = CheckShaderAndCreateMaterial(brightPassFilterShader, brightPassFilterMaterial); - - if (!isSupported) - ReportAutoDisable (); - return isSupported; - } - - public void OnRenderImage (RenderTexture source, RenderTexture destination) - { - if (CheckResources()==false) - { - Graphics.Blit (source, destination); - return; - } - - // screen blend is not supported when HDR is enabled (will cap values) - - doHdr = false; - if (hdr == HDRBloomMode.Auto) - doHdr = source.format == RenderTextureFormat.ARGBHalf && GetComponent().hdr; - else { - doHdr = hdr == HDRBloomMode.On; - } - - doHdr = doHdr && supportHDRTextures; - - BloomScreenBlendMode realBlendMode = screenBlendMode; - if (doHdr) - realBlendMode = BloomScreenBlendMode.Add; - - var rtFormat= (doHdr) ? RenderTextureFormat.ARGBHalf : RenderTextureFormat.Default; - var rtW2= source.width/2; - var rtH2= source.height/2; - var rtW4= source.width/4; - var rtH4= source.height/4; - - float widthOverHeight = (1.0f * source.width) / (1.0f * source.height); - float oneOverBaseSize = 1.0f / 512.0f; - - // downsample - RenderTexture quarterRezColor = RenderTexture.GetTemporary (rtW4, rtH4, 0, rtFormat); - RenderTexture halfRezColorDown = RenderTexture.GetTemporary (rtW2, rtH2, 0, rtFormat); - if (quality > BloomQuality.Cheap) { - Graphics.Blit (source, halfRezColorDown, screenBlend, 2); - RenderTexture rtDown4 = RenderTexture.GetTemporary (rtW4, rtH4, 0, rtFormat); - Graphics.Blit (halfRezColorDown, rtDown4, screenBlend, 2); - Graphics.Blit (rtDown4, quarterRezColor, screenBlend, 6); - RenderTexture.ReleaseTemporary(rtDown4); - } - else { - Graphics.Blit (source, halfRezColorDown); - Graphics.Blit (halfRezColorDown, quarterRezColor, screenBlend, 6); - } - RenderTexture.ReleaseTemporary (halfRezColorDown); - - // cut colors (thresholding) - RenderTexture secondQuarterRezColor = RenderTexture.GetTemporary (rtW4, rtH4, 0, rtFormat); - BrightFilter (bloomThreshold * bloomThresholdColor, quarterRezColor, secondQuarterRezColor); - - // blurring - - if (bloomBlurIterations < 1) bloomBlurIterations = 1; - else if (bloomBlurIterations > 10) bloomBlurIterations = 10; - - for (int iter = 0; iter < bloomBlurIterations; iter++) - { - float spreadForPass = (1.0f + (iter * 0.25f)) * sepBlurSpread; - - // vertical blur - RenderTexture blur4 = RenderTexture.GetTemporary (rtW4, rtH4, 0, rtFormat); - blurAndFlaresMaterial.SetVector ("_Offsets", new Vector4 (0.0f, spreadForPass * oneOverBaseSize, 0.0f, 0.0f)); - Graphics.Blit (secondQuarterRezColor, blur4, blurAndFlaresMaterial, 4); - RenderTexture.ReleaseTemporary(secondQuarterRezColor); - secondQuarterRezColor = blur4; - - // horizontal blur - blur4 = RenderTexture.GetTemporary (rtW4, rtH4, 0, rtFormat); - blurAndFlaresMaterial.SetVector ("_Offsets", new Vector4 ((spreadForPass / widthOverHeight) * oneOverBaseSize, 0.0f, 0.0f, 0.0f)); - Graphics.Blit (secondQuarterRezColor, blur4, blurAndFlaresMaterial, 4); - RenderTexture.ReleaseTemporary (secondQuarterRezColor); - secondQuarterRezColor = blur4; - - if (quality > BloomQuality.Cheap) - { - if (iter == 0) - { - Graphics.SetRenderTarget(quarterRezColor); - GL.Clear(false, true, Color.black); // Clear to avoid RT restore - Graphics.Blit (secondQuarterRezColor, quarterRezColor); - } - else - { - quarterRezColor.MarkRestoreExpected(); // using max blending, RT restore expected - Graphics.Blit (secondQuarterRezColor, quarterRezColor, screenBlend, 10); - } - } - } - - if (quality > BloomQuality.Cheap) - { - Graphics.SetRenderTarget(secondQuarterRezColor); - GL.Clear(false, true, Color.black); // Clear to avoid RT restore - Graphics.Blit (quarterRezColor, secondQuarterRezColor, screenBlend, 6); - } - - // lens flares: ghosting, anamorphic or both (ghosted anamorphic flares) - - if (lensflareIntensity > Mathf.Epsilon) - { - - RenderTexture rtFlares4 = RenderTexture.GetTemporary (rtW4, rtH4, 0, rtFormat); - - if (lensflareMode == 0) - { - // ghosting only - - BrightFilter (lensflareThreshold, secondQuarterRezColor, rtFlares4); - - if (quality > BloomQuality.Cheap) - { - // smooth a little - blurAndFlaresMaterial.SetVector ("_Offsets", new Vector4 (0.0f, (1.5f) / (1.0f * quarterRezColor.height), 0.0f, 0.0f)); - Graphics.SetRenderTarget(quarterRezColor); - GL.Clear(false, true, Color.black); // Clear to avoid RT restore - Graphics.Blit (rtFlares4, quarterRezColor, blurAndFlaresMaterial, 4); - - blurAndFlaresMaterial.SetVector ("_Offsets", new Vector4 ((1.5f) / (1.0f * quarterRezColor.width), 0.0f, 0.0f, 0.0f)); - Graphics.SetRenderTarget(rtFlares4); - GL.Clear(false, true, Color.black); // Clear to avoid RT restore - Graphics.Blit (quarterRezColor, rtFlares4, blurAndFlaresMaterial, 4); - } - - // no ugly edges! - Vignette (0.975f, rtFlares4, rtFlares4); - BlendFlares (rtFlares4, secondQuarterRezColor); - } - else - { - - //Vignette (0.975ff, rtFlares4, rtFlares4); - //DrawBorder(rtFlares4, screenBlend, 8); - - float flareXRot = 1.0f * Mathf.Cos(flareRotation); - float flareyRot = 1.0f * Mathf.Sin(flareRotation); - - float stretchWidth = (hollyStretchWidth * 1.0f / widthOverHeight) * oneOverBaseSize; - - blurAndFlaresMaterial.SetVector ("_Offsets", new Vector4 (flareXRot, flareyRot, 0.0f, 0.0f)); - blurAndFlaresMaterial.SetVector ("_Threshhold", new Vector4 (lensflareThreshold, 1.0f, 0.0f, 0.0f)); - blurAndFlaresMaterial.SetVector ("_TintColor", new Vector4 (flareColorA.r, flareColorA.g, flareColorA.b, flareColorA.a) * flareColorA.a * lensflareIntensity); - blurAndFlaresMaterial.SetFloat ("_Saturation", lensFlareSaturation); - - // "pre and cut" - quarterRezColor.DiscardContents(); - Graphics.Blit (rtFlares4, quarterRezColor, blurAndFlaresMaterial, 2); - // "post" - rtFlares4.DiscardContents(); - Graphics.Blit (quarterRezColor, rtFlares4, blurAndFlaresMaterial, 3); - - blurAndFlaresMaterial.SetVector ("_Offsets", new Vector4 (flareXRot * stretchWidth, flareyRot * stretchWidth, 0.0f, 0.0f)); - // stretch 1st - blurAndFlaresMaterial.SetFloat ("_StretchWidth", hollyStretchWidth); - quarterRezColor.DiscardContents(); - Graphics.Blit (rtFlares4, quarterRezColor, blurAndFlaresMaterial, 1); - // stretch 2nd - blurAndFlaresMaterial.SetFloat ("_StretchWidth", hollyStretchWidth * 2.0f); - rtFlares4.DiscardContents(); - Graphics.Blit (quarterRezColor, rtFlares4, blurAndFlaresMaterial, 1); - // stretch 3rd - blurAndFlaresMaterial.SetFloat ("_StretchWidth", hollyStretchWidth * 4.0f); - quarterRezColor.DiscardContents(); - Graphics.Blit (rtFlares4, quarterRezColor, blurAndFlaresMaterial, 1); - - // additional blur passes - for (int iter = 0; iter < hollywoodFlareBlurIterations; iter++) - { - stretchWidth = (hollyStretchWidth * 2.0f / widthOverHeight) * oneOverBaseSize; - - blurAndFlaresMaterial.SetVector ("_Offsets", new Vector4 (stretchWidth * flareXRot, stretchWidth * flareyRot, 0.0f, 0.0f)); - rtFlares4.DiscardContents(); - Graphics.Blit (quarterRezColor, rtFlares4, blurAndFlaresMaterial, 4); - - blurAndFlaresMaterial.SetVector ("_Offsets", new Vector4 (stretchWidth * flareXRot, stretchWidth * flareyRot, 0.0f, 0.0f)); - quarterRezColor.DiscardContents(); - Graphics.Blit (rtFlares4, quarterRezColor, blurAndFlaresMaterial, 4); - } - - if (lensflareMode == (LensFlareStyle) 1) - // anamorphic lens flares - AddTo (1.0f, quarterRezColor, secondQuarterRezColor); - else - { - // "combined" lens flares - - Vignette (1.0f, quarterRezColor, rtFlares4); - BlendFlares (rtFlares4, quarterRezColor); - AddTo (1.0f, quarterRezColor, secondQuarterRezColor); - } - } - RenderTexture.ReleaseTemporary (rtFlares4); - } - - int blendPass = (int) realBlendMode; - //if (Mathf.Abs(chromaticBloom) < Mathf.Epsilon) - // blendPass += 4; - - screenBlend.SetFloat ("_Intensity", bloomIntensity); - screenBlend.SetTexture ("_ColorBuffer", source); - - if (quality > BloomQuality.Cheap) - { - RenderTexture halfRezColorUp = RenderTexture.GetTemporary (rtW2, rtH2, 0, rtFormat); - Graphics.Blit (secondQuarterRezColor, halfRezColorUp); - Graphics.Blit (halfRezColorUp, destination, screenBlend, blendPass); - RenderTexture.ReleaseTemporary (halfRezColorUp); - } - else - Graphics.Blit (secondQuarterRezColor, destination, screenBlend, blendPass); - - RenderTexture.ReleaseTemporary (quarterRezColor); - RenderTexture.ReleaseTemporary (secondQuarterRezColor); - } - - private void AddTo (float intensity_, RenderTexture from, RenderTexture to) - { - screenBlend.SetFloat ("_Intensity", intensity_); - to.MarkRestoreExpected(); // additive blending, RT restore expected - Graphics.Blit (from, to, screenBlend, 9); - } - - private void BlendFlares (RenderTexture from, RenderTexture to) - { - lensFlareMaterial.SetVector ("colorA", new Vector4 (flareColorA.r, flareColorA.g, flareColorA.b, flareColorA.a) * lensflareIntensity); - lensFlareMaterial.SetVector ("colorB", new Vector4 (flareColorB.r, flareColorB.g, flareColorB.b, flareColorB.a) * lensflareIntensity); - lensFlareMaterial.SetVector ("colorC", new Vector4 (flareColorC.r, flareColorC.g, flareColorC.b, flareColorC.a) * lensflareIntensity); - lensFlareMaterial.SetVector ("colorD", new Vector4 (flareColorD.r, flareColorD.g, flareColorD.b, flareColorD.a) * lensflareIntensity); - to.MarkRestoreExpected(); // additive blending, RT restore expected - Graphics.Blit (from, to, lensFlareMaterial); - } - - private void BrightFilter (float thresh, RenderTexture from, RenderTexture to) - { - brightPassFilterMaterial.SetVector ("_Threshhold", new Vector4 (thresh, thresh, thresh, thresh)); - Graphics.Blit (from, to, brightPassFilterMaterial, 0); - } - - private void BrightFilter (Color threshColor, RenderTexture from, RenderTexture to) - { - brightPassFilterMaterial.SetVector ("_Threshhold", threshColor); - Graphics.Blit (from, to, brightPassFilterMaterial, 1); - } - - private void Vignette (float amount, RenderTexture from, RenderTexture to) - { - if (lensFlareVignetteMask) - { - screenBlend.SetTexture ("_ColorBuffer", lensFlareVignetteMask); - to.MarkRestoreExpected(); // using blending, RT restore expected - Graphics.Blit (from == to ? null : from, to, screenBlend, from == to ? 7 : 3); - } - else if (from != to) - { - Graphics.SetRenderTarget (to); - GL.Clear(false, true, Color.black); // clear destination to avoid RT restore - Graphics.Blit (from, to); - } - } - } -} diff --git a/UnitySample/Assets/UnityCam/Example/Scripts/CubeGenerator.cs b/UnitySample/Assets/UnityCam/Example/Scripts/CubeGenerator.cs deleted file mode 100644 index 6fc849d..0000000 --- a/UnitySample/Assets/UnityCam/Example/Scripts/CubeGenerator.cs +++ /dev/null @@ -1,27 +0,0 @@ -using UnityEngine; -using System.Collections; - -public class CubeGenerator : MonoBehaviour { - - public int Count=10; - - // Use this for initialization - void Start () { - for(int i=0;i (); - } - } - - // Update is called once per frame - void Update () { - - } -} diff --git a/UnitySample/Assets/UnityCam/Example/Scripts/CubeGenerator.cs.meta b/UnitySample/Assets/UnityCam/Example/Scripts/CubeGenerator.cs.meta deleted file mode 100644 index ff5f766..0000000 --- a/UnitySample/Assets/UnityCam/Example/Scripts/CubeGenerator.cs.meta +++ /dev/null @@ -1,12 +0,0 @@ -fileFormatVersion: 2 -guid: 2cd15ebaafd5aff498ea4803c2c745fb -timeCreated: 1461153201 -licenseType: Free -MonoImporter: - serializedVersion: 2 - defaultReferences: [] - executionOrder: 0 - icon: {instanceID: 0} - userData: - assetBundleName: - assetBundleVariant: diff --git a/UnitySample/Assets/UnityCam/Example/Scripts/ImageEffectBase.cs b/UnitySample/Assets/UnityCam/Example/Scripts/ImageEffectBase.cs deleted file mode 100644 index 0158215..0000000 --- a/UnitySample/Assets/UnityCam/Example/Scripts/ImageEffectBase.cs +++ /dev/null @@ -1,55 +0,0 @@ -using System; -using UnityEngine; - -namespace UnityStandardAssets.ImageEffects -{ - [RequireComponent(typeof (Camera))] - [AddComponentMenu("")] - public class ImageEffectBase : MonoBehaviour - { - /// Provides a shader property that is set in the inspector - /// and a material instantiated from the shader - public Shader shader; - - private Material m_Material; - - - protected virtual void Start() - { - // Disable if we don't support image effects - if (!SystemInfo.supportsImageEffects) - { - enabled = false; - return; - } - - // Disable the image effect if the shader can't - // run on the users graphics card - if (!shader || !shader.isSupported) - enabled = false; - } - - - protected Material material - { - get - { - if (m_Material == null) - { - m_Material = new Material(shader); - m_Material.hideFlags = HideFlags.HideAndDontSave; - } - return m_Material; - } - } - - - protected virtual void OnDisable() - { - if (m_Material) - { - DestroyImmediate(m_Material); - } - } - } -} diff --git a/UnitySample/Assets/UnityCam/Example/Scripts/ImageEffectBase.cs.meta b/UnitySample/Assets/UnityCam/Example/Scripts/ImageEffectBase.cs.meta deleted file mode 100644 index 9d7b882..0000000 --- a/UnitySample/Assets/UnityCam/Example/Scripts/ImageEffectBase.cs.meta +++ /dev/null @@ -1,12 +0,0 @@ -fileFormatVersion: 2 -guid: 92f4c664a8d71d74987de89f94cb8cf3 -timeCreated: 1463487751 -licenseType: Free -MonoImporter: - serializedVersion: 2 - defaultReferences: [] - executionOrder: 0 - icon: {instanceID: 0} - userData: - assetBundleName: - assetBundleVariant: diff --git a/UnitySample/Assets/UnityCam/Example/Scripts/JitterMotion.cs b/UnitySample/Assets/UnityCam/Example/Scripts/JitterMotion.cs deleted file mode 100644 index d680a8f..0000000 --- a/UnitySample/Assets/UnityCam/Example/Scripts/JitterMotion.cs +++ /dev/null @@ -1,108 +0,0 @@ -// -// Reaktion - An audio reactive animation toolkit for Unity. -// -// Copyright (C) 2013, 2014 Keijiro Takahashi -// -// 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. -// -using UnityEngine; - -namespace Reaktion { - -public class JitterMotion : MonoBehaviour -{ - public float positionFrequency = 0.2f; - public float rotationFrequency = 0.2f; - - public float positionAmount = 1.0f; - public float rotationAmount = 30.0f; - - public Vector3 positionComponents = Vector3.one; - public Vector3 rotationComponents = new Vector3(1, 1, 0); - - public int positionOctave = 3; - public int rotationOctave = 3; - - float timePosition; - float timeRotation; - - Vector2[] noiseVectors; - - Vector3 initialPosition; - Quaternion initialRotation; - - void Awake() - { - timePosition = Random.value * 10; - timeRotation = Random.value * 10; - - noiseVectors = new Vector2[6]; - - for (var i = 0; i < 6; i++) - { - var theta = Random.value * Mathf.PI * 2; - noiseVectors[i].Set(Mathf.Cos(theta), Mathf.Sin(theta)); - } - - initialPosition = transform.localPosition; - initialRotation = transform.localRotation; - } - - void Update() - { - timePosition += Time.deltaTime * positionFrequency; - timeRotation += Time.deltaTime * rotationFrequency; - - if (positionAmount != 0.0f) - { - var p = new Vector3( - Fbm(noiseVectors[0] * timePosition, positionOctave), - Fbm(noiseVectors[1] * timePosition, positionOctave), - Fbm(noiseVectors[2] * timePosition, positionOctave) - ); - p = Vector3.Scale(p, positionComponents) * positionAmount * 2; - transform.localPosition = initialPosition + p; - } - - if (rotationAmount != 0.0f) - { - var r = new Vector3( - Fbm(noiseVectors[3] * timeRotation, rotationOctave), - Fbm(noiseVectors[4] * timeRotation, rotationOctave), - Fbm(noiseVectors[5] * timeRotation, rotationOctave) - ); - r = Vector3.Scale(r, rotationComponents) * rotationAmount * 2; - transform.localRotation = Quaternion.Euler(r) * initialRotation; - } - } - - static float Fbm(Vector2 coord, int octave) - { - var f = 0.0f; - var w = 1.0f; - for (var i = 0; i < octave; i++) - { - f += w * Perlin.Noise(coord.x, coord.y) * 0.5f; - coord *= 2; - w *= 0.5f; - } - return f; - } -} - -} // namespace Reaktion diff --git a/UnitySample/Assets/UnityCam/Example/Scripts/MotionBlur.cs b/UnitySample/Assets/UnityCam/Example/Scripts/MotionBlur.cs deleted file mode 100644 index 3914868..0000000 --- a/UnitySample/Assets/UnityCam/Example/Scripts/MotionBlur.cs +++ /dev/null @@ -1,76 +0,0 @@ -using System; -using UnityEngine; - -// This class implements simple ghosting type Motion Blur. -// If Extra Blur is selected, the scene will allways be a little blurred, -// as it is scaled to a smaller resolution. -// The effect works by accumulating the previous frames in an accumulation -// texture. -namespace UnityStandardAssets.ImageEffects -{ - [ExecuteInEditMode] - [AddComponentMenu("Image Effects/Blur/Motion Blur (Color Accumulation)")] - [RequireComponent(typeof(Camera))] - public class MotionBlur : ImageEffectBase - { - [Range(0.0f, 0.92f)] - public float blurAmount = 0.8f; - public bool extraBlur = false; - - private RenderTexture accumTexture; - - override protected void Start() - { - if (!SystemInfo.supportsRenderTextures) - { - enabled = false; - return; - } - base.Start(); - } - - override protected void OnDisable() - { - base.OnDisable(); - DestroyImmediate(accumTexture); - } - - // Called by camera to apply image effect - void OnRenderImage (RenderTexture source, RenderTexture destination) - { - // Create the accumulation texture - if (accumTexture == null || accumTexture.width != source.width || accumTexture.height != source.height) - { - DestroyImmediate(accumTexture); - accumTexture = new RenderTexture(source.width, source.height, 0); - accumTexture.hideFlags = HideFlags.HideAndDontSave; - Graphics.Blit( source, accumTexture ); - } - - // If Extra Blur is selected, downscale the texture to 4x4 smaller resolution. - if (extraBlur) - { - RenderTexture blurbuffer = RenderTexture.GetTemporary(source.width/4, source.height/4, 0); - accumTexture.MarkRestoreExpected(); - Graphics.Blit(accumTexture, blurbuffer); - Graphics.Blit(blurbuffer,accumTexture); - RenderTexture.ReleaseTemporary(blurbuffer); - } - - // Clamp the motion blur variable, so it can never leave permanent trails in the image - blurAmount = Mathf.Clamp( blurAmount, 0.0f, 0.92f ); - - // Setup the texture and floating point values in the shader - material.SetTexture("_MainTex", accumTexture); - material.SetFloat("_AccumOrig", 1.0F-blurAmount); - - // We are accumulating motion over frames without clear/discard - // by design, so silence any performance warnings from Unity - accumTexture.MarkRestoreExpected(); - - // Render the image using the motion blur shader - Graphics.Blit (source, accumTexture, material); - Graphics.Blit (accumTexture, destination); - } - } -} diff --git a/UnitySample/Assets/UnityCam/Example/Scripts/MotionBlur.cs.meta b/UnitySample/Assets/UnityCam/Example/Scripts/MotionBlur.cs.meta deleted file mode 100644 index 529cc57..0000000 --- a/UnitySample/Assets/UnityCam/Example/Scripts/MotionBlur.cs.meta +++ /dev/null @@ -1,12 +0,0 @@ -fileFormatVersion: 2 -guid: 89c052e18f3d04e4f94e08044286f3b9 -timeCreated: 1463487675 -licenseType: Free -MonoImporter: - serializedVersion: 2 - defaultReferences: [] - executionOrder: 0 - icon: {instanceID: 0} - userData: - assetBundleName: - assetBundleVariant: diff --git a/UnitySample/Assets/UnityCam/Example/Scripts/ObjectMotion.cs b/UnitySample/Assets/UnityCam/Example/Scripts/ObjectMotion.cs deleted file mode 100644 index 46f4b7d..0000000 --- a/UnitySample/Assets/UnityCam/Example/Scripts/ObjectMotion.cs +++ /dev/null @@ -1,21 +0,0 @@ -using UnityEngine; -using System.Collections; - -public class ObjectMotion : MonoBehaviour { - - float _time; - Vector3 _Speed; - // Use this for initialization - void Start () { - _Speed = Random.insideUnitSphere * 50; - } - - - // Update is called once per frame - void Update () { - - transform.localRotation = Quaternion.Euler (_Speed * _time); - _time += Time.deltaTime; - - } -} diff --git a/UnitySample/Assets/UnityCam/Example/Scripts/ObjectMotion.cs.meta b/UnitySample/Assets/UnityCam/Example/Scripts/ObjectMotion.cs.meta deleted file mode 100644 index c749468..0000000 --- a/UnitySample/Assets/UnityCam/Example/Scripts/ObjectMotion.cs.meta +++ /dev/null @@ -1,12 +0,0 @@ -fileFormatVersion: 2 -guid: 5f9f194e504baa74b9c03007f7a00772 -timeCreated: 1461153446 -licenseType: Free -MonoImporter: - serializedVersion: 2 - defaultReferences: [] - executionOrder: 0 - icon: {instanceID: 0} - userData: - assetBundleName: - assetBundleVariant: diff --git a/UnitySample/Assets/UnityCam/Example/Scripts/Perlin.cs b/UnitySample/Assets/UnityCam/Example/Scripts/Perlin.cs deleted file mode 100644 index 5d2b897..0000000 --- a/UnitySample/Assets/UnityCam/Example/Scripts/Perlin.cs +++ /dev/null @@ -1,185 +0,0 @@ -// -// Reaktion - An audio reactive animation toolkit for Unity. -// -// Copyright (C) 2013, 2014 Keijiro Takahashi -// -// 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. -// - -using UnityEngine; -using System.Runtime.InteropServices; - -namespace Reaktion { - -public static class Perlin -{ - // - // Based on the original implementation by Ken Perlin - // http://mrl.nyu.edu/~perlin/noise/ - // - - #region Noise functions - - public static float Noise (float x) - { - var X = Mathf.FloorToInt (x) & 0xff; - x -= Mathf.Floor (x); - return Lerp (Fade (x), Grad(X, x), Grad (X + 1, x - 1)); - } - - public static float Noise (float x, float y) - { - var X = Mathf.FloorToInt (x) & 0xff; - var Y = Mathf.FloorToInt (y) & 0xff; - x -= Mathf.Floor (x); - y -= Mathf.Floor (y); - var u = Fade (x); - var v = Fade (y); - var A = (perm [X ] + Y) & 0xff; - var B = (perm [X + 1] + Y) & 0xff; - return Lerp (v, Lerp (u, Grad (A , x, y ), Grad (B, x - 1, y )), - Lerp (u, Grad (A + 1, x, y - 1), Grad (B + 1, x - 1, y - 1))); - } - - public static float Noise (Vector2 coord) - { - return Noise (coord.x, coord.y); - } - - public static float Noise (float x, float y, float z) - { - var X = Mathf.FloorToInt (x) & 0xff; - var Y = Mathf.FloorToInt (y) & 0xff; - var Z = Mathf.FloorToInt (z) & 0xff; - x -= Mathf.Floor (x); - y -= Mathf.Floor (y); - z -= Mathf.Floor (z); - var u = Fade (x); - var v = Fade (y); - var w = Fade (z); - var A = (perm [X ] + Y) & 0xff; - var B = (perm [X + 1] + Y) & 0xff; - var AA = (perm [A ] + Z) & 0xff; - var BA = (perm [B ] + Z) & 0xff; - var AB = (perm [A + 1] + Z) & 0xff; - var BB = (perm [B + 1] + Z) & 0xff; - return Lerp (w, Lerp (v, Lerp (u, Grad (AA , x , y , z ), Grad (BA , x - 1, y , z )), - Lerp (u, Grad (AB , x , y - 1, z ), Grad (BB , x - 1, y - 1, z ))), - Lerp (v, Lerp (u, Grad (AA + 1, x , y , z - 1), Grad (BA + 1, x - 1, y , z - 1)), - Lerp (u, Grad (AB + 1, x , y - 1, z - 1), Grad (BB + 1, x - 1, y - 1, z - 1)))); - } - - public static float Noise (Vector3 coord) - { - return Noise (coord.x, coord.y, coord.z); - } - - #endregion - - #region fBm functions - - public static float Fbm (float x, int octave) - { - var f = 0.0f; - var w = 0.5f; - for (var i = 0; i < octave; i++) { - f += w * Noise (x); - x *= 2.0f; - w *= 0.5f; - } - return f; - } - - public static float Fbm (Vector2 coord, int octave) - { - var f = 0.0f; - var w = 0.5f; - for (var i = 0; i < octave; i++) { - f += w * Noise (coord); - coord *= 2.0f; - w *= 0.5f; - } - return f; - } - - public static float Fbm (Vector3 coord, int octave) - { - var f = 0.0f; - var w = 0.5f; - for (var i = 0; i < octave; i++) { - f += w * Noise (coord); - coord *= 2.0f; - w *= 0.5f; - } - return f; - } - - #endregion - - #region Private functions - - static float Fade (float t) - { - return t * t * t * (t * (t * 6 - 15) + 10); - } - - static float Lerp (float t, float a, float b) - { - return a + t * (b - a); - } - - static float Grad (int i, float x) - { - return (perm [i] & 1) != 0 ? x : -x; - } - - static float Grad (int i, float x, float y) - { - var h = perm [i]; - return ((h & 1) != 0 ? x : -x) + ((h & 2) != 0 ? y : -y); - } - - static float Grad (int i, float x, float y, float z) - { - var h = perm [i] & 15; - var u = h < 8 ? x : y; - var v = h < 4 ? y : (h == 12 || h == 14 ? x : z); - return ((h & 1) != 0 ? u : -u) + ((h & 2) != 0 ? v : -v); - } - - static int[] perm = { - 151,160,137,91,90,15, - 131,13,201,95,96,53,194,233,7,225,140,36,103,30,69,142,8,99,37,240,21,10,23, - 190, 6,148,247,120,234,75,0,26,197,62,94,252,219,203,117,35,11,32,57,177,33, - 88,237,149,56,87,174,20,125,136,171,168, 68,175,74,165,71,134,139,48,27,166, - 77,146,158,231,83,111,229,122,60,211,133,230,220,105,92,41,55,46,245,40,244, - 102,143,54, 65,25,63,161, 1,216,80,73,209,76,132,187,208, 89,18,169,200,196, - 135,130,116,188,159,86,164,100,109,198,173,186, 3,64,52,217,226,250,124,123, - 5,202,38,147,118,126,255,82,85,212,207,206,59,227,47,16,58,17,182,189,28,42, - 223,183,170,213,119,248,152, 2,44,154,163, 70,221,153,101,155,167, 43,172,9, - 129,22,39,253, 19,98,108,110,79,113,224,232,178,185, 112,104,218,246,97,228, - 251,34,242,193,238,210,144,12,191,179,162,241, 81,51,145,235,249,14,239,107, - 49,192,214, 31,181,199,106,157,184, 84,204,176,115,121,50,45,127, 4,150,254, - 138,236,205,93,222,114,67,29,24,72,243,141,128,195,78,66,215,61,156,180, - 151 - }; - - #endregion -} - -} // namespace Reaktion diff --git a/UnitySample/Assets/UnityCam/Example/Scripts/Perlin.cs.meta b/UnitySample/Assets/UnityCam/Example/Scripts/Perlin.cs.meta deleted file mode 100644 index cfdf3b0..0000000 --- a/UnitySample/Assets/UnityCam/Example/Scripts/Perlin.cs.meta +++ /dev/null @@ -1,12 +0,0 @@ -fileFormatVersion: 2 -guid: b654b51054ba6894f892494e84aeca0f -timeCreated: 1461153409 -licenseType: Free -MonoImporter: - serializedVersion: 2 - defaultReferences: [] - executionOrder: 0 - icon: {instanceID: 0} - userData: - assetBundleName: - assetBundleVariant: diff --git a/UnitySample/Assets/UnityCam/Example/Scripts/PostEffectsBase.cs b/UnitySample/Assets/UnityCam/Example/Scripts/PostEffectsBase.cs deleted file mode 100644 index 4909fd2..0000000 --- a/UnitySample/Assets/UnityCam/Example/Scripts/PostEffectsBase.cs +++ /dev/null @@ -1,243 +0,0 @@ -using System; -using UnityEngine; - -namespace UnityStandardAssets.ImageEffects -{ - [ExecuteInEditMode] - [RequireComponent (typeof(Camera))] - public class PostEffectsBase : MonoBehaviour - { - protected bool supportHDRTextures = true; - protected bool supportDX11 = false; - protected bool isSupported = true; - - protected Material CheckShaderAndCreateMaterial ( Shader s, Material m2Create) - { - if (!s) - { - Debug.Log("Missing shader in " + ToString ()); - enabled = false; - return null; - } - - if (s.isSupported && m2Create && m2Create.shader == s) - return m2Create; - - if (!s.isSupported) - { - NotSupported (); - Debug.Log("The shader " + s.ToString() + " on effect "+ToString()+" is not supported on this platform!"); - return null; - } - else - { - m2Create = new Material (s); - m2Create.hideFlags = HideFlags.DontSave; - if (m2Create) - return m2Create; - else return null; - } - } - - - protected Material CreateMaterial (Shader s, Material m2Create) - { - if (!s) - { - Debug.Log ("Missing shader in " + ToString ()); - return null; - } - - if (m2Create && (m2Create.shader == s) && (s.isSupported)) - return m2Create; - - if (!s.isSupported) - { - return null; - } - else - { - m2Create = new Material (s); - m2Create.hideFlags = HideFlags.DontSave; - if (m2Create) - return m2Create; - else return null; - } - } - - void OnEnable () - { - isSupported = true; - } - - protected bool CheckSupport () - { - return CheckSupport (false); - } - - - public virtual bool CheckResources () - { - Debug.LogWarning ("CheckResources () for " + ToString() + " should be overwritten."); - return isSupported; - } - - - protected void Start () - { - CheckResources (); - } - - protected bool CheckSupport (bool needDepth) - { - isSupported = true; - supportHDRTextures = SystemInfo.SupportsRenderTextureFormat(RenderTextureFormat.ARGBHalf); - supportDX11 = SystemInfo.graphicsShaderLevel >= 50 && SystemInfo.supportsComputeShaders; - - if (!SystemInfo.supportsImageEffects || !SystemInfo.supportsRenderTextures) - { - NotSupported (); - return false; - } - - if (needDepth && !SystemInfo.SupportsRenderTextureFormat (RenderTextureFormat.Depth)) - { - NotSupported (); - return false; - } - - if (needDepth) - GetComponent().depthTextureMode |= DepthTextureMode.Depth; - - return true; - } - - protected bool CheckSupport (bool needDepth, bool needHdr) - { - if (!CheckSupport(needDepth)) - return false; - - if (needHdr && !supportHDRTextures) - { - NotSupported (); - return false; - } - - return true; - } - - - public bool Dx11Support () - { - return supportDX11; - } - - - protected void ReportAutoDisable () - { - Debug.LogWarning ("The image effect " + ToString() + " has been disabled as it's not supported on the current platform."); - } - - // deprecated but needed for old effects to survive upgrading - bool CheckShader (Shader s) - { - Debug.Log("The shader " + s.ToString () + " on effect "+ ToString () + " is not part of the Unity 3.2+ effects suite anymore. For best performance and quality, please ensure you are using the latest Standard Assets Image Effects (Pro only) package."); - if (!s.isSupported) - { - NotSupported (); - return false; - } - else - { - return false; - } - } - - - protected void NotSupported () - { - enabled = false; - isSupported = false; - return; - } - - - protected void DrawBorder (RenderTexture dest, Material material) - { - float x1; - float x2; - float y1; - float y2; - - RenderTexture.active = dest; - bool invertY = true; // source.texelSize.y < 0.0ff; - // Set up the simple Matrix - GL.PushMatrix(); - GL.LoadOrtho(); - - for (int i = 0; i < material.passCount; i++) - { - material.SetPass(i); - - float y1_; float y2_; - if (invertY) - { - y1_ = 1.0f; y2_ = 0.0f; - } - else - { - y1_ = 0.0f; y2_ = 1.0f; - } - - // left - x1 = 0.0f; - x2 = 0.0f + 1.0f/(dest.width*1.0f); - y1 = 0.0f; - y2 = 1.0f; - GL.Begin(GL.QUADS); - - GL.TexCoord2(0.0f, y1_); GL.Vertex3(x1, y1, 0.1f); - GL.TexCoord2(1.0f, y1_); GL.Vertex3(x2, y1, 0.1f); - GL.TexCoord2(1.0f, y2_); GL.Vertex3(x2, y2, 0.1f); - GL.TexCoord2(0.0f, y2_); GL.Vertex3(x1, y2, 0.1f); - - // right - x1 = 1.0f - 1.0f/(dest.width*1.0f); - x2 = 1.0f; - y1 = 0.0f; - y2 = 1.0f; - - GL.TexCoord2(0.0f, y1_); GL.Vertex3(x1, y1, 0.1f); - GL.TexCoord2(1.0f, y1_); GL.Vertex3(x2, y1, 0.1f); - GL.TexCoord2(1.0f, y2_); GL.Vertex3(x2, y2, 0.1f); - GL.TexCoord2(0.0f, y2_); GL.Vertex3(x1, y2, 0.1f); - - // top - x1 = 0.0f; - x2 = 1.0f; - y1 = 0.0f; - y2 = 0.0f + 1.0f/(dest.height*1.0f); - - GL.TexCoord2(0.0f, y1_); GL.Vertex3(x1, y1, 0.1f); - GL.TexCoord2(1.0f, y1_); GL.Vertex3(x2, y1, 0.1f); - GL.TexCoord2(1.0f, y2_); GL.Vertex3(x2, y2, 0.1f); - GL.TexCoord2(0.0f, y2_); GL.Vertex3(x1, y2, 0.1f); - - // bottom - x1 = 0.0f; - x2 = 1.0f; - y1 = 1.0f - 1.0f/(dest.height*1.0f); - y2 = 1.0f; - - GL.TexCoord2(0.0f, y1_); GL.Vertex3(x1, y1, 0.1f); - GL.TexCoord2(1.0f, y1_); GL.Vertex3(x2, y1, 0.1f); - GL.TexCoord2(1.0f, y2_); GL.Vertex3(x2, y2, 0.1f); - GL.TexCoord2(0.0f, y2_); GL.Vertex3(x1, y2, 0.1f); - - GL.End(); - } - - GL.PopMatrix(); - } - } -} diff --git a/UnitySample/Assets/UnityCam/Example/Scripts/PostEffectsBase.cs.meta b/UnitySample/Assets/UnityCam/Example/Scripts/PostEffectsBase.cs.meta deleted file mode 100644 index 5b0854f..0000000 --- a/UnitySample/Assets/UnityCam/Example/Scripts/PostEffectsBase.cs.meta +++ /dev/null @@ -1,12 +0,0 @@ -fileFormatVersion: 2 -guid: 7041d7ae6f5e53048928e254b1dd7f23 -timeCreated: 1463487751 -licenseType: Free -MonoImporter: - serializedVersion: 2 - defaultReferences: [] - executionOrder: 0 - icon: {instanceID: 0} - userData: - assetBundleName: - assetBundleVariant: diff --git a/UnitySample/Assets/UnityCam/Resources.meta b/UnitySample/Assets/UnityCam/Resources.meta deleted file mode 100644 index 051a9fb..0000000 --- a/UnitySample/Assets/UnityCam/Resources.meta +++ /dev/null @@ -1,9 +0,0 @@ -fileFormatVersion: 2 -guid: 596a25b3925172d4689d0ea19279d560 -folderAsset: yes -timeCreated: 1460973219 -licenseType: Free -DefaultImporter: - userData: - assetBundleName: - assetBundleVariant: diff --git a/UnitySample/Assets/UnityCam/Resources/Blitter.shader b/UnitySample/Assets/UnityCam/Resources/Blitter.shader deleted file mode 100644 index 76b4948..0000000 --- a/UnitySample/Assets/UnityCam/Resources/Blitter.shader +++ /dev/null @@ -1,97 +0,0 @@ -Shader "UnityCam/Image/Blitter" { - Properties { - _MainTex ("Base (RGB)", 2D) = "white" {} - TextureRect ("Texture Clip Rect",Vector) = (0,0,1,1) - } - SubShader { - Pass{ - ZTest Always Cull Off ZWrite Off - Fog { Mode off } - - CGPROGRAM - #pragma vertex vert - #pragma fragment frag - - #include "UnityCG.cginc" - - sampler2D _MainTex; - - struct v2f - { - float4 position : SV_POSITION; - float2 texCoord : TEXCOORD0; - }; - - struct a2v - { - float4 vertex : POSITION; - }; - - - half4 TextureRect= half4(0,0,1,1); - - - v2f vert(appdata_img IN) { - - v2f Out; - Out.position.xy=2*sign(IN.vertex.xy)-1; - Out.position.z = 1.0; - Out.position.w = 1.0; - Out.texCoord.xy =IN.texcoord.xy*TextureRect.zw+TextureRect.xy; - Out.texCoord.xy=1-Out.texCoord.xy; - return Out; - } - - float4 frag(v2f IN) :COLOR { - return tex2D(_MainTex, IN.texCoord.xy); - } - - ENDCG - } - - Pass{ - ZTest Always Cull Off ZWrite Off - Fog { Mode off } - - CGPROGRAM - #pragma vertex vert - #pragma fragment frag - - #include "UnityCG.cginc" - - sampler2D _MainTex; - - struct v2f - { - float4 position : SV_POSITION; - float2 texCoord : TEXCOORD0; - }; - - struct a2v - { - float4 vertex : POSITION; - }; - - - half4 TextureRect= half4(0,0,1,1); - - - v2f vert(appdata_img IN) { - - v2f Out; - Out.position.xy=2*sign(IN.vertex.xy)-1; - Out.position.z = 1.0; - Out.position.w = 1.0; - Out.texCoord.xy =IN.texcoord.xy*TextureRect.zw+TextureRect.xy; - Out.texCoord.y=1-Out.texCoord.y; - return Out; - } - - float4 frag(v2f IN) :COLOR { - return tex2D(_MainTex, IN.texCoord.xy); - } - - ENDCG - } - } -} diff --git a/UnitySample/Assets/UnityCam/Resources/Blitter.shader.meta b/UnitySample/Assets/UnityCam/Resources/Blitter.shader.meta deleted file mode 100644 index e7638ed..0000000 --- a/UnitySample/Assets/UnityCam/Resources/Blitter.shader.meta +++ /dev/null @@ -1,9 +0,0 @@ -fileFormatVersion: 2 -guid: 7b07c0df157f9b04499e7deb94cd461c -timeCreated: 1460983949 -licenseType: Free -ShaderImporter: - defaultTextures: [] - userData: - assetBundleName: - assetBundleVariant: diff --git a/UnitySample/Assets/UnityCam/Scripts.meta b/UnitySample/Assets/UnityCam/Scripts.meta deleted file mode 100644 index 90e6bde..0000000 --- a/UnitySample/Assets/UnityCam/Scripts.meta +++ /dev/null @@ -1,9 +0,0 @@ -fileFormatVersion: 2 -guid: 62d816a67c6a3a84ab05b5a8befb4d14 -folderAsset: yes -timeCreated: 1463485956 -licenseType: Free -DefaultImporter: - userData: - assetBundleName: - assetBundleVariant: diff --git a/UnitySample/Assets/UnityCam/Scripts/OffscreenProcessor.cs b/UnitySample/Assets/UnityCam/Scripts/OffscreenProcessor.cs deleted file mode 100644 index 6ab9963..0000000 --- a/UnitySample/Assets/UnityCam/Scripts/OffscreenProcessor.cs +++ /dev/null @@ -1,75 +0,0 @@ -// -// UnityWebcam -// -// MHD Yamen Saraiji -// yamen@myamens.com -// -// OffscreenProcessor -// Used to apply a shader on a texture - - -using UnityEngine; -using System.Collections; - -public class OffscreenProcessor { - - Material _ProcessingMaterial; - public RenderTexture ResultTexture{ - get{ - return _RenderTexture; - } - } - public Material ProcessingMaterial { - get{ return _ProcessingMaterial; } - } - RenderTexture _RenderTexture; - - public RenderTextureFormat TargetFormat; - - public string ShaderName - { - set{ - ProcessingShader=Shader.Find(value); - } - } - public Shader ProcessingShader - { - set{ - ProcessingMaterial.shader=value; - } - get{ - return ProcessingMaterial.shader; - } - } - - public OffscreenProcessor() - { - _ProcessingMaterial = new Material (Shader.Find("Diffuse")); - TargetFormat = RenderTextureFormat.Default; - } - void _Setup(Texture InputTexture,int downSample) - { - int width = InputTexture.width/(downSample+1); - int height = InputTexture.height/(downSample+1); - if ( (InputTexture as Texture2D !=null) && ((Texture2D)InputTexture).format == TextureFormat.Alpha8) - height =(int)( height / 1.5f); - if (_RenderTexture == null) { - _RenderTexture = new RenderTexture (width, height,16, TargetFormat); - } else if ( _RenderTexture.width != width || - _RenderTexture.height != height) - { - _RenderTexture = new RenderTexture (width, height,16, TargetFormat); - } - } - public Texture ProcessTexture(Texture InputTexture,int pass=0,int downSample=0) - { - if (InputTexture==null || InputTexture.width == 0 || InputTexture.height == 0) - return InputTexture; - _Setup (InputTexture,downSample); - ProcessingMaterial.mainTexture = InputTexture; - Graphics.Blit (InputTexture,_RenderTexture, ProcessingMaterial,pass); - return _RenderTexture; - - } - -} diff --git a/UnitySample/Assets/UnityCam/Scripts/OffscreenProcessor.cs.meta b/UnitySample/Assets/UnityCam/Scripts/OffscreenProcessor.cs.meta deleted file mode 100644 index e5b6313..0000000 --- a/UnitySample/Assets/UnityCam/Scripts/OffscreenProcessor.cs.meta +++ /dev/null @@ -1,12 +0,0 @@ -fileFormatVersion: 2 -guid: 433cb3027c34bb34ba2997cf961bea09 -timeCreated: 1463485948 -licenseType: Free -MonoImporter: - serializedVersion: 2 - defaultReferences: [] - executionOrder: 0 - icon: {instanceID: 0} - userData: - assetBundleName: - assetBundleVariant: diff --git a/UnitySample/Assets/UnityCam/Scripts/TextureWrapper.cs b/UnitySample/Assets/UnityCam/Scripts/TextureWrapper.cs deleted file mode 100644 index b7f48a0..0000000 --- a/UnitySample/Assets/UnityCam/Scripts/TextureWrapper.cs +++ /dev/null @@ -1,57 +0,0 @@ -// -// UnityWebcam -// -// MHD Yamen Saraiji -// yamen@myamens.com -// -// TextureWrapper -// Convert almost any type of textures into Texture2D -// Helpful to access texture pixels - - -using UnityEngine; -using System.Collections; - -public class TextureWrapper -{ - - - Texture2D _wrappedTexture; - - public Texture2D WrappedTexture - { - get { return _wrappedTexture; } - } - - - public Texture2D ConvertTexture(Texture src) - { - if (src == null) - return null; - if (src as Texture2D != null) { - _wrappedTexture = src as Texture2D; - return _wrappedTexture; - } - if (_wrappedTexture == null || - _wrappedTexture.width != src.width || - _wrappedTexture.height != src.height) { - _wrappedTexture = new Texture2D (src.width, src.height, TextureFormat.ARGB32, false); - } - - if (src as WebCamTexture != null) { - _wrappedTexture.SetPixels((src as WebCamTexture).GetPixels ()); - _wrappedTexture.Apply (); - return _wrappedTexture; - } - - if (src as RenderTexture != null) { - RenderTexture.active = src as RenderTexture; - _wrappedTexture.ReadPixels (new Rect (0, 0, src.width, src.height), 0, 0); - _wrappedTexture.Apply (); - RenderTexture.active = null; - return _wrappedTexture; - } - - return null; - } -} diff --git a/UnitySample/Assets/UnityCam/Scripts/TextureWrapper.cs.meta b/UnitySample/Assets/UnityCam/Scripts/TextureWrapper.cs.meta deleted file mode 100644 index 999c9b6..0000000 --- a/UnitySample/Assets/UnityCam/Scripts/TextureWrapper.cs.meta +++ /dev/null @@ -1,12 +0,0 @@ -fileFormatVersion: 2 -guid: 7d793713874f6724a9ef611138c12ceb -timeCreated: 1463485948 -licenseType: Free -MonoImporter: - serializedVersion: 2 - defaultReferences: [] - executionOrder: 0 - icon: {instanceID: 0} - userData: - assetBundleName: - assetBundleVariant: diff --git a/UnitySample/Assets/UnityCam/Scripts/UnityCam.cs b/UnitySample/Assets/UnityCam/Scripts/UnityCam.cs deleted file mode 100644 index 9611b03..0000000 --- a/UnitySample/Assets/UnityCam/Scripts/UnityCam.cs +++ /dev/null @@ -1,90 +0,0 @@ -//Copyright (c) 2016 MHD Yamen Saraiji - - - -using UnityEngine; -using System.Runtime.InteropServices; - -[RequireComponent(typeof(Camera))] -public class UnityCam : MonoBehaviour { - - internal const string DllName="UnityWebcam"; - - [DllImport(DllName,CallingConvention=CallingConvention.Cdecl)] - extern static private System.IntPtr CreateTextureWrapper(); - - [DllImport(DllName,CallingConvention=CallingConvention.Cdecl)] - extern static private void DeleteTextureWrapper(System.IntPtr w); - - [DllImport(DllName,CallingConvention=CallingConvention.Cdecl)] - extern static private bool SendTexture(System.IntPtr w,System.IntPtr textureID); - - - System.IntPtr _instance; - - public Texture ResultTexture; - - public bool Flip=false; - public bool BlitLocaly=true; - - TextureWrapper _wrapper; - - OffscreenProcessor _BlitterProcessor; - - - void Start() { - //Init UnityWebCamera plugin - _instance = CreateTextureWrapper (); - - _BlitterProcessor = new OffscreenProcessor (); - _BlitterProcessor.ShaderName = "UnityCam/Image/Blitter"; - - _wrapper = new TextureWrapper (); - - //Add Post Renderer invoker, it will handle the rest - gameObject.AddComponent (); - } - - //will be invoked by HUGVRPostRenderer - public void RenderImage(RenderTexture source, RenderTexture destination) { - Texture tex = source; - - if(Flip) - tex=_BlitterProcessor.ProcessTexture(tex,0); - else - tex=_BlitterProcessor.ProcessTexture(tex,1); - - _wrapper.ConvertTexture (tex); - tex = _wrapper.WrappedTexture; - ResultTexture = tex; - - //Send the rendered image to the plugin - SendTexture (_instance,tex.GetNativeTexturePtr()); - - if(BlitLocaly) - Graphics.Blit (source, destination); - } - - void OnDestroy() { - for (int i = 0; i < transform.childCount; i++) { - GameObject obj = transform.GetChild(i).gameObject; - DestroyImmediate(obj); - } - } - - class RenderEvent : MonoBehaviour { - public Material material; - - void OnRenderImage(RenderTexture source, RenderTexture destination) { - if (material == null) { - Graphics.Blit(source, destination); - } - Graphics.Blit(source, destination, material); - } - - void OnDestroy() { - DestroyImmediate(material); - } - } - -} \ No newline at end of file diff --git a/UnitySample/Assets/UnityCam/Scripts/UnityCamPostRenderer.cs b/UnitySample/Assets/UnityCam/Scripts/UnityCamPostRenderer.cs deleted file mode 100644 index 9dfd705..0000000 --- a/UnitySample/Assets/UnityCam/Scripts/UnityCamPostRenderer.cs +++ /dev/null @@ -1,23 +0,0 @@ -using UnityEngine; -using System.Collections; - -public class UnityCamPostRenderer : MonoBehaviour { - UnityCam _ownerCamera; - - // Use this for initialization - void Start () { - _ownerCamera = gameObject.GetComponent (); - } - - - // Update is called once per frame - void Update () { - - } - - - - void OnRenderImage(RenderTexture source, RenderTexture destination) { - _ownerCamera.RenderImage (source, destination); - } -} diff --git a/UnitySample/Assets/UnityCam/Scripts/UnityCamPostRenderer.cs.meta b/UnitySample/Assets/UnityCam/Scripts/UnityCamPostRenderer.cs.meta deleted file mode 100644 index e73541e..0000000 --- a/UnitySample/Assets/UnityCam/Scripts/UnityCamPostRenderer.cs.meta +++ /dev/null @@ -1,12 +0,0 @@ -fileFormatVersion: 2 -guid: 5912a2e4c076e3240a46b843a8c9aa4c -timeCreated: 1463487094 -licenseType: Free -MonoImporter: - serializedVersion: 2 - defaultReferences: [] - executionOrder: 0 - icon: {instanceID: 0} - userData: - assetBundleName: - assetBundleVariant: diff --git a/UnitySample/ProjectSettings/AudioManager.asset b/UnitySample/ProjectSettings/AudioManager.asset deleted file mode 100644 index ca5f85c..0000000 Binary files a/UnitySample/ProjectSettings/AudioManager.asset and /dev/null differ diff --git a/UnitySample/ProjectSettings/ClusterInputManager.asset b/UnitySample/ProjectSettings/ClusterInputManager.asset deleted file mode 100644 index 23a0620..0000000 Binary files a/UnitySample/ProjectSettings/ClusterInputManager.asset and /dev/null differ diff --git a/UnitySample/ProjectSettings/DynamicsManager.asset b/UnitySample/ProjectSettings/DynamicsManager.asset deleted file mode 100644 index 6bea8aa..0000000 Binary files a/UnitySample/ProjectSettings/DynamicsManager.asset and /dev/null differ diff --git a/UnitySample/ProjectSettings/EditorBuildSettings.asset b/UnitySample/ProjectSettings/EditorBuildSettings.asset deleted file mode 100644 index 22e6c50..0000000 Binary files a/UnitySample/ProjectSettings/EditorBuildSettings.asset and /dev/null differ diff --git a/UnitySample/ProjectSettings/EditorSettings.asset b/UnitySample/ProjectSettings/EditorSettings.asset deleted file mode 100644 index 74adc0d..0000000 Binary files a/UnitySample/ProjectSettings/EditorSettings.asset and /dev/null differ diff --git a/UnitySample/ProjectSettings/GraphicsSettings.asset b/UnitySample/ProjectSettings/GraphicsSettings.asset deleted file mode 100644 index cfd3d64..0000000 Binary files a/UnitySample/ProjectSettings/GraphicsSettings.asset and /dev/null differ diff --git a/UnitySample/ProjectSettings/InputManager.asset b/UnitySample/ProjectSettings/InputManager.asset deleted file mode 100644 index 2aef0e4..0000000 Binary files a/UnitySample/ProjectSettings/InputManager.asset and /dev/null differ diff --git a/UnitySample/ProjectSettings/NavMeshAreas.asset b/UnitySample/ProjectSettings/NavMeshAreas.asset deleted file mode 100644 index d70765e..0000000 Binary files a/UnitySample/ProjectSettings/NavMeshAreas.asset and /dev/null differ diff --git a/UnitySample/ProjectSettings/NetworkManager.asset b/UnitySample/ProjectSettings/NetworkManager.asset deleted file mode 100644 index 7f5693e..0000000 Binary files a/UnitySample/ProjectSettings/NetworkManager.asset and /dev/null differ diff --git a/UnitySample/ProjectSettings/Physics2DSettings.asset b/UnitySample/ProjectSettings/Physics2DSettings.asset deleted file mode 100644 index 6947a86..0000000 Binary files a/UnitySample/ProjectSettings/Physics2DSettings.asset and /dev/null differ diff --git a/UnitySample/ProjectSettings/ProjectSettings.asset b/UnitySample/ProjectSettings/ProjectSettings.asset deleted file mode 100644 index b5754c6..0000000 Binary files a/UnitySample/ProjectSettings/ProjectSettings.asset and /dev/null differ diff --git a/UnitySample/ProjectSettings/ProjectVersion.txt b/UnitySample/ProjectSettings/ProjectVersion.txt deleted file mode 100644 index 86d1b1e..0000000 --- a/UnitySample/ProjectSettings/ProjectVersion.txt +++ /dev/null @@ -1 +0,0 @@ -m_EditorVersion: 5.5.1f1 diff --git a/UnitySample/ProjectSettings/QualitySettings.asset b/UnitySample/ProjectSettings/QualitySettings.asset deleted file mode 100644 index 09b6715..0000000 Binary files a/UnitySample/ProjectSettings/QualitySettings.asset and /dev/null differ diff --git a/UnitySample/ProjectSettings/TagManager.asset b/UnitySample/ProjectSettings/TagManager.asset deleted file mode 100644 index 1805621..0000000 Binary files a/UnitySample/ProjectSettings/TagManager.asset and /dev/null differ diff --git a/UnitySample/ProjectSettings/TimeManager.asset b/UnitySample/ProjectSettings/TimeManager.asset deleted file mode 100644 index 42aaac4..0000000 Binary files a/UnitySample/ProjectSettings/TimeManager.asset and /dev/null differ diff --git a/UnitySample/ProjectSettings/UnityAdsSettings.asset b/UnitySample/ProjectSettings/UnityAdsSettings.asset deleted file mode 100644 index 0db06d2..0000000 Binary files a/UnitySample/ProjectSettings/UnityAdsSettings.asset and /dev/null differ diff --git a/UnitySample/ProjectSettings/UnityConnectSettings.asset b/UnitySample/ProjectSettings/UnityConnectSettings.asset deleted file mode 100644 index 51030e7..0000000 Binary files a/UnitySample/ProjectSettings/UnityConnectSettings.asset and /dev/null differ diff --git a/UnitySample/UnitySample.sln b/UnitySample/UnitySample.sln deleted file mode 100644 index 27ef28c..0000000 --- a/UnitySample/UnitySample.sln +++ /dev/null @@ -1,29 +0,0 @@ - -Microsoft Visual Studio Solution File, Format Version 11.00 -# Visual Studio 2010 -Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "UnitySample", "Assembly-CSharp.csproj", "{8CA90CBA-908E-E48D-E4F6-89E98795426A}" -EndProject -Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "UnitySample", "Assembly-CSharp-Editor.csproj", "{9C21D318-2030-5359-A548-3B6B7BE01728}" -EndProject -Global - GlobalSection(SolutionConfigurationPlatforms) = preSolution - Debug|Any CPU = Debug|Any CPU - Release|Any CPU = Release|Any CPU - EndGlobalSection - GlobalSection(ProjectConfigurationPlatforms) = postSolution - {8CA90CBA-908E-E48D-E4F6-89E98795426A}.Debug|Any CPU.ActiveCfg = Debug|Any CPU - {8CA90CBA-908E-E48D-E4F6-89E98795426A}.Debug|Any CPU.Build.0 = Debug|Any CPU - {8CA90CBA-908E-E48D-E4F6-89E98795426A}.Release|Any CPU.ActiveCfg = Release|Any CPU - {8CA90CBA-908E-E48D-E4F6-89E98795426A}.Release|Any CPU.Build.0 = Release|Any CPU - {9C21D318-2030-5359-A548-3B6B7BE01728}.Debug|Any CPU.ActiveCfg = Debug|Any CPU - {9C21D318-2030-5359-A548-3B6B7BE01728}.Debug|Any CPU.Build.0 = Debug|Any CPU - {9C21D318-2030-5359-A548-3B6B7BE01728}.Release|Any CPU.ActiveCfg = Release|Any CPU - {9C21D318-2030-5359-A548-3B6B7BE01728}.Release|Any CPU.Build.0 = Release|Any CPU - EndGlobalSection - GlobalSection(SolutionProperties) = preSolution - HideSolutionNode = FALSE - EndGlobalSection - GlobalSection(MonoDevelopProperties) = preSolution - StartupItem = Assembly-CSharp.csproj - EndGlobalSection -EndGlobal diff --git a/UnitySample/UnityWebcam.sln b/UnitySample/UnityWebcam.sln deleted file mode 100644 index 811dc98..0000000 --- a/UnitySample/UnityWebcam.sln +++ /dev/null @@ -1,29 +0,0 @@ -Microsoft Visual Studio Solution File, Format Version 11.00 -# Visual Studio 2008 - -Project("{31D7C034-6A48-B351-511D-3327DE92CCBB}") = "UnityWebcam", "Assembly-CSharp.csproj", "{A9030E16-E41F-D264-F799-646233B948ED}" -EndProject -Project("{31D7C034-6A48-B351-511D-3327DE92CCBB}") = "UnityWebcam", "Assembly-CSharp-Editor.csproj", "{413A5073-4620-A495-2156-06A23421B168}" -EndProject -Global - GlobalSection(SolutionConfigurationPlatforms) = preSolution - Debug|Any CPU = Debug|Any CPU - Release|Any CPU = Release|Any CPU - EndGlobalSection - GlobalSection(ProjectConfigurationPlatforms) = postSolution - {A9030E16-E41F-D264-F799-646233B948ED}.Debug|Any CPU.ActiveCfg = Debug|Any CPU - {A9030E16-E41F-D264-F799-646233B948ED}.Debug|Any CPU.Build.0 = Debug|Any CPU - {A9030E16-E41F-D264-F799-646233B948ED}.Release|Any CPU.ActiveCfg = Release|Any CPU - {A9030E16-E41F-D264-F799-646233B948ED}.Release|Any CPU.Build.0 = Release|Any CPU - {413A5073-4620-A495-2156-06A23421B168}.Debug|Any CPU.ActiveCfg = Debug|Any CPU - {413A5073-4620-A495-2156-06A23421B168}.Debug|Any CPU.Build.0 = Debug|Any CPU - {413A5073-4620-A495-2156-06A23421B168}.Release|Any CPU.ActiveCfg = Release|Any CPU - {413A5073-4620-A495-2156-06A23421B168}.Release|Any CPU.Build.0 = Release|Any CPU - EndGlobalSection - GlobalSection(SolutionProperties) = preSolution - HideSolutionNode = FALSE - EndGlobalSection - GlobalSection(MonoDevelopProperties) = preSolution - StartupItem = Assembly-CSharp.csproj - EndGlobalSection -EndGlobal diff --git a/UnityWebcam/UnityCamService/CapFilter.cpp b/UnityWebcam/UnityCamService/CapFilter.cpp deleted file mode 100644 index 2d3ca1e..0000000 --- a/UnityWebcam/UnityCamService/CapFilter.cpp +++ /dev/null @@ -1,142 +0,0 @@ - -#include "StdAfx.h" -#include -#include "CaptureSource.h" - -#define CreateComObject(clsid, iid, var) CoCreateInstance( clsid, NULL, CLSCTX_INPROC_SERVER, iid, (void **)&var); - -STDAPI AMovieSetupRegisterServer( CLSID clsServer, LPCWSTR szDescription, LPCWSTR szFileName, LPCWSTR szThreadingModel = L"Both", LPCWSTR szServerType = L"InprocServer32" ); -STDAPI AMovieSetupUnregisterServer( CLSID clsServer ); - -CFactoryTemplate g_Templates[] = -{ - { CaptureSourceName, &CLSID_UnityCamService, CaptureSource::CreateInstance, NULL, &sudCaptureSource } -}; -int g_cTemplates = sizeof(g_Templates) / sizeof(g_Templates[0]); - - -// Stack Overflow - "Fake" DirectShow video capture device -// http://stackoverflow.com/questions/1376734/fake-directshow-video-capture-device -STDAPI RegisterFilters(BOOL bRegister) -{ - HRESULT hr = NOERROR; - WCHAR achFileName[MAX_PATH]; - char achTemp[MAX_PATH]; - ASSERT(g_hInst != 0); - - - if( 0 == GetModuleFileNameA(g_hInst, achTemp, sizeof(achTemp))) - return AmHresultFromWin32(GetLastError()); - - MultiByteToWideChar(CP_ACP, 0L, achTemp, lstrlenA(achTemp) + 1, - achFileName, NUMELMS(achFileName)); - - hr = CoInitialize(0); - if(bRegister) - { - hr = AMovieSetupRegisterServer(CLSID_UnityCamService, CaptureSourceName, achFileName, L"Both", L"InprocServer32"); - } - - if(SUCCEEDED(hr)) { - IFilterMapper2 *fm = NULL; - hr = CreateComObject(CLSID_FilterMapper2, IID_IFilterMapper2, fm); - - if(SUCCEEDED(hr)) { - if(bRegister) { - IMoniker *pMoniker = 0; - REGFILTER2 rf2; - rf2.dwVersion = 1; - rf2.dwMerit = MERIT_DO_NOT_USE; - rf2.cPins = 1; - rf2.rgPins = &sudCaptureSourceOut; - hr = fm->RegisterFilter(CLSID_UnityCamService, CaptureSourceName, 0, &CLSID_VideoInputDeviceCategory, NULL, &rf2); - if (SUCCEEDED(hr)) - { - //MessageBox(0, L"RegisterFilter", L"Success", NULL); - } - else{ - //MessageBox(0, L"RegisterFilter", L"Failed", NULL); - } - }else{ - hr = fm->UnregisterFilter(&CLSID_VideoInputDeviceCategory, 0, CLSID_UnityCamService); - } - } - if(fm) { - fm->Release(); - fm = NULL; - } - } - - if(SUCCEEDED(hr) && !bRegister) { - hr = AMovieSetupUnregisterServer(CLSID_UnityCamService); - } - if (!SUCCEEDED(hr)) - { - // MessageBox(0, L"Failed to RegisterFilters", L"Error", NULL); - } - else{ - //MessageBox(0, L"Success to RegisterFilters", L"Success", NULL); - - } - - CoFreeUnusedLibraries(); - CoUninitialize(); - return hr; -} - -STDAPI DllRegisterServer() -{ - HRESULT res= RegisterFilters(TRUE); - - //this quick hack lets unity read the virtual camera too! - // thanks for: - //https://social.msdn.microsoft.com/Forums/windowsdesktop/en-US/cd2b9d2d-b961-442d-8946-fdc038fed530/where-to-specify-device-id-in-the-filter?forum=windowsdirectshowdevelopment - HKEY hKey; - - LPOLESTR guidString; - StringFromCLSID(CLSID_VideoInputDeviceCategory, &guidString); - std::wstring inputCat = guidString; - std::wstring str_video_capture_device_key = L"CLSID\\" + inputCat + L"\\Instance"; - - //std::string str_video_capture_device_key("SOFTWARE\\Classes\\CLSID\\{860BB310-5D01-11d0-BD3B-00A0C911CE86}\\Instance\\"); - - LPOLESTR olestr_CLSID; - StringFromCLSID(CLSID_UnityCamService, &olestr_CLSID); - - std::wstring wstr_CLSID(olestr_CLSID); - - int size_needed = WideCharToMultiByte(CP_UTF8, 0, &wstr_CLSID[0], (int)wstr_CLSID.size(), NULL, 0, NULL, NULL); - std::string str2(size_needed, 0); - WideCharToMultiByte(CP_UTF8, 0, &wstr_CLSID[0], (int)wstr_CLSID.size(), &str2[0], size_needed, NULL, NULL); - - str_video_capture_device_key.append(wstr_CLSID); - - RegOpenKeyEx(HKEY_LOCAL_MACHINE, str_video_capture_device_key.c_str(), 0, KEY_ALL_ACCESS, &hKey); - LPCSTR value = ("DevicePath"); - LPCSTR data = "foo:bar"; - RegSetValueExA(hKey, value, 0, REG_SZ, (LPBYTE)data, strlen(data) + 1); - RegCloseKey(hKey); - if (!SUCCEEDED(res)) - { - //MessageBox(0, L"Failed to RegisterServer", L"Error", NULL); - } - else{ - //MessageBox(0, L"Success to RegisterServer", L"Success", NULL); - - } - return res; -} - -STDAPI DllUnregisterServer() -{ - HRESULT res = RegisterFilters(FALSE); - if (!SUCCEEDED(res)) - { - //MessageBox(0, L"Failed to DllUnregisterServer", L"Error", NULL); - } - else{ - //MessageBox(0, L"Success to DllUnregisterServer", L"Success", NULL); - - } - return res; -} diff --git a/UnityWebcam/UnityCamService/CaptureSharedMemory.cpp b/UnityWebcam/UnityCamService/CaptureSharedMemory.cpp deleted file mode 100644 index 9239960..0000000 --- a/UnityWebcam/UnityCamService/CaptureSharedMemory.cpp +++ /dev/null @@ -1,110 +0,0 @@ -#include "StdAfx.h" -#include "CaptureSharedMemory.h" -#include "SharedMutex.h" - -CaptureSharedMemory::CaptureSharedMemory(const wchar_t* memName, const wchar_t* writeEventName, const wchar_t* readEventName, HRESULT* phr) -{ - m_pMutex = NULL; - m_iLocalBufSize = 0; - m_pLocalBuf = NULL; - m_hSharedFile = NULL; - m_hWriteEvent = NULL; - m_pSharedBuf = NULL; - - HRESULT hr = S_OK; - if(memName == NULL || writeEventName == NULL || readEventName == NULL) { - *phr = E_POINTER; - return; - } - - m_pMutex = new SharedMutex(readEventName, TRUE, & hr); - if(FAILED(hr)) { - *phr = hr; - return; - } - - CriticalSection cs(m_pMutex); - m_hSharedFile = CreateFileMapping(INVALID_HANDLE_VALUE, NULL, PAGE_READWRITE, NULL, sizeof(SharedMemHeader) + MAX_BUF_SIZE, memName); - if (m_hSharedFile == NULL) { - *phr = E_UNEXPECTED; - return; - } - - m_pSharedBuf = (SharedMemHeader*)MapViewOfFile(m_hSharedFile, FILE_MAP_WRITE, 0, 0, 0); - if(m_pSharedBuf == NULL) { - *phr = E_UNEXPECTED; - return; - } - ZeroMemory(m_pSharedBuf, sizeof(SharedMemHeader)+MAX_BUF_SIZE); - m_pSharedBuf->maxSize = MAX_BUF_SIZE; - m_pSharedBuf->size = sizeof(BufferHeader)+3; - BufferHeader* pBufDesc = (BufferHeader*)m_pSharedBuf->bufferPtr; - pBufDesc->width = 1; - pBufDesc->height = 1; - pBufDesc->timestamp = 0; - - m_hWriteEvent = CreateEvent(NULL, FALSE, FALSE, writeEventName); - if (m_hWriteEvent == NULL) { - *phr = E_UNEXPECTED; - return; - } -} - -CaptureSharedMemory::~CaptureSharedMemory(void) -{ - if(m_pMutex != NULL) { - delete m_pMutex; - m_pMutex = NULL; - } - if(m_pLocalBuf != NULL) { - delete[] m_pLocalBuf; - m_pLocalBuf = NULL; - } - if(m_hWriteEvent != NULL) { - CloseHandle(m_hWriteEvent); - m_hWriteEvent = NULL; - } - if(m_hSharedFile != NULL) { - CloseHandle(m_hSharedFile); - m_hSharedFile = NULL; - } - m_pSharedBuf = NULL; -} - -void CaptureSharedMemory::Destroy() -{ - delete this; -} - -HRESULT CaptureSharedMemory::Receive(BufferHeader* pDesc, unsigned char** ppBuffer) -{ - if(pDesc == NULL || ppBuffer == NULL) { - return E_POINTER; - } - DWORD dwEvent = WaitForSingleObject(m_hWriteEvent, 0); - if (dwEvent == WAIT_OBJECT_0 || m_pLocalBuf == NULL) { - CriticalSection cs(m_pMutex); - if(m_iLocalBufSize != m_pSharedBuf->size) { - if(m_pLocalBuf != NULL) { - delete[] m_pLocalBuf; - m_pLocalBuf = NULL; - } - //MessageBox(0, L"Receive", L"", NULL); - m_pLocalBuf = new unsigned char[m_pSharedBuf->size]; - m_iLocalBufSize = m_pSharedBuf->size; - } - memcpy(m_pLocalBuf, m_pSharedBuf->bufferPtr, m_iLocalBufSize); - } - - memcpy(pDesc, m_pLocalBuf, sizeof(BufferHeader)); - *ppBuffer = m_pLocalBuf + sizeof(BufferHeader); - return S_OK; -} - -HRESULT CaptureSharedMemory::NotifyProcessed(unsigned char* pBuffer) -{ - if(pBuffer == NULL) { - return E_POINTER; - } - return S_OK; -} diff --git a/UnityWebcam/UnityCamService/CaptureSharedMemory.h b/UnityWebcam/UnityCamService/CaptureSharedMemory.h deleted file mode 100644 index e08c734..0000000 --- a/UnityWebcam/UnityCamService/CaptureSharedMemory.h +++ /dev/null @@ -1,31 +0,0 @@ -#pragma once - -class SharedMutex; - -#define MAX_BUF_SIZE 2000 * 2000 * 3 - -#include "SharedMemData.h" - -class CaptureSharedMemory -{ -public: - - CaptureSharedMemory(const wchar_t* memName, const wchar_t* writeEventName, const wchar_t* readEventName, HRESULT* phr); - virtual ~CaptureSharedMemory(void); - - virtual void Destroy(); - - virtual HRESULT Receive(BufferHeader* pDesc, unsigned char** ppBuffer); - - virtual HRESULT NotifyProcessed(unsigned char* pBuffer); - -private: - - HANDLE m_hWriteEvent; - SharedMutex* m_pMutex; - HANDLE m_hSharedFile; - SharedMemHeader* m_pSharedBuf; - int32_t m_iLocalBufSize; - unsigned char* m_pLocalBuf; - -}; diff --git a/UnityWebcam/UnityCamService/CaptureSource.cpp b/UnityWebcam/UnityCamService/CaptureSource.cpp deleted file mode 100644 index 04771c9..0000000 --- a/UnityWebcam/UnityCamService/CaptureSource.cpp +++ /dev/null @@ -1,666 +0,0 @@ -#include "StdAfx.h" -#include "CaptureSource.h" -#include "Globals.h" - -#include "CaptureSharedMemory.h" - -#define DEFAULT_WIDTH 1280 -#define DEFAULT_HEIGHT 720 -#define MIN_WIDTH 640 -#define MIN_HEIGHT 480 -#define MAX_WIDTH 1280 -#define MAX_HEIGHT 720 -#define MAX_FPS 30 -#define MIN_FPS 30 -#define MAX_FRAME_INTERVAL 10000000 / MIN_FPS -#define MIN_FRAME_INTERVAL 10000000 / MAX_FPS - -#define DEFAULT_FPS 60 - -#pragma comment(lib, "wsock32.lib") -#include -#include - - - -std::function waitFps_closure() { - auto startTime = std::chrono::system_clock::now(); - long long counter = 0; - int fpsCounter = 0; - return [startTime, counter]() mutable { - auto now = std::chrono::system_clock::now(); - auto diff = now - startTime; - long long diffInt = std::chrono::duration_cast(diff).count(); - - if (diffInt * DEFAULT_FPS > 1000 * counter) { - counter++; - return true; - } - else { - return false; - } - }; -} - -const AMOVIESETUP_MEDIATYPE sudMediaTypesCaptureSourceOut = -{ - &MEDIATYPE_Video, - &MEDIASUBTYPE_NULL -}; - -const AMOVIESETUP_PIN sudCaptureSourceOut = -{ - L"Output", // Pin string name - FALSE, // Is it rendered - TRUE, // Is it an output - FALSE, // Can we have none - FALSE, // Can we have many - &CLSID_NULL, // Connects to filter - NULL, // Connects to pin - 1, // Number of types - &sudMediaTypesCaptureSourceOut // Pin Media types -}; - -const AMOVIESETUP_FILTER sudCaptureSource = -{ - &CLSID_UnityCamService, // Filter CLSID - CaptureSourceName, // String name - MERIT_DO_NOT_USE, // Filter merit - 1,//0, // Number pins - & sudCaptureSourceOut // Pin details -}; - -CUnknown * WINAPI CaptureSource::CreateInstance(LPUNKNOWN lpunk, HRESULT *phr) -{ - ASSERT(phr); - //MessageBox(0, L"CreateInstance", L"", NULL); - CaptureSource *punk = new CaptureSource(lpunk, phr); - if (punk == NULL) - { - *phr = E_OUTOFMEMORY; - } - - HRESULT hr = S_OK; - CaptureSharedMemory* pRecv = new CaptureSharedMemory(CS_SHARED_Base_PATH, CS_EVENT_Base_WRITE,CS_EVENT_Base_READ, &hr); - if(FAILED(hr)) { - *phr = hr; - delete pRecv; - pRecv = NULL; - delete punk; - punk = NULL; - return NULL; - } - - hr = punk->Init(pRecv, DEFAULT_FPS); - if(FAILED(hr)) { - *phr = hr; - delete pRecv; - pRecv = NULL; - delete punk; - punk = NULL; - return NULL; - } - return punk; -} - -CaptureSource::CaptureSource(LPUNKNOWN lpunk, HRESULT* phr) -: CSource(L"Source", lpunk, CLSID_UnityCamService, phr) -{ - //MessageBox(0, L"CaptureSource()", L"", 0);; - -} - -CaptureSource::~CaptureSource(void) -{ - ; -} - -STDMETHODIMP CaptureSource::NonDelegatingQueryInterface(REFIID riid, void ** ppv) -{ - if(ppv == NULL) { - return E_POINTER; - } - if(riid == IID_IQualityControl) { - *ppv = (IQualityControl*) this; - AddRef(); - return S_OK; - }else if(riid == IID_ICamSource) { - *ppv = (ICamSource*) this; - AddRef(); - return S_OK; - } - return CSource::NonDelegatingQueryInterface(riid, ppv); -} - -STDMETHODIMP CaptureSource::Notify(IBaseFilter *pSelf, Quality q) -{ - return S_OK; -} - -STDMETHODIMP CaptureSource::SetSink(IQualityControl *piqc) -{ - return S_OK; -} - -HRESULT CaptureSource::Init(CaptureSharedMemory* pReceiver, int fps) -{ - HRESULT hr = S_OK; - CaptureStream* pStream = new CaptureStream(this, pReceiver, fps, & hr); - if(FAILED(hr)) { - delete pStream; - pStream = NULL; - return hr; - } - return S_OK; -} - -CaptureSource::CaptureStream::CaptureStream(CaptureSource* pOwner, CaptureSharedMemory* pReceiver, int fps, HRESULT* phr) -:CSourceStream(L"Stream", phr, pOwner, L"Output") -{ - oldStartTime_ = 0; - lastTime = std::chrono::system_clock::now(); - fpsChecker = waitFps_closure(); - m_avgTimePerFrame = 10000000 / fps; - m_iPrefWidth = DEFAULT_WIDTH; - m_iPrefHeight = DEFAULT_HEIGHT; - m_llTime = 0; - m_llFrame = 0; - m_pReceiver = pReceiver; - m_llLastSampleTime = -1; - - - GetMediaType(/*1,*/ &m_mt); -} - -CaptureSource::CaptureStream::~CaptureStream() -{ - if(m_pReceiver != NULL) { - m_pReceiver->Destroy(); - m_pReceiver = NULL; - } -} - -HRESULT CaptureSource::CaptureStream::QueryInterface(REFIID riid, void **ppv) -{ - // Standard OLE stuff - if (riid == _uuidof(IAMStreamConfig)) - *ppv = (IAMStreamConfig*)this; - else if (riid == _uuidof(IKsPropertySet)) - *ppv = (IKsPropertySet*)this; - else - return CSourceStream::QueryInterface(riid, ppv); - - AddRef(); - return S_OK; -} - - -STDMETHODIMP CaptureSource::CaptureStream::NonDelegatingQueryInterface(REFIID riid, void ** ppv) -{ - if(ppv == NULL) { - return E_POINTER; - } - if(riid == IID_IKsPropertySet) { - *ppv = (IKsPropertySet*) this; - AddRef(); - return S_OK; - }else if(riid == IID_IQualityControl) { - *ppv = (IQualityControl*) this; - AddRef(); - return S_OK; - }else if(riid == IID_IAMStreamConfig) { - *ppv = (IAMStreamConfig*) this; - AddRef(); - return S_OK; - } - return CSourceStream::NonDelegatingQueryInterface(riid, ppv); -} - -STDMETHODIMP CaptureSource::CaptureStream::QuerySupported(REFGUID rguidPropSet, ULONG ulId, PULONG pulTypeSupport) -{ - - if (rguidPropSet != AMPROPSETID_Pin) return E_PROP_SET_UNSUPPORTED; - if (ulId != AMPROPERTY_PIN_CATEGORY) return E_PROP_ID_UNSUPPORTED; - // We support getting this property, but not setting it. - if (pulTypeSupport) *pulTypeSupport = KSPROPERTY_SUPPORT_GET; - return S_OK; - /* - if(rguidPropSet == AMPROPSETID_Pin && ulId == AMPROPERTY_PIN_CATEGORY) { - *pulTypeSupport = KSPROPERTY_SUPPORT_GET; - return S_OK; - } - return E_NOTIMPL;*/ -} - -STDMETHODIMP CaptureSource::CaptureStream::Get(REFGUID rguidPropSet, ULONG ulId, LPVOID pInstanceData, ULONG ulInstanceLength, LPVOID pPropertyData, ULONG ulDataLength, PULONG pulBytesReturned) -{ - - if (rguidPropSet != AMPROPSETID_Pin) return E_PROP_SET_UNSUPPORTED; - if (ulId != AMPROPERTY_PIN_CATEGORY) return E_PROP_ID_UNSUPPORTED; - if (pPropertyData == NULL && pulBytesReturned == NULL) return E_POINTER; - - if (pulBytesReturned) *pulBytesReturned = sizeof(GUID); - if (pPropertyData == NULL) return S_OK; // Caller just wants to know the size. - if (ulDataLength < sizeof(GUID)) return E_UNEXPECTED;// The buffer is too small. - - *(GUID *)pPropertyData = PIN_CATEGORY_CAPTURE; - return S_OK; - /* - if(rguidPropSet == AMPROPSETID_Pin && ulId == AMPROPERTY_PIN_CATEGORY) { - if(pPropertyData == NULL) { - return E_POINTER; - } - if(ulDataLength != sizeof(GUID)) { - return E_INVALIDARG; - } - memcpy(pPropertyData, &PIN_CATEGORY_CAPTURE, sizeof(GUID)); - *pulBytesReturned = sizeof(GUID); - return S_OK; - } - return E_NOTIMPL;*/ -} - -STDMETHODIMP CaptureSource::CaptureStream::Set(REFGUID rguidPropSet, ULONG ulId, LPVOID pInstanceData, ULONG ulInstanceLength, LPVOID pPropertyData, ULONG ulDataLength) -{ - return E_NOTIMPL; -} - -HRESULT CaptureSource::CaptureStream::FillBuffer(IMediaSample *pSamp) -{ - - CAutoLock lock(m_pFilter->pStateLock()); - - HRESULT hr = S_OK; - VIDEOINFO *pvi = (VIDEOINFO*) m_mt.Format(); - hr = pSamp->SetActualDataLength(pvi->bmiHeader.biSizeImage); - if(FAILED(hr)) { - return hr; - } - BYTE* pBuf = NULL; - hr = pSamp->GetPointer(& pBuf); - if(FAILED(hr)) { - return hr; - } - ZeroMemory(pBuf, pvi->bmiHeader.biSizeImage); - unsigned char* pRecvBuf = NULL; - BufferHeader recvDesc; - ZeroMemory(& recvDesc, sizeof(recvDesc)); - LONGLONG avgTimePF = m_avgTimePerFrame / 10000; - hr = m_pReceiver->Receive(& recvDesc, & pRecvBuf); - - - if(FAILED(hr)) { - return hr; - } - hr = m_pReceiver->NotifyProcessed(pRecvBuf); - pRecvBuf = NULL; - if (FAILED(hr)) { - return hr; - } - // Sleep((DWORD) avgTimePF / 2); - -// while (!fpsChecker()) { -// Sleep(3); -// } - - hr = m_pReceiver->Receive(&recvDesc, &pRecvBuf); - if (FAILED(hr)) { - return hr; - } - - HRESULT retCode = S_OK; - if(hr == S_FALSE) { - retCode = S_FALSE; - } - m_llLastSampleTime = recvDesc.timestamp; - - int destbytes = pvi->bmiHeader.biBitCount / 8; - int destwidthstep = pvi->bmiHeader.biSizeImage / pvi->bmiHeader.biHeight; - double scaling = 0.0, ax = 0.0, ay = 0.0; - hr = GetScaling(recvDesc.width, recvDesc.height, & scaling, & ax, & ay); - if(FAILED(hr)) { - return hr; - } - - for(int y = 0; y < pvi->bmiHeader.biHeight; y ++) { - for(int x = 0; x < pvi->bmiHeader.biWidth; x ++) { - double sx = (x - ax) / scaling; - double sy = (y - ay) / scaling; - int isx = (int) sx; - int isy = (int) sy; - int destoffs = x * destbytes + y * destwidthstep; - if(isx < 0 || isy < 0 || isx >= recvDesc.width || isy >= recvDesc.height) { - pBuf[destoffs + 2] = 0x00; - pBuf[destoffs + 1] = 0x00; - pBuf[destoffs + 0] = 0x00; - continue; - } - - int srcoffs = isx * 3 + isy * (recvDesc.width * 3); - pBuf[destoffs + 2] = pRecvBuf[srcoffs + 0]; - pBuf[destoffs + 1] = pRecvBuf[srcoffs + 1]; - pBuf[destoffs + 0] = pRecvBuf[srcoffs + 2]; - } - } - - hr = m_pReceiver->NotifyProcessed(pRecvBuf); - pRecvBuf = NULL; - if(FAILED(hr)) { - return hr; - } - - REFERENCE_TIME startTime = oldStartTime_; - REFERENCE_TIME endTime = startTime + m_avgTimePerFrame; - - oldStartTime_ = endTime; - - hr = pSamp->SetTime(& startTime, & endTime); - if(FAILED(hr)) { - return hr; - } - LONGLONG mtStart = m_llFrame; - LONGLONG mtEnd = mtStart + 1; - hr = pSamp->SetMediaTime(& mtStart, & mtEnd); - if(FAILED(hr)) { - return hr; - } - m_llTime += avgTimePF; - m_llFrame ++; - return retCode; -} - -HRESULT CaptureSource::CaptureStream::DecideBufferSize(IMemAllocator * pAlloc, ALLOCATOR_PROPERTIES * pRequest) -{ - if(pAlloc == NULL || pRequest == NULL) { - return E_POINTER; - } - HRESULT hr = NOERROR; - VIDEOINFO *pvi = (VIDEOINFO*) m_mt.Format(); - pRequest->cBuffers = 1; - - if (pvi->bmiHeader.biSizeImage > (DWORD)pRequest->cbBuffer) { - pRequest->cbBuffer = pvi->bmiHeader.biSizeImage; - } - ALLOCATOR_PROPERTIES actual; - hr=pAlloc->SetProperties(pRequest, &actual); - if (FAILED(hr)) { - return hr; - } - if (actual.cbBuffer < pRequest->cbBuffer) { - return E_FAIL; - } - return S_OK; -} -////////////////////////////////////////////////////////////////////////// -// This is called when the output format has been negotiated -////////////////////////////////////////////////////////////////////////// -HRESULT CaptureSource::CaptureStream::SetMediaType(const CMediaType *pmt) -{ - DECLARE_PTR(VIDEOINFOHEADER, pvi, pmt->Format()); - HRESULT hr = CSourceStream::SetMediaType(pmt); - return hr; -} - - -// This method is called to see if a given output format is supported -HRESULT CaptureSource::CaptureStream::CheckMediaType(const CMediaType *pMediaType) -{ - VIDEOINFOHEADER *pvi = (VIDEOINFOHEADER *)(pMediaType->Format()); - if (*pMediaType != m_mt) - return E_INVALIDARG; - return S_OK; -} // CheckMediaType - -STDMETHODIMP CaptureSource::CaptureStream::Notify(IBaseFilter *pSelf, Quality q) -{ - return S_OK; -} - -STDMETHODIMP CaptureSource::CaptureStream::SetSink(IQualityControl *piqc) -{ - return S_OK; -} - -STDMETHODIMP CaptureSource::CaptureStream::SetFormat(AM_MEDIA_TYPE *pmt) -{ - if(pmt == NULL) { - return E_POINTER; - } - VIDEOINFO* pvi = (VIDEOINFO*) pmt->pbFormat; - if(pvi == NULL) { - return E_UNEXPECTED; - } - m_avgTimePerFrame = pvi->AvgTimePerFrame; - m_iPrefWidth = pvi->bmiHeader.biWidth; - m_iPrefHeight = pvi->bmiHeader.biHeight; - return S_OK; -} - -STDMETHODIMP CaptureSource::CaptureStream::GetFormat(AM_MEDIA_TYPE **ppmt) -{ - if(ppmt == NULL) { - return E_POINTER; - } - /* - HRESULT hr = GetMediaType(& m_mt); - if(FAILED(hr)) { - return hr; - }*/ - - *ppmt = CreateMediaType(&m_mt); - return S_OK; -} - -STDMETHODIMP CaptureSource::CaptureStream::GetNumberOfCapabilities(int *piCount, int *piSize) -{ - if(piCount == NULL || piSize == NULL) { - return E_POINTER; - } - *piCount = 1;// 1; - *piSize = sizeof(VIDEO_STREAM_CONFIG_CAPS); - return S_OK; -} - -STDMETHODIMP CaptureSource::CaptureStream::GetStreamCaps(int iIndex, AM_MEDIA_TYPE **ppmt, BYTE *pSCC) -{ - if(ppmt == NULL || pSCC == NULL) { - return E_POINTER; - } - -// if (iIndex == 0) iIndex = 4; - CMediaType mt; - HRESULT hr = GetMediaType(/*iIndex,*/ & mt); - if(FAILED(hr)) { - return hr; - } - *ppmt = CreateMediaType(& mt); - - VIDEO_STREAM_CONFIG_CAPS* pCaps = (VIDEO_STREAM_CONFIG_CAPS*) pSCC; - ZeroMemory(pCaps, sizeof(VIDEO_STREAM_CONFIG_CAPS)); - - pCaps->guid = FORMAT_VideoInfo; - pCaps->VideoStandard = 0; - pCaps->InputSize.cx = MAX_WIDTH; - pCaps->InputSize.cy = MAX_HEIGHT; - pCaps->MinCroppingSize.cx = MIN_WIDTH; - pCaps->MinCroppingSize.cy = MIN_HEIGHT; - pCaps->MaxCroppingSize.cx = MIN_WIDTH; - pCaps->MaxCroppingSize.cy = MIN_HEIGHT; - pCaps->CropGranularityX = MIN_WIDTH; - pCaps->CropGranularityY = MIN_HEIGHT; - pCaps->CropAlignX = 1; - pCaps->CropAlignY = 1; - pCaps->MinOutputSize.cx = MIN_WIDTH; - pCaps->MinOutputSize.cy = MIN_HEIGHT; - pCaps->MaxOutputSize.cx = MAX_WIDTH; - pCaps->MaxOutputSize.cy = MAX_HEIGHT; - pCaps->OutputGranularityX = 1; - pCaps->OutputGranularityY = 1; - pCaps->StretchTapsX = 0; - pCaps->StretchTapsY = 0; - pCaps->ShrinkTapsX = 0; - pCaps->ShrinkTapsY = 0; - pCaps->MinFrameInterval = MIN_FRAME_INTERVAL; - pCaps->MaxFrameInterval = MAX_FRAME_INTERVAL; - pCaps->MinBitsPerSecond = MIN_WIDTH * MIN_HEIGHT * 3 * 8 * MIN_FPS; - pCaps->MaxBitsPerSecond = MAX_WIDTH * MAX_HEIGHT * 3 * 8 * MAX_FPS; - - return S_OK; -} - -HRESULT CaptureSource::CaptureStream::GetMediaType(CMediaType *pMediaType) -{ - int iPos = 1; - if (iPos < 0) return E_INVALIDARG; - if (iPos > 2) return VFW_S_NO_MORE_ITEMS; - - if(pMediaType == NULL) { - return E_POINTER; - } - - struct MediaType - { - MediaType(){} - MediaType(int w,int h):width(w),height(h){} - int width, height; - }; - - static MediaType _media[] = { - MediaType(640, 480), - MediaType(1280, 720), - MediaType(1920, 1080), - }; - - VIDEOINFO *pvi = (VIDEOINFO *)pMediaType->AllocFormatBuffer(sizeof(VIDEOINFO)); - ZeroMemory(pvi, sizeof(VIDEOINFO)); - pvi->AvgTimePerFrame = m_avgTimePerFrame; - BITMAPINFOHEADER *pBmi = &(pvi->bmiHeader); - pBmi->biSize = sizeof(BITMAPINFOHEADER); - pBmi->biWidth = _media[iPos].width;// m_iPrefWidth; - pBmi->biHeight = _media[iPos].height;// m_iPrefHeight; - pBmi->biPlanes = 1; - pBmi->biBitCount = 24; - pBmi->biCompression = BI_RGB; - pvi->bmiHeader.biSizeImage = DIBSIZE(pvi->bmiHeader); - - pMediaType->SetType(&MEDIATYPE_Video); - pMediaType->SetFormatType(&FORMAT_VideoInfo); - const GUID subtype=GetBitmapSubtype(&pvi->bmiHeader); - pMediaType->SetSubtype(&subtype); - pMediaType->SetSampleSize(DIBSIZE(*pBmi)); - pMediaType->SetTemporalCompression(FALSE); - return S_OK; -} - -HRESULT CaptureSource::CaptureStream::OnThreadStartPlay(void) -{ - m_llTime = 0; - m_llFrame = 0; - m_llLastSampleTime = -1; - - return CSourceStream::OnThreadStartPlay(); -} - -HRESULT CaptureSource::CaptureStream::GetScaling(int width, int height, double* pScaling, double* pOffsetX, double* pOffsetY) -{ - if(pScaling == NULL || pOffsetX == NULL || pOffsetY == NULL) { - return E_POINTER; - } - VIDEOINFO *pvi = (VIDEOINFO*) m_mt.Format(); - BITMAPINFOHEADER *pBmi = &(pvi->bmiHeader); - - double aw = pBmi->biWidth; - double ah = pBmi->biHeight; - double sw = width; - double sh = height; - double wscaling = aw / sw; - double hscaling = ah / sh; - double scaling = min(wscaling, hscaling); - if(scaling < 0.0001) { - return E_UNEXPECTED; - } - - double dw = scaling * sw; - double dh = scaling * sh; - double ax = (aw - dw) / 2.0; - double ay = (ah - dh) / 2.0; - *pScaling = scaling; - *pOffsetX = ax; - *pOffsetY = ay; - return S_OK; -} -////////////////////////////////////////////////////////////////////////// - -HRESULT CaptureSource::CaptureStream::StartAt( - /* [annotation][in] */ - _In_opt_ const REFERENCE_TIME *ptStart, - /* [in] */ DWORD dwCookie) -{ - - return NOERROR; -} - - HRESULT CaptureSource::CaptureStream::StopAt( - /* [annotation][in] */ - _In_opt_ const REFERENCE_TIME *ptStop, - /* [in] */ BOOL bSendExtra, - /* [in] */ DWORD dwCookie) - { - - return NOERROR; - } - - HRESULT CaptureSource::CaptureStream::GetInfo( - /* [annotation][out] */ - _Out_ AM_STREAM_INFO *pInfo) - { - return NOERROR; - - } -//// - - HRESULT CaptureSource::CaptureStream::GetPushSourceFlags( - /* [annotation][out] */ - _Out_ ULONG *pFlags) - { - *pFlags = AM_PUSHSOURCECAPS_INTERNAL_RM; - return NOERROR; - - } - - HRESULT CaptureSource::CaptureStream::SetPushSourceFlags( - /* [in] */ ULONG Flags) - { - return E_NOTIMPL; - - } - - HRESULT CaptureSource::CaptureStream::SetStreamOffset( - /* [in] */ REFERENCE_TIME rtOffset) - { - return NOERROR; - - } - - HRESULT CaptureSource::CaptureStream::GetStreamOffset( - /* [annotation][out] */ - _Out_ REFERENCE_TIME *prtOffset) - { - *prtOffset = 0; - return NOERROR; - } - - HRESULT CaptureSource::CaptureStream::GetMaxStreamOffset( - /* [annotation][out] */ - _Out_ REFERENCE_TIME *prtMaxOffset) - { - *prtMaxOffset = 0; - return NOERROR; - - } - - HRESULT CaptureSource::CaptureStream::SetMaxStreamOffset( - /* [in] */ REFERENCE_TIME rtMaxOffset) - { - return NOERROR; - } \ No newline at end of file diff --git a/UnityWebcam/UnityCamService/CaptureSource.h b/UnityWebcam/UnityCamService/CaptureSource.h deleted file mode 100644 index 97c0c83..0000000 --- a/UnityWebcam/UnityCamService/CaptureSource.h +++ /dev/null @@ -1,161 +0,0 @@ -#pragma once - -#include "Globals.h" -#include "ICamSource.h" - -#include -#include - -class CaptureSharedMemory; - -extern const AMOVIESETUP_FILTER sudCaptureSource; -extern const AMOVIESETUP_PIN sudCaptureSourceOut; -#define DECLARE_PTR(type, ptr, expr) type* ptr = (type*)(expr); - -class CaptureSource : - public CSource, public IQualityControl, public ICamSource -{ -public: - - static CUnknown * WINAPI CreateInstance(LPUNKNOWN lpunk, HRESULT *phr); - -private: - - CaptureSource(LPUNKNOWN lpunk, HRESULT* phr); - -public: - - virtual ~CaptureSource(void); - - DECLARE_IUNKNOWN; - - virtual STDMETHODIMP NonDelegatingQueryInterface(REFIID riid, void ** ppv); - - virtual STDMETHODIMP Notify(IBaseFilter *pSelf, Quality q); - - virtual STDMETHODIMP SetSink(IQualityControl *piqc); - -private: - HRESULT Init(CaptureSharedMemory* pReceiver, int fps); - - class CaptureStream : public CSourceStream, public IAMStreamControl, public IKsPropertySet, public IAMStreamConfig, public IAMPushSource, public IAMLatency - { - public: - - CaptureStream(CaptureSource* pOwner, CaptureSharedMemory* pReceiver, int fps, HRESULT* phr); - - virtual ~CaptureStream(); - - ////////////////////////////////////////////////////////////////////////// - // IUnknown - ////////////////////////////////////////////////////////////////////////// - STDMETHODIMP QueryInterface(REFIID riid, void **ppv); - STDMETHODIMP_(ULONG) AddRef() { return GetOwner()->AddRef(); } - STDMETHODIMP_(ULONG) Release() { return GetOwner()->Release(); } - - virtual STDMETHODIMP NonDelegatingQueryInterface(REFIID riid, void ** ppv); - - virtual STDMETHODIMP QuerySupported(REFGUID rguidPropSet, ULONG ulId, PULONG pulTypeSupport); - - virtual STDMETHODIMP Get(REFGUID rguidPropSet, ULONG ulId, LPVOID pInstanceData, ULONG ulInstanceLength, LPVOID pPropertyData, ULONG ulDataLength, PULONG pulBytesReturned); - - virtual STDMETHODIMP Set(REFGUID rguidPropSet, ULONG ulId, LPVOID pInstanceData, ULONG ulInstanceLength, LPVOID pPropertyData, ULONG ulDataLength); - - virtual HRESULT FillBuffer(IMediaSample *pSamp); - - virtual HRESULT DecideBufferSize(IMemAllocator * pAlloc, ALLOCATOR_PROPERTIES * pRequest); - - virtual STDMETHODIMP Notify(IBaseFilter *pSelf, Quality q); - - virtual STDMETHODIMP SetSink(IQualityControl *piqc); - - virtual STDMETHODIMP SetFormat(AM_MEDIA_TYPE *pmt); - - virtual STDMETHODIMP GetFormat(AM_MEDIA_TYPE **ppmt); - - virtual STDMETHODIMP GetNumberOfCapabilities(int *piCount, int *piSize); - - virtual STDMETHODIMP GetStreamCaps(int iIndex, AM_MEDIA_TYPE **ppmt, BYTE *pSCC); - - HRESULT CheckMediaType(const CMediaType *pMediaType); - HRESULT SetMediaType(const CMediaType *pmt); - - ////////////////////////////////////////////////////////////////////////// - - virtual HRESULT STDMETHODCALLTYPE StartAt( - /* [annotation][in] */ - _In_opt_ const REFERENCE_TIME *ptStart, - /* [in] */ DWORD dwCookie) ; - - virtual HRESULT STDMETHODCALLTYPE StopAt( - /* [annotation][in] */ - _In_opt_ const REFERENCE_TIME *ptStop, - /* [in] */ BOOL bSendExtra, - /* [in] */ DWORD dwCookie) ; - - virtual HRESULT STDMETHODCALLTYPE GetInfo( - /* [annotation][out] */ - _Out_ AM_STREAM_INFO *pInfo) ; - -// IAMPushSource - - virtual HRESULT STDMETHODCALLTYPE GetPushSourceFlags( - /* [annotation][out] */ - _Out_ ULONG *pFlags) ; - - virtual HRESULT STDMETHODCALLTYPE SetPushSourceFlags( - /* [in] */ ULONG Flags) ; - - virtual HRESULT STDMETHODCALLTYPE SetStreamOffset( - /* [in] */ REFERENCE_TIME rtOffset) ; - - virtual HRESULT STDMETHODCALLTYPE GetStreamOffset( - /* [annotation][out] */ - _Out_ REFERENCE_TIME *prtOffset) ; - - virtual HRESULT STDMETHODCALLTYPE GetMaxStreamOffset( - /* [annotation][out] */ - _Out_ REFERENCE_TIME *prtMaxOffset) ; - - virtual HRESULT STDMETHODCALLTYPE SetMaxStreamOffset( - /* [in] */ REFERENCE_TIME rtMaxOffset) ; - - - virtual HRESULT STDMETHODCALLTYPE GetLatency( - /* [annotation][in] */ - _Out_ REFERENCE_TIME *prtLatency) - { - - return NOERROR; - } - protected: - - virtual HRESULT GetMediaType(/*int iPos,*/CMediaType *pMediaType); - - virtual HRESULT OnThreadStartPlay(void); - - private: - long long oldStartTime_; - - std::chrono::system_clock::time_point lastTime; - std::function fpsChecker; - HRESULT GetScaling(int width, int height, double* pScaling, double* pOffsetX, double* pOffsetY); - - LONGLONG m_llTime; - - LONGLONG m_llFrame; - - REFERENCE_TIME m_avgTimePerFrame; - - int m_iPrefWidth; - - int m_iPrefHeight; - CMediaType m_mt; - - LONGLONG m_llLastSampleTime; - - CaptureSharedMemory* m_pReceiver; - - }; - -}; diff --git a/UnityWebcam/UnityCamService/Globals.h b/UnityWebcam/UnityCamService/Globals.h deleted file mode 100644 index fe52bca..0000000 --- a/UnityWebcam/UnityCamService/Globals.h +++ /dev/null @@ -1,14 +0,0 @@ -#pragma once - -#include - - -#define CaptureSourceName L"UnityCam" - -DEFINE_GUID(CLSID_UnityCamService, - 0x5c2cd55c, 0x92ad, 0x4999, 0x86, 0x66, 0x91, 0x2b, 0xd3, 0xe7, 0x0, 0x1); - -#define CS_EVENT_Base_WRITE CaptureSourceName L"_Write" -#define CS_EVENT_Base_READ CaptureSourceName L"_Read" -#define CS_SHARED_Base_PATH CaptureSourceName L"_Data" - \ No newline at end of file diff --git a/UnityWebcam/UnityCamService/ICamSource.h b/UnityWebcam/UnityCamService/ICamSource.h deleted file mode 100644 index 602368e..0000000 --- a/UnityWebcam/UnityCamService/ICamSource.h +++ /dev/null @@ -1,8 +0,0 @@ -#pragma once - -DEFINE_GUID(IID_ICamSource, -0xbeffc828, 0xdd38, 0x43b8, 0xab, 0x18, 0x88, 0x9, 0xf9, 0x91, 0x7d, 0x29); - -DECLARE_INTERFACE_(ICamSource, IUnknown) -{ -}; diff --git a/UnityWebcam/UnityCamService/ReadMe.txt b/UnityWebcam/UnityCamService/ReadMe.txt deleted file mode 100644 index a7308a0..0000000 --- a/UnityWebcam/UnityCamService/ReadMe.txt +++ /dev/null @@ -1,48 +0,0 @@ -======================================================================== - DYNAMIC LINK LIBRARY : UnityCapture Project Overview -======================================================================== - -AppWizard has created this UnityCapture DLL for you. - -This file contains a summary of what you will find in each of the files that -make up your UnityCapture application. - - -UnityCapture.vcxproj - This is the main project file for VC++ projects generated using an Application Wizard. - It contains information about the version of Visual C++ that generated the file, and - information about the platforms, configurations, and project features selected with the - Application Wizard. - -UnityCapture.vcxproj.filters - This is the filters file for VC++ projects generated using an Application Wizard. - It contains information about the association between the files in your project - and the filters. This association is used in the IDE to show grouping of files with - similar extensions under a specific node (for e.g. ".cpp" files are associated with the - "Source Files" filter). - -UnityCapture.cpp - This is the main DLL source file. - - When created, this DLL does not export any symbols. As a result, it - will not produce a .lib file when it is built. If you wish this project - to be a project dependency of some other project, you will either need to - add code to export some symbols from the DLL so that an export library - will be produced, or you can set the Ignore Input Library property to Yes - on the General propert page of the Linker folder in the project's Property - Pages dialog box. - -///////////////////////////////////////////////////////////////////////////// -Other standard files: - -StdAfx.h, StdAfx.cpp - These files are used to build a precompiled header (PCH) file - named UnityCapture.pch and a precompiled types file named StdAfx.obj. - -///////////////////////////////////////////////////////////////////////////// -Other notes: - -AppWizard uses "TODO:" comments to indicate parts of the source code you -should add to or customize. - -///////////////////////////////////////////////////////////////////////////// diff --git a/UnityWebcam/UnityCamService/SharedMemData.h b/UnityWebcam/UnityCamService/SharedMemData.h deleted file mode 100644 index 30afc23..0000000 --- a/UnityWebcam/UnityCamService/SharedMemData.h +++ /dev/null @@ -1,18 +0,0 @@ -#pragma once - -#include - -struct SharedMemHeader { - - int32_t maxSize; - int32_t size; - - unsigned char bufferPtr[1]; - -}; - -struct BufferHeader { - int32_t width; - int32_t height; - LONGLONG timestamp; -}; \ No newline at end of file diff --git a/UnityWebcam/UnityCamService/SharedMutex.h b/UnityWebcam/UnityCamService/SharedMutex.h deleted file mode 100644 index 9aab610..0000000 --- a/UnityWebcam/UnityCamService/SharedMutex.h +++ /dev/null @@ -1,65 +0,0 @@ -#pragma once - -class SharedMutex -{ -public: - - SharedMutex(const wchar_t* name, bool create, HRESULT* phr) - { - if(create) { - m_crit = CreateMutex(NULL, FALSE, name); - }else{ - m_crit = OpenMutex(SYNCHRONIZE, FALSE, name); - } - if(m_crit == NULL) { - *phr = E_UNEXPECTED; - } - }; - - virtual ~SharedMutex(void) - { - if(m_crit != NULL) { - CloseHandle(m_crit); - m_crit = NULL; - } - }; - - void Lock() - { - WaitForSingleObject(m_crit, INFINITE); - }; - - void Unlock() - { - ReleaseMutex(m_crit); - }; - -private: - - HANDLE m_crit; - -}; - -class CriticalSection -{ -public: - - CriticalSection(SharedMutex* pMutex) - { - pMutex->Lock(); - m_pMutex = pMutex; - }; - - virtual ~CriticalSection() - { - if (m_pMutex != NULL) { - m_pMutex->Unlock(); - m_pMutex = NULL; - } - }; - -private: - - SharedMutex* m_pMutex; - -}; diff --git a/UnityWebcam/UnityCamService/UnityCamService.def b/UnityWebcam/UnityCamService/UnityCamService.def deleted file mode 100644 index 783b96a..0000000 --- a/UnityWebcam/UnityCamService/UnityCamService.def +++ /dev/null @@ -1,8 +0,0 @@ -LIBRARY "UnityCaptureService" - -EXPORTS - DllMain PRIVATE - DllRegisterServer PRIVATE - DllUnregisterServer PRIVATE - DllGetClassObject PRIVATE - DllCanUnloadNow PRIVATE \ No newline at end of file diff --git a/UnityWebcam/UnityCamService/UnityCamService.vcxproj b/UnityWebcam/UnityCamService/UnityCamService.vcxproj deleted file mode 100644 index f7fe12a..0000000 --- a/UnityWebcam/UnityCamService/UnityCamService.vcxproj +++ /dev/null @@ -1,224 +0,0 @@ - - - - - Debug - Win32 - - - Debug - x64 - - - Release - Win32 - - - Release - x64 - - - - {3D0A9889-9EC1-4012-9382-4FE1EB610D17} - ycapture - Win32Proj - UnityCamService - - - - DynamicLibrary - v120 - Unicode - true - - - DynamicLibrary - v120 - Unicode - true - - - DynamicLibrary - v120 - Unicode - - - DynamicLibrary - v120 - Unicode - - - - - - - - - - - - - - - - - - - <_ProjectFileVersion>10.0.20506.1 - - - ..\$(Platform)\$(Configuration)\ - ..\$(Platform)\$(Configuration)\ - true - C:\Program Files\Microsoft SDKs\Windows\v7.1\Samples\multimedia\directshow\baseclasses;$(IncludePath) - C:\Program Files\Microsoft SDKs\Windows\v7.1\Samples\multimedia\directshow\baseclasses\Debug;$(LibraryPath) - - - true - ..\$(Platform)\$(Configuration)\ - ..\$(Platform)\$(Configuration)\ - - - ..\$(Platform)\$(Configuration)\ - ..\$(Platform)\$(Configuration)\ - false - C:\Program Files\Microsoft SDKs\Windows\v7.1\Samples\multimedia\directshow\baseclasses;$(IncludePath) - C:\Program Files\Microsoft SDKs\Windows\v7.1\Samples\multimedia\directshow\baseclasses\Release;$(LibraryPath) - - - false - C:\Program Files\Microsoft SDKs\Windows\v7.1\Samples\multimedia\directshow\baseclasses;$(IncludePath) - C:\Program Files\Microsoft SDKs\Windows\v7.1\Samples\multimedia\directshow\baseclasses\x64\Release;$(LibraryPath) - ..\$(Platform)\$(Configuration)\ - ..\$(Platform)\$(Configuration)\ - - - - Disabled - .\includes;%(AdditionalIncludeDirectories) - Win32;_DEBUG;_WINDOWS;_USRDLL;YCAPTURE_EXPORTS;%(PreprocessorDefinitions) - true - EnableFastChecks - MultiThreadedDebugDLL - Use - Level3 - EditAndContinue - - - strmbasd.lib;strmiids.lib;winmm.lib;%(AdditionalDependencies) - .\libs\x86;%(AdditionalLibraryDirectories) - UnityCamService.def - true - Windows - MachineX86 - - - - - Disabled - .\includes\;%(AdditionalIncludeDirectories) - Win32;_DEBUG;_WINDOWS;_USRDLL;YCAPTURE_EXPORTS;%(PreprocessorDefinitions) - EnableFastChecks - MultiThreadedDebugDLL - Use - Level3 - ProgramDatabase - - - strmbasd.lib;winmm.lib;%(AdditionalDependencies) - .\libs\x64;%(AdditionalLibraryDirectories) - UnityCamService.def - true - Windows - - - - - MaxSpeed - true - .\includes;%(AdditionalIncludeDirectories) - Win32;NDEBUG;_WINDOWS;_USRDLL;YCAPTURE_EXPORTS;%(PreprocessorDefinitions) - MultiThreadedDLL - true - Use - Level3 - ProgramDatabase - - - strmbase.lib;strmiids.lib;winmm.lib;%(AdditionalDependencies) - .\libs\x86;%(AdditionalLibraryDirectories) - UnityCamService.def - true - Windows - true - true - MachineX86 - - - - - MaxSpeed - true - .\includes\;%(AdditionalIncludeDirectories) - Win32;NDEBUG;_WINDOWS;_USRDLL;YCAPTURE_EXPORTS;%(PreprocessorDefinitions) - MultiThreadedDLL - true - Use - Level3 - ProgramDatabase - - - strmbase.lib;strmiids.lib;winmm.lib;%(AdditionalDependencies) - .\libs\x64;%(AdditionalLibraryDirectories) - UnityCamService.def - true - Windows - true - true - - - - - - - - - - false - false - - - - - false - false - - - - Create - Create - Create - Create - - - - - - - - - - - - - - - - - - - - - - - \ No newline at end of file diff --git a/UnityWebcam/UnityCamService/dllmain.cpp b/UnityWebcam/UnityCamService/dllmain.cpp deleted file mode 100644 index d393cd9..0000000 --- a/UnityWebcam/UnityCamService/dllmain.cpp +++ /dev/null @@ -1,67 +0,0 @@ - - - -#include "stdafx.h" - -#include - - -// -// DllEntryPoint -// -extern "C" BOOL WINAPI DllEntryPoint(HINSTANCE, ULONG, LPVOID); - - - -//http://stackoverflow.com/questions/6646702/get-file-name-without-extension -#ifdef UNICODE //Test to see if we're using wchar_ts or not. -typedef std::wstring StringType; -#else -typedef std::string StringType; -#endif - -StringType GetBaseFilename(const TCHAR *filename) -{ - StringType fName(filename); - size_t pos = fName.rfind(L"\\"); - if (pos != StringType::npos) - { - fName = fName.substr(pos+1, fName.length()-pos); - } - - - pos = fName.rfind(L"."); - if (pos == StringType::npos) //No extension. - return fName; - - if (pos == 0) //. is at the front. Not an extension. - return fName; - - return fName.substr(0, pos); -} - - -BOOL APIENTRY DllMain( HMODULE hModule, - DWORD ul_reason_for_call, - LPVOID lpReserved - ) -{ - //TCHAR ModuleName[256]; - //::GetModuleFileName(hModule, ModuleName, 255); - - //CaptureSourceName= GetBaseFilename(ModuleName); - switch (ul_reason_for_call) - { - - case DLL_PROCESS_ATTACH: - //MessageBox(0, L" DLL_PROCESS_ATTACH", L"", 0); - break; - case DLL_THREAD_DETACH: - //MessageBox(0, L" DLL_THREAD_DETACH", L"", 0); - break; - case DLL_PROCESS_DETACH: - //MessageBox(0, L" DLL_PROCESS_DETACH", L"", 0); - break; - } - return DllEntryPoint((HINSTANCE)(hModule), ul_reason_for_call, lpReserved); -} diff --git a/UnityWebcam/UnityCamService/includes/amextra.h b/UnityWebcam/UnityCamService/includes/amextra.h deleted file mode 100644 index 3caf64c..0000000 --- a/UnityWebcam/UnityCamService/includes/amextra.h +++ /dev/null @@ -1,56 +0,0 @@ -//------------------------------------------------------------------------------ -// File: AMExtra.h -// -// Desc: DirectShow base classes. -// -// Copyright (c) 1992-2001 Microsoft Corporation. All rights reserved. -//------------------------------------------------------------------------------ - - -#ifndef __AMEXTRA__ -#define __AMEXTRA__ - -// Simple rendered input pin -// -// NOTE if your filter queues stuff before rendering then it may not be -// appropriate to use this class -// -// In that case queue the end of stream condition until the last sample -// is actually rendered and flush the condition appropriately - -class CRenderedInputPin : public CBaseInputPin -{ -public: - - CRenderedInputPin(__in_opt LPCTSTR pObjectName, - __in CBaseFilter *pFilter, - __in CCritSec *pLock, - __inout HRESULT *phr, - __in_opt LPCWSTR pName); -#ifdef UNICODE - CRenderedInputPin(__in_opt LPCSTR pObjectName, - __in CBaseFilter *pFilter, - __in CCritSec *pLock, - __inout HRESULT *phr, - __in_opt LPCWSTR pName); -#endif - - // Override methods to track end of stream state - STDMETHODIMP EndOfStream(); - STDMETHODIMP EndFlush(); - - HRESULT Active(); - HRESULT Run(REFERENCE_TIME tStart); - -protected: - - // Member variables to track state - BOOL m_bAtEndOfStream; // Set by EndOfStream - BOOL m_bCompleteNotified; // Set when we notify for EC_COMPLETE - -private: - void DoCompleteHandling(); -}; - -#endif // __AMEXTRA__ - diff --git a/UnityWebcam/UnityCamService/includes/amfilter.h b/UnityWebcam/UnityCamService/includes/amfilter.h deleted file mode 100644 index 8646bc0..0000000 --- a/UnityWebcam/UnityCamService/includes/amfilter.h +++ /dev/null @@ -1,1587 +0,0 @@ -//------------------------------------------------------------------------------ -// File: AMFilter.h -// -// Desc: DirectShow base classes - efines class hierarchy for streams -// architecture. -// -// Copyright (c) 1992-2001 Microsoft Corporation. All rights reserved. -//------------------------------------------------------------------------------ - - -#ifndef __FILTER__ -#define __FILTER__ - -/* The following classes are declared in this header: */ - -class CBaseMediaFilter; // IMediaFilter support -class CBaseFilter; // IBaseFilter,IMediaFilter support -class CBasePin; // Abstract base class for IPin interface -class CEnumPins; // Enumerate input and output pins -class CEnumMediaTypes; // Enumerate the pin's preferred formats -class CBaseOutputPin; // Adds data provider member functions -class CBaseInputPin; // Implements IMemInputPin interface -class CMediaSample; // Basic transport unit for IMemInputPin -class CBaseAllocator; // General list guff for most allocators -class CMemAllocator; // Implements memory buffer allocation - - -//===================================================================== -//===================================================================== -// -// QueryFilterInfo and QueryPinInfo AddRef the interface pointers -// they return. You can use the macro below to release the interface. -// -//===================================================================== -//===================================================================== - -#define QueryFilterInfoReleaseGraph(fi) if ((fi).pGraph) (fi).pGraph->Release(); - -#define QueryPinInfoReleaseFilter(pi) if ((pi).pFilter) (pi).pFilter->Release(); - -//===================================================================== -//===================================================================== -// Defines CBaseMediaFilter -// -// Abstract base class implementing IMediaFilter. -// -// Typically you will derive your filter from CBaseFilter rather than -// this, unless you are implementing an object such as a plug-in -// distributor that needs to support IMediaFilter but not IBaseFilter. -// -// Note that IMediaFilter is derived from IPersist to allow query of -// class id. -//===================================================================== -//===================================================================== - -class AM_NOVTABLE CBaseMediaFilter : public CUnknown, - public IMediaFilter -{ - -protected: - - FILTER_STATE m_State; // current state: running, paused - IReferenceClock *m_pClock; // this filter's reference clock - // note: all filters in a filter graph use the same clock - - // offset from stream time to reference time - CRefTime m_tStart; - - CLSID m_clsid; // This filters clsid - // used for serialization - CCritSec *m_pLock; // Object we use for locking - -public: - - CBaseMediaFilter( - __in_opt LPCTSTR pName, - __inout_opt LPUNKNOWN pUnk, - __in CCritSec *pLock, - REFCLSID clsid); - - virtual ~CBaseMediaFilter(); - - DECLARE_IUNKNOWN - - // override this to say what interfaces we support where - STDMETHODIMP NonDelegatingQueryInterface(REFIID riid, __deref_out void ** ppv); - - // - // --- IPersist method --- - // - - STDMETHODIMP GetClassID(__out CLSID *pClsID); - - // --- IMediaFilter methods --- - - STDMETHODIMP GetState(DWORD dwMSecs, __out FILTER_STATE *State); - - STDMETHODIMP SetSyncSource(__inout_opt IReferenceClock *pClock); - - STDMETHODIMP GetSyncSource(__deref_out_opt IReferenceClock **pClock); - - // default implementation of Stop and Pause just record the - // state. Override to activate or de-activate your filter. - // Note that Run when called from Stopped state will call Pause - // to ensure activation, so if you are a source or transform - // you will probably not need to override Run. - STDMETHODIMP Stop(); - STDMETHODIMP Pause(); - - - // the start parameter is the difference to be added to the - // sample's stream time to get the reference time for - // its presentation - STDMETHODIMP Run(REFERENCE_TIME tStart); - - // --- helper methods --- - - // return the current stream time - ie find out what - // stream time should be appearing now - virtual HRESULT StreamTime(CRefTime& rtStream); - - // Is the filter currently active? (running or paused) - BOOL IsActive() { - CAutoLock cObjectLock(m_pLock); - return ((m_State == State_Paused) || (m_State == State_Running)); - }; -}; - -//===================================================================== -//===================================================================== -// Defines CBaseFilter -// -// An abstract class providing basic IBaseFilter support for pin -// enumeration and filter information reading. -// -// We cannot derive from CBaseMediaFilter since methods in IMediaFilter -// are also in IBaseFilter and would be ambiguous. Since much of the code -// assumes that they derive from a class that has m_State and other state -// directly available, we duplicate code from CBaseMediaFilter rather than -// having a member variable. -// -// Derive your filter from this, or from a derived object such as -// CTransformFilter. -//===================================================================== -//===================================================================== - - -class AM_NOVTABLE CBaseFilter : public CUnknown, // Handles an IUnknown - public IBaseFilter, // The Filter Interface - public IAMovieSetup // For un/registration -{ - -friend class CBasePin; - -protected: - FILTER_STATE m_State; // current state: running, paused - IReferenceClock *m_pClock; // this graph's ref clock - CRefTime m_tStart; // offset from stream time to reference time - CLSID m_clsid; // This filters clsid - // used for serialization - CCritSec *m_pLock; // Object we use for locking - - WCHAR *m_pName; // Full filter name - IFilterGraph *m_pGraph; // Graph we belong to - IMediaEventSink *m_pSink; // Called with notify events - LONG m_PinVersion; // Current pin version - -public: - - CBaseFilter( - __in_opt LPCTSTR pName, // Object description - __inout_opt LPUNKNOWN pUnk, // IUnknown of delegating object - __in CCritSec *pLock, // Object who maintains lock - REFCLSID clsid); // The clsid to be used to serialize this filter - - CBaseFilter( - __in_opt LPCTSTR pName, // Object description - __in_opt LPUNKNOWN pUnk, // IUnknown of delegating object - __in CCritSec *pLock, // Object who maintains lock - REFCLSID clsid, // The clsid to be used to serialize this filter - __inout HRESULT *phr); // General OLE return code -#ifdef UNICODE - CBaseFilter( - __in_opt LPCSTR pName, // Object description - __in_opt LPUNKNOWN pUnk, // IUnknown of delegating object - __in CCritSec *pLock, // Object who maintains lock - REFCLSID clsid); // The clsid to be used to serialize this filter - - CBaseFilter( - __in_opt LPCSTR pName, // Object description - __in_opt LPUNKNOWN pUnk, // IUnknown of delegating object - __in CCritSec *pLock, // Object who maintains lock - REFCLSID clsid, // The clsid to be used to serialize this filter - __inout HRESULT *phr); // General OLE return code -#endif - ~CBaseFilter(); - - DECLARE_IUNKNOWN - - // override this to say what interfaces we support where - STDMETHODIMP NonDelegatingQueryInterface(REFIID riid, __deref_out void ** ppv); -#ifdef DEBUG - STDMETHODIMP_(ULONG) NonDelegatingRelease(); -#endif - - // - // --- IPersist method --- - // - - STDMETHODIMP GetClassID(__out CLSID *pClsID); - - // --- IMediaFilter methods --- - - STDMETHODIMP GetState(DWORD dwMSecs, __out FILTER_STATE *State); - - STDMETHODIMP SetSyncSource(__in_opt IReferenceClock *pClock); - - STDMETHODIMP GetSyncSource(__deref_out_opt IReferenceClock **pClock); - - - // override Stop and Pause so we can activate the pins. - // Note that Run will call Pause first if activation needed. - // Override these if you want to activate your filter rather than - // your pins. - STDMETHODIMP Stop(); - STDMETHODIMP Pause(); - - // the start parameter is the difference to be added to the - // sample's stream time to get the reference time for - // its presentation - STDMETHODIMP Run(REFERENCE_TIME tStart); - - // --- helper methods --- - - // return the current stream time - ie find out what - // stream time should be appearing now - virtual HRESULT StreamTime(CRefTime& rtStream); - - // Is the filter currently active? - BOOL IsActive() { - CAutoLock cObjectLock(m_pLock); - return ((m_State == State_Paused) || (m_State == State_Running)); - }; - - // Is this filter stopped (without locking) - BOOL IsStopped() { - return (m_State == State_Stopped); - }; - - // - // --- IBaseFilter methods --- - // - - // pin enumerator - STDMETHODIMP EnumPins( - __deref_out IEnumPins ** ppEnum); - - - // default behaviour of FindPin assumes pin ids are their names - STDMETHODIMP FindPin( - LPCWSTR Id, - __deref_out IPin ** ppPin - ); - - STDMETHODIMP QueryFilterInfo( - __out FILTER_INFO * pInfo); - - STDMETHODIMP JoinFilterGraph( - __inout_opt IFilterGraph * pGraph, - __in_opt LPCWSTR pName); - - // return a Vendor information string. Optional - may return E_NOTIMPL. - // memory returned should be freed using CoTaskMemFree - // default implementation returns E_NOTIMPL - STDMETHODIMP QueryVendorInfo( - __deref_out LPWSTR* pVendorInfo - ); - - // --- helper methods --- - - // send an event notification to the filter graph if we know about it. - // returns S_OK if delivered, S_FALSE if the filter graph does not sink - // events, or an error otherwise. - HRESULT NotifyEvent( - long EventCode, - LONG_PTR EventParam1, - LONG_PTR EventParam2); - - // return the filter graph we belong to - __out_opt IFilterGraph *GetFilterGraph() { - return m_pGraph; - } - - // Request reconnect - // pPin is the pin to reconnect - // pmt is the type to reconnect with - can be NULL - // Calls ReconnectEx on the filter graph - HRESULT ReconnectPin(IPin *pPin, __in_opt AM_MEDIA_TYPE const *pmt); - - // find out the current pin version (used by enumerators) - virtual LONG GetPinVersion(); - void IncrementPinVersion(); - - // you need to supply these to access the pins from the enumerator - // and for default Stop and Pause/Run activation. - virtual int GetPinCount() PURE; - virtual CBasePin *GetPin(int n) PURE; - - // --- IAMovieSetup methods --- - - STDMETHODIMP Register(); // ask filter to register itself - STDMETHODIMP Unregister(); // and unregister itself - - // --- setup helper methods --- - // (override to return filters setup data) - - virtual __out_opt LPAMOVIESETUP_FILTER GetSetupData(){ return NULL; } - -}; - - -//===================================================================== -//===================================================================== -// Defines CBasePin -// -// Abstract class that supports the basics of IPin -//===================================================================== -//===================================================================== - -class AM_NOVTABLE CBasePin : public CUnknown, public IPin, public IQualityControl -{ - -protected: - - WCHAR * m_pName; // This pin's name - IPin *m_Connected; // Pin we have connected to - PIN_DIRECTION m_dir; // Direction of this pin - CCritSec *m_pLock; // Object we use for locking - bool m_bRunTimeError; // Run time error generated - bool m_bCanReconnectWhenActive; // OK to reconnect when active - bool m_bTryMyTypesFirst; // When connecting enumerate - // this pin's types first - CBaseFilter *m_pFilter; // Filter we were created by - IQualityControl *m_pQSink; // Target for Quality messages - LONG m_TypeVersion; // Holds current type version - CMediaType m_mt; // Media type of connection - - CRefTime m_tStart; // time from NewSegment call - CRefTime m_tStop; // time from NewSegment - double m_dRate; // rate from NewSegment - -#ifdef DEBUG - LONG m_cRef; // Ref count tracing -#endif - - // displays pin connection information - -#ifdef DEBUG - void DisplayPinInfo(IPin *pReceivePin); - void DisplayTypeInfo(IPin *pPin, const CMediaType *pmt); -#else - void DisplayPinInfo(IPin *pReceivePin) {}; - void DisplayTypeInfo(IPin *pPin, const CMediaType *pmt) {}; -#endif - - // used to agree a media type for a pin connection - - // given a specific media type, attempt a connection (includes - // checking that the type is acceptable to this pin) - HRESULT - AttemptConnection( - IPin* pReceivePin, // connect to this pin - const CMediaType* pmt // using this type - ); - - // try all the media types in this enumerator - for each that - // we accept, try to connect using ReceiveConnection. - HRESULT TryMediaTypes( - IPin *pReceivePin, // connect to this pin - __in_opt const CMediaType *pmt, // proposed type from Connect - IEnumMediaTypes *pEnum); // try this enumerator - - // establish a connection with a suitable mediatype. Needs to - // propose a media type if the pmt pointer is null or partially - // specified - use TryMediaTypes on both our and then the other pin's - // enumerator until we find one that works. - HRESULT AgreeMediaType( - IPin *pReceivePin, // connect to this pin - const CMediaType *pmt); // proposed type from Connect - -public: - - CBasePin( - __in_opt LPCTSTR pObjectName, // Object description - __in CBaseFilter *pFilter, // Owning filter who knows about pins - __in CCritSec *pLock, // Object who implements the lock - __inout HRESULT *phr, // General OLE return code - __in_opt LPCWSTR pName, // Pin name for us - PIN_DIRECTION dir); // Either PINDIR_INPUT or PINDIR_OUTPUT -#ifdef UNICODE - CBasePin( - __in_opt LPCSTR pObjectName, // Object description - __in CBaseFilter *pFilter, // Owning filter who knows about pins - __in CCritSec *pLock, // Object who implements the lock - __inout HRESULT *phr, // General OLE return code - __in_opt LPCWSTR pName, // Pin name for us - PIN_DIRECTION dir); // Either PINDIR_INPUT or PINDIR_OUTPUT -#endif - virtual ~CBasePin(); - - DECLARE_IUNKNOWN - - STDMETHODIMP NonDelegatingQueryInterface(REFIID riid, __deref_out void ** ppv); - STDMETHODIMP_(ULONG) NonDelegatingRelease(); - STDMETHODIMP_(ULONG) NonDelegatingAddRef(); - - // --- IPin methods --- - - // take lead role in establishing a connection. Media type pointer - // may be null, or may point to partially-specified mediatype - // (subtype or format type may be GUID_NULL). - STDMETHODIMP Connect( - IPin * pReceivePin, - __in_opt const AM_MEDIA_TYPE *pmt // optional media type - ); - - // (passive) accept a connection from another pin - STDMETHODIMP ReceiveConnection( - IPin * pConnector, // this is the initiating connecting pin - const AM_MEDIA_TYPE *pmt // this is the media type we will exchange - ); - - STDMETHODIMP Disconnect(); - - STDMETHODIMP ConnectedTo(__deref_out IPin **pPin); - - STDMETHODIMP ConnectionMediaType(__out AM_MEDIA_TYPE *pmt); - - STDMETHODIMP QueryPinInfo( - __out PIN_INFO * pInfo - ); - - STDMETHODIMP QueryDirection( - __out PIN_DIRECTION * pPinDir - ); - - STDMETHODIMP QueryId( - __deref_out LPWSTR * Id - ); - - // does the pin support this media type - STDMETHODIMP QueryAccept( - const AM_MEDIA_TYPE *pmt - ); - - // return an enumerator for this pins preferred media types - STDMETHODIMP EnumMediaTypes( - __deref_out IEnumMediaTypes **ppEnum - ); - - // return an array of IPin* - the pins that this pin internally connects to - // All pins put in the array must be AddReffed (but no others) - // Errors: "Can't say" - FAIL, not enough slots - return S_FALSE - // Default: return E_NOTIMPL - // The filter graph will interpret NOT_IMPL as any input pin connects to - // all visible output pins and vice versa. - // apPin can be NULL if nPin==0 (not otherwise). - STDMETHODIMP QueryInternalConnections( - __out_ecount_part(*nPin,*nPin) IPin* *apPin, // array of IPin* - __inout ULONG *nPin // on input, the number of slots - // on output the number of pins - ) { return E_NOTIMPL; } - - // Called when no more data will be sent - STDMETHODIMP EndOfStream(void); - - // Begin/EndFlush still PURE - - // NewSegment notifies of the start/stop/rate applying to the data - // about to be received. Default implementation records data and - // returns S_OK. - // Override this to pass downstream. - STDMETHODIMP NewSegment( - REFERENCE_TIME tStart, - REFERENCE_TIME tStop, - double dRate); - - //================================================================================ - // IQualityControl methods - //================================================================================ - - STDMETHODIMP Notify(IBaseFilter * pSender, Quality q); - - STDMETHODIMP SetSink(IQualityControl * piqc); - - // --- helper methods --- - - // Returns true if the pin is connected. false otherwise. - BOOL IsConnected(void) {return (m_Connected != NULL); }; - // Return the pin this is connected to (if any) - IPin * GetConnected() { return m_Connected; }; - - // Check if our filter is currently stopped - BOOL IsStopped() { - return (m_pFilter->m_State == State_Stopped); - }; - - // find out the current type version (used by enumerators) - virtual LONG GetMediaTypeVersion(); - void IncrementTypeVersion(); - - // switch the pin to active (paused or running) mode - // not an error to call this if already active - virtual HRESULT Active(void); - - // switch the pin to inactive state - may already be inactive - virtual HRESULT Inactive(void); - - // Notify of Run() from filter - virtual HRESULT Run(REFERENCE_TIME tStart); - - // check if the pin can support this specific proposed type and format - virtual HRESULT CheckMediaType(const CMediaType *) PURE; - - // set the connection to use this format (previously agreed) - virtual HRESULT SetMediaType(const CMediaType *); - - // check that the connection is ok before verifying it - // can be overridden eg to check what interfaces will be supported. - virtual HRESULT CheckConnect(IPin *); - - // Set and release resources required for a connection - virtual HRESULT BreakConnect(); - virtual HRESULT CompleteConnect(IPin *pReceivePin); - - // returns the preferred formats for a pin - virtual HRESULT GetMediaType(int iPosition, __inout CMediaType *pMediaType); - - // access to NewSegment values - REFERENCE_TIME CurrentStopTime() { - return m_tStop; - } - REFERENCE_TIME CurrentStartTime() { - return m_tStart; - } - double CurrentRate() { - return m_dRate; - } - - // Access name - LPWSTR Name() { return m_pName; }; - - // Can reconnectwhen active? - void SetReconnectWhenActive(bool bCanReconnect) - { - m_bCanReconnectWhenActive = bCanReconnect; - } - - bool CanReconnectWhenActive() - { - return m_bCanReconnectWhenActive; - } - -protected: - STDMETHODIMP DisconnectInternal(); -}; - - -//===================================================================== -//===================================================================== -// Defines CEnumPins -// -// Pin enumerator class that works by calling CBaseFilter. This interface -// is provided by CBaseFilter::EnumPins and calls GetPinCount() and -// GetPin() to enumerate existing pins. Needs to be a separate object so -// that it can be cloned (creating an existing object at the same -// position in the enumeration) -// -//===================================================================== -//===================================================================== - -class CEnumPins : public IEnumPins // The interface we support -{ - int m_Position; // Current ordinal position - int m_PinCount; // Number of pins available - CBaseFilter *m_pFilter; // The filter who owns us - LONG m_Version; // Pin version information - LONG m_cRef; - - typedef CGenericList CPinList; - - CPinList m_PinCache; // These pointers have not been AddRef'ed and - // so they should not be dereferenced. They are - // merely kept to ID which pins have been enumerated. - -#ifdef DEBUG - DWORD m_dwCookie; -#endif - - /* If while we are retrieving a pin for example from the filter an error - occurs we assume that our internal state is stale with respect to the - filter (someone may have deleted all the pins). We can check before - starting whether or not the operation is likely to fail by asking the - filter what it's current version number is. If the filter has not - overriden the GetPinVersion method then this will always match */ - - BOOL AreWeOutOfSync() { - return (m_pFilter->GetPinVersion() == m_Version ? FALSE : TRUE); - }; - - /* This method performs the same operations as Reset, except is does not clear - the cache of pins already enumerated. */ - - STDMETHODIMP Refresh(); - -public: - - CEnumPins( - __in CBaseFilter *pFilter, - __in_opt CEnumPins *pEnumPins); - - virtual ~CEnumPins(); - - // IUnknown - STDMETHODIMP QueryInterface(REFIID riid, __deref_out void **ppv); - STDMETHODIMP_(ULONG) AddRef(); - STDMETHODIMP_(ULONG) Release(); - - // IEnumPins - STDMETHODIMP Next( - ULONG cPins, // place this many pins... - __out_ecount(cPins) IPin ** ppPins, // ...in this array of IPin* - __out_opt ULONG * pcFetched // actual count passed returned here - ); - - STDMETHODIMP Skip(ULONG cPins); - STDMETHODIMP Reset(); - STDMETHODIMP Clone(__deref_out IEnumPins **ppEnum); - - -}; - - -//===================================================================== -//===================================================================== -// Defines CEnumMediaTypes -// -// Enumerates the preferred formats for input and output pins -//===================================================================== -//===================================================================== - -class CEnumMediaTypes : public IEnumMediaTypes // The interface we support -{ - int m_Position; // Current ordinal position - CBasePin *m_pPin; // The pin who owns us - LONG m_Version; // Media type version value - LONG m_cRef; -#ifdef DEBUG - DWORD m_dwCookie; -#endif - - /* The media types a filter supports can be quite dynamic so we add to - the general IEnumXXXX interface the ability to be signaled when they - change via an event handle the connected filter supplies. Until the - Reset method is called after the state changes all further calls to - the enumerator (except Reset) will return E_UNEXPECTED error code */ - - BOOL AreWeOutOfSync() { - return (m_pPin->GetMediaTypeVersion() == m_Version ? FALSE : TRUE); - }; - -public: - - CEnumMediaTypes( - __in CBasePin *pPin, - __in_opt CEnumMediaTypes *pEnumMediaTypes); - - virtual ~CEnumMediaTypes(); - - // IUnknown - STDMETHODIMP QueryInterface(REFIID riid, __deref_out void **ppv); - STDMETHODIMP_(ULONG) AddRef(); - STDMETHODIMP_(ULONG) Release(); - - // IEnumMediaTypes - STDMETHODIMP Next( - ULONG cMediaTypes, // place this many pins... - __out_ecount(cMediaTypes) AM_MEDIA_TYPE ** ppMediaTypes, // ...in this array - __out_opt ULONG * pcFetched // actual count passed - ); - - STDMETHODIMP Skip(ULONG cMediaTypes); - STDMETHODIMP Reset(); - STDMETHODIMP Clone(__deref_out IEnumMediaTypes **ppEnum); -}; - - - - -//===================================================================== -//===================================================================== -// Defines CBaseOutputPin -// -// class derived from CBasePin that can pass buffers to a connected pin -// that supports IMemInputPin. Supports IPin. -// -// Derive your output pin from this. -// -//===================================================================== -//===================================================================== - -class AM_NOVTABLE CBaseOutputPin : public CBasePin -{ - -protected: - - IMemAllocator *m_pAllocator; - IMemInputPin *m_pInputPin; // interface on the downstreaminput pin - // set up in CheckConnect when we connect. - -public: - - CBaseOutputPin( - __in_opt LPCTSTR pObjectName, - __in CBaseFilter *pFilter, - __in CCritSec *pLock, - __inout HRESULT *phr, - __in_opt LPCWSTR pName); -#ifdef UNICODE - CBaseOutputPin( - __in_opt LPCSTR pObjectName, - __in CBaseFilter *pFilter, - __in CCritSec *pLock, - __inout HRESULT *phr, - __in_opt LPCWSTR pName); -#endif - // override CompleteConnect() so we can negotiate an allocator - virtual HRESULT CompleteConnect(IPin *pReceivePin); - - // negotiate the allocator and its buffer size/count and other properties - // Calls DecideBufferSize to set properties - virtual HRESULT DecideAllocator(IMemInputPin * pPin, __deref_out IMemAllocator ** pAlloc); - - // override this to set the buffer size and count. Return an error - // if the size/count is not to your liking. - // The allocator properties passed in are those requested by the - // input pin - use eg the alignment and prefix members if you have - // no preference on these. - virtual HRESULT DecideBufferSize( - IMemAllocator * pAlloc, - __inout ALLOCATOR_PROPERTIES * ppropInputRequest - ) PURE; - - // returns an empty sample buffer from the allocator - virtual HRESULT GetDeliveryBuffer(__deref_out IMediaSample ** ppSample, - __in_opt REFERENCE_TIME * pStartTime, - __in_opt REFERENCE_TIME * pEndTime, - DWORD dwFlags); - - // deliver a filled-in sample to the connected input pin - // note - you need to release it after calling this. The receiving - // pin will addref the sample if it needs to hold it beyond the - // call. - virtual HRESULT Deliver(IMediaSample *); - - // override this to control the connection - virtual HRESULT InitAllocator(__deref_out IMemAllocator **ppAlloc); - HRESULT CheckConnect(IPin *pPin); - HRESULT BreakConnect(); - - // override to call Commit and Decommit - HRESULT Active(void); - HRESULT Inactive(void); - - // we have a default handling of EndOfStream which is to return - // an error, since this should be called on input pins only - STDMETHODIMP EndOfStream(void); - - // called from elsewhere in our filter to pass EOS downstream to - // our connected input pin - virtual HRESULT DeliverEndOfStream(void); - - // same for Begin/EndFlush - we handle Begin/EndFlush since it - // is an error on an output pin, and we have Deliver methods to - // call the methods on the connected pin - STDMETHODIMP BeginFlush(void); - STDMETHODIMP EndFlush(void); - virtual HRESULT DeliverBeginFlush(void); - virtual HRESULT DeliverEndFlush(void); - - // deliver NewSegment to connected pin - you will need to - // override this if you queue any data in your output pin. - virtual HRESULT DeliverNewSegment( - REFERENCE_TIME tStart, - REFERENCE_TIME tStop, - double dRate); - - //================================================================================ - // IQualityControl methods - //================================================================================ - - // All inherited from CBasePin and not overridden here. - // STDMETHODIMP Notify(IBaseFilter * pSender, Quality q); - // STDMETHODIMP SetSink(IQualityControl * piqc); -}; - - -//===================================================================== -//===================================================================== -// Defines CBaseInputPin -// -// derive your standard input pin from this. -// you need to supply GetMediaType and CheckConnect etc (see CBasePin), -// and you need to supply Receive to do something more useful. -// -//===================================================================== -//===================================================================== - -class AM_NOVTABLE CBaseInputPin : public CBasePin, - public IMemInputPin -{ - -protected: - - IMemAllocator *m_pAllocator; // Default memory allocator - - // allocator is read-only, so received samples - // cannot be modified (probably only relevant to in-place - // transforms - BYTE m_bReadOnly; - - // in flushing state (between BeginFlush and EndFlush) - // if TRUE, all Receives are returned with S_FALSE - BYTE m_bFlushing; - - // Sample properties - initalized in Receive - AM_SAMPLE2_PROPERTIES m_SampleProps; - -public: - - CBaseInputPin( - __in_opt LPCTSTR pObjectName, - __in CBaseFilter *pFilter, - __in CCritSec *pLock, - __inout HRESULT *phr, - __in_opt LPCWSTR pName); -#ifdef UNICODE - CBaseInputPin( - __in_opt LPCSTR pObjectName, - __in CBaseFilter *pFilter, - __in CCritSec *pLock, - __inout HRESULT *phr, - __in_opt LPCWSTR pName); -#endif - virtual ~CBaseInputPin(); - - DECLARE_IUNKNOWN - - // override this to publicise our interfaces - STDMETHODIMP NonDelegatingQueryInterface(REFIID riid, __deref_out void **ppv); - - // return the allocator interface that this input pin - // would like the output pin to use - STDMETHODIMP GetAllocator(__deref_out IMemAllocator ** ppAllocator); - - // tell the input pin which allocator the output pin is actually - // going to use. - STDMETHODIMP NotifyAllocator( - IMemAllocator * pAllocator, - BOOL bReadOnly); - - // do something with this media sample - STDMETHODIMP Receive(IMediaSample *pSample); - - // do something with these media samples - STDMETHODIMP ReceiveMultiple ( - __in_ecount(nSamples) IMediaSample **pSamples, - long nSamples, - __out long *nSamplesProcessed); - - // See if Receive() blocks - STDMETHODIMP ReceiveCanBlock(); - - // Default handling for BeginFlush - call at the beginning - // of your implementation (makes sure that all Receive calls - // fail). After calling this, you need to free any queued data - // and then call downstream. - STDMETHODIMP BeginFlush(void); - - // default handling for EndFlush - call at end of your implementation - // - before calling this, ensure that there is no queued data and no thread - // pushing any more without a further receive, then call downstream, - // then call this method to clear the m_bFlushing flag and re-enable - // receives - STDMETHODIMP EndFlush(void); - - // this method is optional (can return E_NOTIMPL). - // default implementation returns E_NOTIMPL. Override if you have - // specific alignment or prefix needs, but could use an upstream - // allocator - STDMETHODIMP GetAllocatorRequirements(__out ALLOCATOR_PROPERTIES*pProps); - - // Release the pin's allocator. - HRESULT BreakConnect(); - - // helper method to check the read-only flag - BOOL IsReadOnly() { - return m_bReadOnly; - }; - - // helper method to see if we are flushing - BOOL IsFlushing() { - return m_bFlushing; - }; - - // Override this for checking whether it's OK to process samples - // Also call this from EndOfStream. - virtual HRESULT CheckStreaming(); - - // Pass a Quality notification on to the appropriate sink - HRESULT PassNotify(Quality& q); - - - //================================================================================ - // IQualityControl methods (from CBasePin) - //================================================================================ - - STDMETHODIMP Notify(IBaseFilter * pSender, Quality q); - - // no need to override: - // STDMETHODIMP SetSink(IQualityControl * piqc); - - - // switch the pin to inactive state - may already be inactive - virtual HRESULT Inactive(void); - - // Return sample properties pointer - AM_SAMPLE2_PROPERTIES * SampleProps() { - ASSERT(m_SampleProps.cbData != 0); - return &m_SampleProps; - } - -}; - -/////////////////////////////////////////////////////////////////////////// -// CDynamicOutputPin -// - -class CDynamicOutputPin : public CBaseOutputPin, - public IPinFlowControl -{ -public: -#ifdef UNICODE - CDynamicOutputPin( - __in_opt LPCSTR pObjectName, - __in CBaseFilter *pFilter, - __in CCritSec *pLock, - __inout HRESULT *phr, - __in_opt LPCWSTR pName); -#endif - - CDynamicOutputPin( - __in_opt LPCTSTR pObjectName, - __in CBaseFilter *pFilter, - __in CCritSec *pLock, - __inout HRESULT *phr, - __in_opt LPCWSTR pName); - - ~CDynamicOutputPin(); - - // IUnknown Methods - DECLARE_IUNKNOWN - STDMETHODIMP NonDelegatingQueryInterface(REFIID riid, __deref_out void **ppv); - - // IPin Methods - STDMETHODIMP Disconnect(void); - - // IPinFlowControl Methods - STDMETHODIMP Block(DWORD dwBlockFlags, HANDLE hEvent); - - // Set graph config info - void SetConfigInfo(IGraphConfig *pGraphConfig, HANDLE hStopEvent); - - #ifdef DEBUG - virtual HRESULT Deliver(IMediaSample *pSample); - virtual HRESULT DeliverEndOfStream(void); - virtual HRESULT DeliverNewSegment(REFERENCE_TIME tStart, REFERENCE_TIME tStop, double dRate); - #endif // DEBUG - - HRESULT DeliverBeginFlush(void); - HRESULT DeliverEndFlush(void); - - HRESULT Inactive(void); - HRESULT Active(void); - virtual HRESULT CompleteConnect(IPin *pReceivePin); - - virtual HRESULT StartUsingOutputPin(void); - virtual void StopUsingOutputPin(void); - virtual bool StreamingThreadUsingOutputPin(void); - - HRESULT ChangeOutputFormat - ( - const AM_MEDIA_TYPE *pmt, - REFERENCE_TIME tSegmentStart, - REFERENCE_TIME tSegmentStop, - double dSegmentRate - ); - HRESULT ChangeMediaType(const CMediaType *pmt); - HRESULT DynamicReconnect(const CMediaType *pmt); - -protected: - HRESULT SynchronousBlockOutputPin(void); - HRESULT AsynchronousBlockOutputPin(HANDLE hNotifyCallerPinBlockedEvent); - HRESULT UnblockOutputPin(void); - - void BlockOutputPin(void); - void ResetBlockState(void); - - static HRESULT WaitEvent(HANDLE hEvent); - - enum BLOCK_STATE - { - NOT_BLOCKED, - PENDING, - BLOCKED - }; - - // This lock should be held when the following class members are - // being used: m_hNotifyCallerPinBlockedEvent, m_BlockState, - // m_dwBlockCallerThreadID and m_dwNumOutstandingOutputPinUsers. - CCritSec m_BlockStateLock; - - // This event should be signaled when the output pin is - // not blocked. This is a manual reset event. For more - // information on events, see the documentation for - // CreateEvent() in the Windows SDK. - HANDLE m_hUnblockOutputPinEvent; - - // This event will be signaled when block operation succeedes or - // when the user cancels the block operation. The block operation - // can be canceled by calling IPinFlowControl2::Block( 0, NULL ) - // while the block operation is pending. - HANDLE m_hNotifyCallerPinBlockedEvent; - - // The state of the current block operation. - BLOCK_STATE m_BlockState; - - // The ID of the thread which last called IPinFlowControl::Block(). - // For more information on thread IDs, see the documentation for - // GetCurrentThreadID() in the Windows SDK. - DWORD m_dwBlockCallerThreadID; - - // The number of times StartUsingOutputPin() has been sucessfully - // called and a corresponding call to StopUsingOutputPin() has not - // been made. When this variable is greater than 0, the streaming - // thread is calling IPin::NewSegment(), IPin::EndOfStream(), - // IMemInputPin::Receive() or IMemInputPin::ReceiveMultiple(). The - // streaming thread could also be calling: DynamicReconnect(), - // ChangeMediaType() or ChangeOutputFormat(). The output pin cannot - // be blocked while the output pin is being used. - DWORD m_dwNumOutstandingOutputPinUsers; - - // This event should be set when the IMediaFilter::Stop() is called. - // This is a manual reset event. It is also set when the output pin - // delivers a flush to the connected input pin. - HANDLE m_hStopEvent; - IGraphConfig* m_pGraphConfig; - - // TRUE if the output pin's allocator's samples are read only. - // Otherwise FALSE. For more information, see the documentation - // for IMemInputPin::NotifyAllocator(). - BOOL m_bPinUsesReadOnlyAllocator; - -private: - HRESULT Initialize(void); - HRESULT ChangeMediaTypeHelper(const CMediaType *pmt); - - #ifdef DEBUG - void AssertValid(void); - #endif // DEBUG -}; - -class CAutoUsingOutputPin -{ -public: - CAutoUsingOutputPin( __in CDynamicOutputPin* pOutputPin, __inout HRESULT* phr ); - ~CAutoUsingOutputPin(); - -private: - CDynamicOutputPin* m_pOutputPin; -}; - -inline CAutoUsingOutputPin::CAutoUsingOutputPin( __in CDynamicOutputPin* pOutputPin, __inout HRESULT* phr ) : - m_pOutputPin(NULL) -{ - // The caller should always pass in valid pointers. - ASSERT( NULL != pOutputPin ); - ASSERT( NULL != phr ); - - // Make sure the user initialized phr. - ASSERT( S_OK == *phr ); - - HRESULT hr = pOutputPin->StartUsingOutputPin(); - if( FAILED( hr ) ) - { - *phr = hr; - return; - } - - m_pOutputPin = pOutputPin; -} - -inline CAutoUsingOutputPin::~CAutoUsingOutputPin() -{ - if( NULL != m_pOutputPin ) - { - m_pOutputPin->StopUsingOutputPin(); - } -} - -#ifdef DEBUG - -inline HRESULT CDynamicOutputPin::Deliver(IMediaSample *pSample) -{ - // The caller should call StartUsingOutputPin() before calling this - // method. - ASSERT(StreamingThreadUsingOutputPin()); - - return CBaseOutputPin::Deliver(pSample); -} - -inline HRESULT CDynamicOutputPin::DeliverEndOfStream(void) -{ - // The caller should call StartUsingOutputPin() before calling this - // method. - ASSERT( StreamingThreadUsingOutputPin() ); - - return CBaseOutputPin::DeliverEndOfStream(); -} - -inline HRESULT CDynamicOutputPin::DeliverNewSegment(REFERENCE_TIME tStart, REFERENCE_TIME tStop, double dRate) -{ - // The caller should call StartUsingOutputPin() before calling this - // method. - ASSERT(StreamingThreadUsingOutputPin()); - - return CBaseOutputPin::DeliverNewSegment(tStart, tStop, dRate); -} - -#endif // DEBUG - -//===================================================================== -//===================================================================== -// Memory allocators -// -// the shared memory transport between pins requires the input pin -// to provide a memory allocator that can provide sample objects. A -// sample object supports the IMediaSample interface. -// -// CBaseAllocator handles the management of free and busy samples. It -// allocates CMediaSample objects. CBaseAllocator is an abstract class: -// in particular it has no method of initializing the list of free -// samples. CMemAllocator is derived from CBaseAllocator and initializes -// the list of samples using memory from the standard IMalloc interface. -// -// If you want your buffers to live in some special area of memory, -// derive your allocator object from CBaseAllocator. If you derive your -// IMemInputPin interface object from CBaseMemInputPin, you will get -// CMemAllocator-based allocation etc for free and will just need to -// supply the Receive handling, and media type / format negotiation. -//===================================================================== -//===================================================================== - - -//===================================================================== -//===================================================================== -// Defines CMediaSample -// -// an object of this class supports IMediaSample and represents a buffer -// for media data with some associated properties. Releasing it returns -// it to a freelist managed by a CBaseAllocator derived object. -//===================================================================== -//===================================================================== - -class CMediaSample : public IMediaSample2 // The interface we support -{ - -protected: - - friend class CBaseAllocator; - - /* Values for dwFlags - these are used for backward compatiblity - only now - use AM_SAMPLE_xxx - */ - enum { Sample_SyncPoint = 0x01, /* Is this a sync point */ - Sample_Preroll = 0x02, /* Is this a preroll sample */ - Sample_Discontinuity = 0x04, /* Set if start of new segment */ - Sample_TypeChanged = 0x08, /* Has the type changed */ - Sample_TimeValid = 0x10, /* Set if time is valid */ - Sample_MediaTimeValid = 0x20, /* Is the media time valid */ - Sample_TimeDiscontinuity = 0x40, /* Time discontinuity */ - Sample_StopValid = 0x100, /* Stop time valid */ - Sample_ValidFlags = 0x1FF - }; - - /* Properties, the media sample class can be a container for a format - change in which case we take a copy of a type through the SetMediaType - interface function and then return it when GetMediaType is called. As - we do no internal processing on it we leave it as a pointer */ - - DWORD m_dwFlags; /* Flags for this sample */ - /* Type specific flags are packed - into the top word - */ - DWORD m_dwTypeSpecificFlags; /* Media type specific flags */ - __field_ecount_opt(m_cbBuffer) LPBYTE m_pBuffer; /* Pointer to the complete buffer */ - LONG m_lActual; /* Length of data in this sample */ - LONG m_cbBuffer; /* Size of the buffer */ - CBaseAllocator *m_pAllocator; /* The allocator who owns us */ - CMediaSample *m_pNext; /* Chaining in free list */ - REFERENCE_TIME m_Start; /* Start sample time */ - REFERENCE_TIME m_End; /* End sample time */ - LONGLONG m_MediaStart; /* Real media start position */ - LONG m_MediaEnd; /* A difference to get the end */ - AM_MEDIA_TYPE *m_pMediaType; /* Media type change data */ - DWORD m_dwStreamId; /* Stream id */ -public: - LONG m_cRef; /* Reference count */ - - -public: - - CMediaSample( - __in_opt LPCTSTR pName, - __in_opt CBaseAllocator *pAllocator, - __inout_opt HRESULT *phr, - __in_bcount_opt(length) LPBYTE pBuffer = NULL, - LONG length = 0); -#ifdef UNICODE - CMediaSample( - __in_opt LPCSTR pName, - __in_opt CBaseAllocator *pAllocator, - __inout_opt HRESULT *phr, - __in_bcount_opt(length) LPBYTE pBuffer = NULL, - LONG length = 0); -#endif - - virtual ~CMediaSample(); - - /* Note the media sample does not delegate to its owner */ - - STDMETHODIMP QueryInterface(REFIID riid, __deref_out void **ppv); - STDMETHODIMP_(ULONG) AddRef(); - STDMETHODIMP_(ULONG) Release(); - - // set the buffer pointer and length. Used by allocators that - // want variable sized pointers or pointers into already-read data. - // This is only available through a CMediaSample* not an IMediaSample* - // and so cannot be changed by clients. - HRESULT SetPointer(__in_bcount(cBytes) BYTE * ptr, LONG cBytes); - - // Get me a read/write pointer to this buffer's memory. - STDMETHODIMP GetPointer(__deref_out BYTE ** ppBuffer); - - STDMETHODIMP_(LONG) GetSize(void); - - // get the stream time at which this sample should start and finish. - STDMETHODIMP GetTime( - __out REFERENCE_TIME * pTimeStart, // put time here - __out REFERENCE_TIME * pTimeEnd - ); - - // Set the stream time at which this sample should start and finish. - STDMETHODIMP SetTime( - __in_opt REFERENCE_TIME * pTimeStart, // put time here - __in_opt REFERENCE_TIME * pTimeEnd - ); - STDMETHODIMP IsSyncPoint(void); - STDMETHODIMP SetSyncPoint(BOOL bIsSyncPoint); - STDMETHODIMP IsPreroll(void); - STDMETHODIMP SetPreroll(BOOL bIsPreroll); - - STDMETHODIMP_(LONG) GetActualDataLength(void); - STDMETHODIMP SetActualDataLength(LONG lActual); - - // these allow for limited format changes in band - - STDMETHODIMP GetMediaType(__deref_out AM_MEDIA_TYPE **ppMediaType); - STDMETHODIMP SetMediaType(__in_opt AM_MEDIA_TYPE *pMediaType); - - // returns S_OK if there is a discontinuity in the data (this same is - // not a continuation of the previous stream of data - // - there has been a seek). - STDMETHODIMP IsDiscontinuity(void); - // set the discontinuity property - TRUE if this sample is not a - // continuation, but a new sample after a seek. - STDMETHODIMP SetDiscontinuity(BOOL bDiscontinuity); - - // get the media times for this sample - STDMETHODIMP GetMediaTime( - __out LONGLONG * pTimeStart, - __out LONGLONG * pTimeEnd - ); - - // Set the media times for this sample - STDMETHODIMP SetMediaTime( - __in_opt LONGLONG * pTimeStart, - __in_opt LONGLONG * pTimeEnd - ); - - // Set and get properties (IMediaSample2) - STDMETHODIMP GetProperties( - DWORD cbProperties, - __out_bcount(cbProperties) BYTE * pbProperties - ); - - STDMETHODIMP SetProperties( - DWORD cbProperties, - __in_bcount(cbProperties) const BYTE * pbProperties - ); -}; - - -//===================================================================== -//===================================================================== -// Defines CBaseAllocator -// -// Abstract base class that manages a list of media samples -// -// This class provides support for getting buffers from the free list, -// including handling of commit and (asynchronous) decommit. -// -// Derive from this class and override the Alloc and Free functions to -// allocate your CMediaSample (or derived) objects and add them to the -// free list, preparing them as necessary. -//===================================================================== -//===================================================================== - -class AM_NOVTABLE CBaseAllocator : public CUnknown,// A non delegating IUnknown - public IMemAllocatorCallbackTemp, // The interface we support - public CCritSec // Provides object locking -{ - class CSampleList; - friend class CSampleList; - - /* Trick to get at protected member in CMediaSample */ - static CMediaSample * &NextSample(__in CMediaSample *pSample) - { - return pSample->m_pNext; - }; - - /* Mini list class for the free list */ - class CSampleList - { - public: - CSampleList() : m_List(NULL), m_nOnList(0) {}; -#ifdef DEBUG - ~CSampleList() - { - ASSERT(m_nOnList == 0); - }; -#endif - CMediaSample *Head() const { return m_List; }; - CMediaSample *Next(__in CMediaSample *pSample) const { return CBaseAllocator::NextSample(pSample); }; - int GetCount() const { return m_nOnList; }; - void Add(__inout CMediaSample *pSample) - { - ASSERT(pSample != NULL); - CBaseAllocator::NextSample(pSample) = m_List; - m_List = pSample; - m_nOnList++; - }; - CMediaSample *RemoveHead() - { - CMediaSample *pSample = m_List; - if (pSample != NULL) { - m_List = CBaseAllocator::NextSample(m_List); - m_nOnList--; - } - return pSample; - }; - void Remove(__inout CMediaSample *pSample); - - public: - CMediaSample *m_List; - int m_nOnList; - }; -protected: - - CSampleList m_lFree; // Free list - - /* Note to overriders of CBaseAllocator. - - We use a lazy signalling mechanism for waiting for samples. - This means we don't call the OS if no waits occur. - - In order to implement this: - - 1. When a new sample is added to m_lFree call NotifySample() which - calls ReleaseSemaphore on m_hSem with a count of m_lWaiting and - sets m_lWaiting to 0. - This must all be done holding the allocator's critical section. - - 2. When waiting for a sample call SetWaiting() which increments - m_lWaiting BEFORE leaving the allocator's critical section. - - 3. Actually wait by calling WaitForSingleObject(m_hSem, INFINITE) - having left the allocator's critical section. The effect of - this is to remove 1 from the semaphore's count. You MUST call - this once having incremented m_lWaiting. - - The following are then true when the critical section is not held : - (let nWaiting = number about to wait or waiting) - - (1) if (m_lFree.GetCount() != 0) then (m_lWaiting == 0) - (2) m_lWaiting + Semaphore count == nWaiting - - We would deadlock if - nWaiting != 0 && - m_lFree.GetCount() != 0 && - Semaphore count == 0 - - But from (1) if m_lFree.GetCount() != 0 then m_lWaiting == 0 so - from (2) Semaphore count == nWaiting (which is non-0) so the - deadlock can't happen. - */ - - HANDLE m_hSem; // For signalling - long m_lWaiting; // Waiting for a free element - long m_lCount; // how many buffers we have agreed to provide - long m_lAllocated; // how many buffers are currently allocated - long m_lSize; // agreed size of each buffer - long m_lAlignment; // agreed alignment - long m_lPrefix; // agreed prefix (preceeds GetPointer() value) - BOOL m_bChanged; // Have the buffer requirements changed - - // if true, we are decommitted and can't allocate memory - BOOL m_bCommitted; - // if true, the decommit has happened, but we haven't called Free yet - // as there are still outstanding buffers - BOOL m_bDecommitInProgress; - - // Notification interface - IMemAllocatorNotifyCallbackTemp *m_pNotify; - - BOOL m_fEnableReleaseCallback; - - // called to decommit the memory when the last buffer is freed - // pure virtual - need to override this - virtual void Free(void) PURE; - - // override to allocate the memory when commit called - virtual HRESULT Alloc(void); - -public: - - CBaseAllocator( - __in_opt LPCTSTR , __inout_opt LPUNKNOWN, __inout HRESULT *, - BOOL bEvent = TRUE, BOOL fEnableReleaseCallback = FALSE); -#ifdef UNICODE - CBaseAllocator( - __in_opt LPCSTR , __inout_opt LPUNKNOWN, __inout HRESULT *, - BOOL bEvent = TRUE, BOOL fEnableReleaseCallback = FALSE); -#endif - virtual ~CBaseAllocator(); - - DECLARE_IUNKNOWN - - // override this to publicise our interfaces - STDMETHODIMP NonDelegatingQueryInterface(REFIID riid, __deref_out void **ppv); - - STDMETHODIMP SetProperties( - __in ALLOCATOR_PROPERTIES* pRequest, - __out ALLOCATOR_PROPERTIES* pActual); - - // return the properties actually being used on this allocator - STDMETHODIMP GetProperties( - __out ALLOCATOR_PROPERTIES* pProps); - - // override Commit to allocate memory. We handle the GetBuffer - //state changes - STDMETHODIMP Commit(); - - // override this to handle the memory freeing. We handle any outstanding - // GetBuffer calls - STDMETHODIMP Decommit(); - - // get container for a sample. Blocking, synchronous call to get the - // next free buffer (as represented by an IMediaSample interface). - // on return, the time etc properties will be invalid, but the buffer - // pointer and size will be correct. The two time parameters are - // optional and either may be NULL, they may alternatively be set to - // the start and end times the sample will have attached to it - // bPrevFramesSkipped is not used (used only by the video renderer's - // allocator where it affects quality management in direct draw). - - STDMETHODIMP GetBuffer(__deref_out IMediaSample **ppBuffer, - __in_opt REFERENCE_TIME * pStartTime, - __in_opt REFERENCE_TIME * pEndTime, - DWORD dwFlags); - - // final release of a CMediaSample will call this - STDMETHODIMP ReleaseBuffer(IMediaSample *pBuffer); - // obsolete:: virtual void PutOnFreeList(CMediaSample * pSample); - - STDMETHODIMP SetNotify(IMemAllocatorNotifyCallbackTemp *pNotify); - - STDMETHODIMP GetFreeCount(__out LONG *plBuffersFree); - - // Notify that a sample is available - void NotifySample(); - - // Notify that we're waiting for a sample - void SetWaiting() { m_lWaiting++; }; -}; - - -//===================================================================== -//===================================================================== -// Defines CMemAllocator -// -// this is an allocator based on CBaseAllocator that allocates sample -// buffers in main memory (from 'new'). You must call SetProperties -// before calling Commit. -// -// we don't free the memory when going into Decommit state. The simplest -// way to implement this without complicating CBaseAllocator is to -// have a Free() function, called to go into decommit state, that does -// nothing and a ReallyFree function called from our destructor that -// actually frees the memory. -//===================================================================== -//===================================================================== - -// Make me one from quartz.dll -STDAPI CreateMemoryAllocator(__deref_out IMemAllocator **ppAllocator); - -class CMemAllocator : public CBaseAllocator -{ - -protected: - - LPBYTE m_pBuffer; // combined memory for all buffers - - // override to free the memory when decommit completes - // - we actually do nothing, and save the memory until deletion. - void Free(void); - - // called from the destructor (and from Alloc if changing size/count) to - // actually free up the memory - void ReallyFree(void); - - // overriden to allocate the memory when commit called - HRESULT Alloc(void); - -public: - /* This goes in the factory template table to create new instances */ - static CUnknown *CreateInstance(__inout_opt LPUNKNOWN, __inout HRESULT *); - - STDMETHODIMP SetProperties( - __in ALLOCATOR_PROPERTIES* pRequest, - __out ALLOCATOR_PROPERTIES* pActual); - - CMemAllocator(__in_opt LPCTSTR , __inout_opt LPUNKNOWN, __inout HRESULT *); -#ifdef UNICODE - CMemAllocator(__in_opt LPCSTR , __inout_opt LPUNKNOWN, __inout HRESULT *); -#endif - ~CMemAllocator(); -}; - -// helper used by IAMovieSetup implementation -STDAPI -AMovieSetupRegisterFilter( const AMOVIESETUP_FILTER * const psetupdata - , IFilterMapper * pIFM - , BOOL bRegister ); - - -/////////////////////////////////////////////////////////////////////////// -// ------------------------------------------------------------------------ -// ------------------------------------------------------------------------ -// ------------------------------------------------------------------------ -// ------------------------------------------------------------------------ -/////////////////////////////////////////////////////////////////////////// - -#endif /* __FILTER__ */ - - - diff --git a/UnityWebcam/UnityCamService/includes/cache.h b/UnityWebcam/UnityCamService/includes/cache.h deleted file mode 100644 index a2d5752..0000000 --- a/UnityWebcam/UnityCamService/includes/cache.h +++ /dev/null @@ -1,74 +0,0 @@ -//------------------------------------------------------------------------------ -// File: Cache.h -// -// Desc: DirectShow base classes - efines a non-MFC generic cache class. -// -// Copyright (c) 1992-2001 Microsoft Corporation. All rights reserved. -//------------------------------------------------------------------------------ - - -/* This class implements a simple cache. A cache object is instantiated - with the number of items it is to hold. An item is a pointer to an - object derived from CBaseObject (helps reduce memory leaks). The cache - can then have objects added to it and removed from it. The cache size - is fixed at construction time and may therefore run out or be flooded. - If it runs out it returns a NULL pointer, if it fills up it also returns - a NULL pointer instead of a pointer to the object just inserted */ - -/* Making these classes inherit from CBaseObject does nothing for their - functionality but it allows us to check there are no memory leaks */ - -/* WARNING Be very careful when using this class, what it lets you do is - store and retrieve objects so that you can minimise object creation - which in turns improves efficiency. However the object you store is - exactly the same as the object you get back which means that it short - circuits the constructor initialisation phase. This means any class - variables the object has (eg pointers) are highly likely to be invalid. - Therefore ensure you reinitialise the object before using it again */ - - -#ifndef __CACHE__ -#define __CACHE__ - - -class CCache : CBaseObject { - - /* Make copy constructor and assignment operator inaccessible */ - - CCache(const CCache &refCache); - CCache &operator=(const CCache &refCache); - -private: - - /* These are initialised in the constructor. The first variable points to - an array of pointers, each of which points to a CBaseObject derived - object. The m_iCacheSize is the static fixed size for the cache and the - m_iUsed defines the number of places filled with objects at any time. - We fill the array of pointers from the start (ie m_ppObjects[0] first) - and then only add and remove objects from the end position, so in this - respect the array of object pointers should be treated as a stack */ - - CBaseObject **m_ppObjects; - const INT m_iCacheSize; - INT m_iUsed; - -public: - - CCache(__in_opt LPCTSTR pName,INT iItems); - virtual ~CCache(); - - /* Add an item to the cache */ - CBaseObject *AddToCache(__in CBaseObject *pObject); - - /* Remove an item from the cache */ - CBaseObject *RemoveFromCache(); - - /* Delete all the objects held in the cache */ - void RemoveAll(void); - - /* Return the cache size which is set during construction */ - INT GetCacheSize(void) const {return m_iCacheSize;}; -}; - -#endif /* __CACHE__ */ - diff --git a/UnityWebcam/UnityCamService/includes/checkbmi.h b/UnityWebcam/UnityCamService/includes/checkbmi.h deleted file mode 100644 index 9761dae..0000000 --- a/UnityWebcam/UnityCamService/includes/checkbmi.h +++ /dev/null @@ -1,120 +0,0 @@ -// Copyright (c) 1992 - 1997 Microsoft Corporation. All Rights Reserved. - -#ifndef _CHECKBMI_H_ -#define _CHECKBMI_H_ - -#ifdef __cplusplus -extern "C" { -#endif - -// Helper -__inline BOOL MultiplyCheckOverflow(DWORD a, DWORD b, __deref_out_range(==, a * b) DWORD *pab) { - *pab = a * b; - if ((a == 0) || (((*pab) / a) == b)) { - return TRUE; - } - return FALSE; -} - - -// Checks if the fields in a BITMAPINFOHEADER won't generate -// overlows and buffer overruns -// This is not a complete check and does not guarantee code using this structure will be secure -// from attack -// Bugs this is guarding against: -// 1. Total structure size calculation overflowing -// 2. biClrUsed > 256 for 8-bit palettized content -// 3. Total bitmap size in bytes overflowing -// 4. biSize < size of the base structure leading to accessessing random memory -// 5. Total structure size exceeding know size of data -// - -__success(return != 0) __inline BOOL ValidateBitmapInfoHeader( - const BITMAPINFOHEADER *pbmi, // pointer to structure to check - __out_range(>=, sizeof(BITMAPINFOHEADER)) DWORD cbSize // size of memory block containing structure -) -{ - DWORD dwWidthInBytes; - DWORD dwBpp; - DWORD dwWidthInBits; - DWORD dwHeight; - DWORD dwSizeImage; - DWORD dwClrUsed; - - // Reject bad parameters - do the size check first to avoid reading bad memory - if (cbSize < sizeof(BITMAPINFOHEADER) || - pbmi->biSize < sizeof(BITMAPINFOHEADER) || - pbmi->biSize > 4096) { - return FALSE; - } - - // Reject 0 size - if (pbmi->biWidth == 0 || pbmi->biHeight == 0) { - return FALSE; - } - - // Use bpp of 200 for validating against further overflows if not set for compressed format - dwBpp = 200; - - if (pbmi->biBitCount > dwBpp) { - return FALSE; - } - - // Strictly speaking abs can overflow so cast explicitly to DWORD - dwHeight = (DWORD)abs(pbmi->biHeight); - - if (!MultiplyCheckOverflow(dwBpp, (DWORD)pbmi->biWidth, &dwWidthInBits)) { - return FALSE; - } - - // Compute correct width in bytes - rounding up to 4 bytes - dwWidthInBytes = (dwWidthInBits / 8 + 3) & ~3; - - if (!MultiplyCheckOverflow(dwWidthInBytes, dwHeight, &dwSizeImage)) { - return FALSE; - } - - // Fail if total size is 0 - this catches indivual quantities being 0 - // Also don't allow huge values > 1GB which might cause arithmetic - // errors for users - if (dwSizeImage > 0x40000000 || - pbmi->biSizeImage > 0x40000000) { - return FALSE; - } - - // Fail if biClrUsed looks bad - if (pbmi->biClrUsed > 256) { - return FALSE; - } - - if (pbmi->biClrUsed == 0 && pbmi->biBitCount <= 8 && pbmi->biBitCount > 0) { - dwClrUsed = (1 << pbmi->biBitCount); - } else { - dwClrUsed = pbmi->biClrUsed; - } - - // Check total size - if (cbSize < pbmi->biSize + dwClrUsed * sizeof(RGBQUAD) + - (pbmi->biCompression == BI_BITFIELDS ? 3 * sizeof(DWORD) : 0)) { - return FALSE; - } - - // If it is RGB validate biSizeImage - lots of code assumes the size is correct - if (pbmi->biCompression == BI_RGB || pbmi->biCompression == BI_BITFIELDS) { - if (pbmi->biSizeImage != 0) { - DWORD dwBits = (DWORD)pbmi->biWidth * (DWORD)pbmi->biBitCount; - DWORD dwWidthInBytes = ((DWORD)((dwBits+31) & (~31)) / 8); - DWORD dwTotalSize = (DWORD)abs(pbmi->biHeight) * dwWidthInBytes; - if (dwTotalSize > pbmi->biSizeImage) { - return FALSE; - } - } - } - return TRUE; -} - -#ifdef __cplusplus -} -#endif - -#endif // _CHECKBMI_H_ diff --git a/UnityWebcam/UnityCamService/includes/combase.h b/UnityWebcam/UnityCamService/includes/combase.h deleted file mode 100644 index 44ca535..0000000 --- a/UnityWebcam/UnityCamService/includes/combase.h +++ /dev/null @@ -1,305 +0,0 @@ -//------------------------------------------------------------------------------ -// File: ComBase.h -// -// Desc: DirectShow base classes - defines a class hierarchy for creating -// COM objects. -// -// Copyright (c) 1992-2001 Microsoft Corporation. All rights reserved. -//------------------------------------------------------------------------------ - - -/* - -a. Derive your COM object from CUnknown - -b. Make a static CreateInstance function that takes an LPUNKNOWN, an HRESULT * - and a TCHAR *. The LPUNKNOWN defines the object to delegate IUnknown calls - to. The HRESULT * allows error codes to be passed around constructors and - the TCHAR * is a descriptive name that can be printed on the debugger. - - It is important that constructors only change the HRESULT * if they have - to set an ERROR code, if it was successful then leave it alone or you may - overwrite an error code from an object previously created. - - When you call a constructor the descriptive name should be in static store - as we do not copy the string. To stop large amounts of memory being used - in retail builds by all these static strings use the NAME macro, - - CMyFilter = new CImplFilter(NAME("My filter"),pUnknown,phr); - if (FAILED(hr)) { - return hr; - } - - In retail builds NAME(_x_) compiles to NULL, the base CBaseObject class - knows not to do anything with objects that don't have a name. - -c. Have a constructor for your object that passes the LPUNKNOWN, HRESULT * and - TCHAR * to the CUnknown constructor. You can set the HRESULT if you have an - error, or just simply pass it through to the constructor. - - The object creation will fail in the class factory if the HRESULT indicates - an error (ie FAILED(HRESULT) == TRUE) - -d. Create a FactoryTemplate with your object's class id and CreateInstance - function. - -Then (for each interface) either - -Multiple inheritance - -1. Also derive it from ISomeInterface -2. Include DECLARE_IUNKNOWN in your class definition to declare - implementations of QueryInterface, AddRef and Release that - call the outer unknown -3. Override NonDelegatingQueryInterface to expose ISomeInterface by - code something like - - if (riid == IID_ISomeInterface) { - return GetInterface((ISomeInterface *) this, ppv); - } else { - return CUnknown::NonDelegatingQueryInterface(riid, ppv); - } - -4. Declare and implement the member functions of ISomeInterface. - -or: Nested interfaces - -1. Declare a class derived from CUnknown -2. Include DECLARE_IUNKNOWN in your class definition -3. Override NonDelegatingQueryInterface to expose ISomeInterface by - code something like - - if (riid == IID_ISomeInterface) { - return GetInterface((ISomeInterface *) this, ppv); - } else { - return CUnknown::NonDelegatingQueryInterface(riid, ppv); - } - -4. Implement the member functions of ISomeInterface. Use GetOwner() to - access the COM object class. - -And in your COM object class: - -5. Make the nested class a friend of the COM object class, and declare - an instance of the nested class as a member of the COM object class. - - NOTE that because you must always pass the outer unknown and an hResult - to the CUnknown constructor you cannot use a default constructor, in - other words you will have to make the member variable a pointer to the - class and make a NEW call in your constructor to actually create it. - -6. override the NonDelegatingQueryInterface with code like this: - - if (riid == IID_ISomeInterface) { - return m_pImplFilter-> - NonDelegatingQueryInterface(IID_ISomeInterface, ppv); - } else { - return CUnknown::NonDelegatingQueryInterface(riid, ppv); - } - -You can have mixed classes which support some interfaces via multiple -inheritance and some via nested classes - -*/ - -#ifndef __COMBASE__ -#define __COMBASE__ - -// Filter Setup data structures no defined in axextend.idl - -typedef REGPINTYPES -AMOVIESETUP_MEDIATYPE, * PAMOVIESETUP_MEDIATYPE, * FAR LPAMOVIESETUP_MEDIATYPE; - -typedef REGFILTERPINS -AMOVIESETUP_PIN, * PAMOVIESETUP_PIN, * FAR LPAMOVIESETUP_PIN; - -typedef struct _AMOVIESETUP_FILTER -{ - const CLSID * clsID; - const WCHAR * strName; - DWORD dwMerit; - UINT nPins; - const AMOVIESETUP_PIN * lpPin; -} -AMOVIESETUP_FILTER, * PAMOVIESETUP_FILTER, * FAR LPAMOVIESETUP_FILTER; - -/* The DLLENTRY module initialises the module handle on loading */ - -extern HINSTANCE g_hInst; - -/* On DLL load remember which platform we are running on */ - -extern DWORD g_amPlatform; -extern OSVERSIONINFO g_osInfo; // Filled in by GetVersionEx - -/* Version of IUnknown that is renamed to allow a class to support both - non delegating and delegating IUnknowns in the same COM object */ - -#ifndef INONDELEGATINGUNKNOWN_DEFINED -DECLARE_INTERFACE(INonDelegatingUnknown) -{ - STDMETHOD(NonDelegatingQueryInterface) (THIS_ REFIID, LPVOID *) PURE; - STDMETHOD_(ULONG, NonDelegatingAddRef)(THIS) PURE; - STDMETHOD_(ULONG, NonDelegatingRelease)(THIS) PURE; -}; -#define INONDELEGATINGUNKNOWN_DEFINED -#endif - -typedef INonDelegatingUnknown *PNDUNKNOWN; - - -/* This is the base object class that supports active object counting. As - part of the debug facilities we trace every time a C++ object is created - or destroyed. The name of the object has to be passed up through the class - derivation list during construction as you cannot call virtual functions - in the constructor. The downside of all this is that every single object - constructor has to take an object name parameter that describes it */ - -class CBaseObject -{ - -private: - - // Disable the copy constructor and assignment by default so you will get - // compiler errors instead of unexpected behaviour if you pass objects - // by value or assign objects. - CBaseObject(const CBaseObject& objectSrc); // no implementation - void operator=(const CBaseObject& objectSrc); // no implementation - -private: - static LONG m_cObjects; /* Total number of objects active */ - -protected: -#ifdef DEBUG - DWORD m_dwCookie; /* Cookie identifying this object */ -#endif - - -public: - - /* These increment and decrement the number of active objects */ - - CBaseObject(__in_opt LPCTSTR pName); -#ifdef UNICODE - CBaseObject(__in_opt LPCSTR pName); -#endif - ~CBaseObject(); - - /* Call this to find if there are any CUnknown derived objects active */ - - static LONG ObjectsActive() { - return m_cObjects; - }; -}; - - -/* An object that supports one or more COM interfaces will be based on - this class. It supports counting of total objects for DLLCanUnloadNow - support, and an implementation of the core non delegating IUnknown */ - -class AM_NOVTABLE CUnknown : public INonDelegatingUnknown, - public CBaseObject -{ -private: - const LPUNKNOWN m_pUnknown; /* Owner of this object */ - -protected: /* So we can override NonDelegatingRelease() */ - volatile LONG m_cRef; /* Number of reference counts */ - -public: - - CUnknown(__in_opt LPCTSTR pName, __in_opt LPUNKNOWN pUnk); - virtual ~CUnknown() {}; - - // This is redundant, just use the other constructor - // as we never touch the HRESULT in this anyway - CUnknown(__in_opt LPCTSTR Name, __in_opt LPUNKNOWN pUnk, __inout_opt HRESULT *phr); -#ifdef UNICODE - CUnknown(__in_opt LPCSTR pName, __in_opt LPUNKNOWN pUnk); - CUnknown(__in_opt LPCSTR pName, __in_opt LPUNKNOWN pUnk,__inout_opt HRESULT *phr); -#endif - - /* Return the owner of this object */ - - LPUNKNOWN GetOwner() const { - return m_pUnknown; - }; - - /* Called from the class factory to create a new instance, it is - pure virtual so it must be overriden in your derived class */ - - /* static CUnknown *CreateInstance(LPUNKNOWN, HRESULT *) */ - - /* Non delegating unknown implementation */ - - STDMETHODIMP NonDelegatingQueryInterface(REFIID, __deref_out void **); - STDMETHODIMP_(ULONG) NonDelegatingAddRef(); - STDMETHODIMP_(ULONG) NonDelegatingRelease(); -}; - -/* Return an interface pointer to a requesting client - performing a thread safe AddRef as necessary */ - -STDAPI GetInterface(LPUNKNOWN pUnk, __out void **ppv); - -/* A function that can create a new COM object */ - -typedef CUnknown *(CALLBACK *LPFNNewCOMObject)(__in_opt LPUNKNOWN pUnkOuter, __inout_opt HRESULT *phr); - -/* A function (can be NULL) which is called from the DLL entrypoint - routine for each factory template: - - bLoading - TRUE on DLL load, FALSE on DLL unload - rclsid - the m_ClsID of the entry -*/ -typedef void (CALLBACK *LPFNInitRoutine)(BOOL bLoading, const CLSID *rclsid); - -/* Create one of these per object class in an array so that - the default class factory code can create new instances */ - -class CFactoryTemplate { - -public: - - const WCHAR * m_Name; - const CLSID * m_ClsID; - LPFNNewCOMObject m_lpfnNew; - LPFNInitRoutine m_lpfnInit; - const AMOVIESETUP_FILTER * m_pAMovieSetup_Filter; - - BOOL IsClassID(REFCLSID rclsid) const { - return (IsEqualCLSID(*m_ClsID,rclsid)); - }; - - CUnknown *CreateInstance(__inout_opt LPUNKNOWN pUnk, __inout_opt HRESULT *phr) const { - CheckPointer(phr,NULL); - return m_lpfnNew(pUnk, phr); - }; -}; - - -/* You must override the (pure virtual) NonDelegatingQueryInterface to return - interface pointers (using GetInterface) to the interfaces your derived - class supports (the default implementation only supports IUnknown) */ - -#define DECLARE_IUNKNOWN \ - STDMETHODIMP QueryInterface(REFIID riid, __deref_out void **ppv) { \ - return GetOwner()->QueryInterface(riid,ppv); \ - }; \ - STDMETHODIMP_(ULONG) AddRef() { \ - return GetOwner()->AddRef(); \ - }; \ - STDMETHODIMP_(ULONG) Release() { \ - return GetOwner()->Release(); \ - }; - - - -HINSTANCE LoadOLEAut32(); - - -#endif /* __COMBASE__ */ - - - - diff --git a/UnityWebcam/UnityCamService/includes/cprop.h b/UnityWebcam/UnityCamService/includes/cprop.h deleted file mode 100644 index a030f8f..0000000 --- a/UnityWebcam/UnityCamService/includes/cprop.h +++ /dev/null @@ -1,95 +0,0 @@ -//------------------------------------------------------------------------------ -// File: CProp.h -// -// Desc: DirectShow base classes. -// -// Copyright (c) 1992-2001 Microsoft Corporation. All rights reserved. -//------------------------------------------------------------------------------ - - -#ifndef __CPROP__ -#define __CPROP__ - -// Base property page class. Filters typically expose custom properties by -// implementing special control interfaces, examples are IDirectDrawVideo -// and IQualProp on renderers. This allows property pages to be built that -// use the given interface. Applications such as the ActiveMovie OCX query -// filters for the property pages they support and expose them to the user -// -// This class provides all the framework for a property page. A property -// page is a COM object that supports IPropertyPage. We should be created -// with a resource ID for the dialog which we will load when required. We -// should also be given in the constructor a resource ID for a title string -// we will load from the DLLs STRINGTABLE. The property page titles must be -// stored in resource files so that they can be easily internationalised -// -// We have a number of virtual methods (not PURE) that may be overriden in -// derived classes to query for interfaces and so on. These functions have -// simple implementations here that just return NOERROR. Derived classes -// will almost definately have to override the message handler method called -// OnReceiveMessage. We have a static dialog procedure that calls the method -// so that derived classes don't have to fiddle around with the this pointer - -class AM_NOVTABLE CBasePropertyPage : public IPropertyPage, public CUnknown -{ -protected: - - LPPROPERTYPAGESITE m_pPageSite; // Details for our property site - HWND m_hwnd; // Window handle for the page - HWND m_Dlg; // Actual dialog window handle - BOOL m_bDirty; // Has anything been changed - int m_TitleId; // Resource identifier for title - int m_DialogId; // Dialog resource identifier - - static INT_PTR CALLBACK DialogProc(HWND hwnd, - UINT uMsg, - WPARAM wParam, - LPARAM lParam); - -private: - BOOL m_bObjectSet ; // SetObject has been called or not. -public: - - CBasePropertyPage(__in_opt LPCTSTR pName, // Debug only name - __inout_opt LPUNKNOWN pUnk, // COM Delegator - int DialogId, // Resource ID - int TitleId); // To get tital - -#ifdef UNICODE - CBasePropertyPage(__in_opt LPCSTR pName, - __inout_opt LPUNKNOWN pUnk, - int DialogId, - int TitleId); -#endif - virtual ~CBasePropertyPage() { }; - DECLARE_IUNKNOWN - - // Override these virtual methods - - virtual HRESULT OnConnect(IUnknown *pUnknown) { return NOERROR; }; - virtual HRESULT OnDisconnect() { return NOERROR; }; - virtual HRESULT OnActivate() { return NOERROR; }; - virtual HRESULT OnDeactivate() { return NOERROR; }; - virtual HRESULT OnApplyChanges() { return NOERROR; }; - virtual INT_PTR OnReceiveMessage(HWND hwnd,UINT uMsg,WPARAM wParam,LPARAM lParam); - - // These implement an IPropertyPage interface - - STDMETHODIMP NonDelegatingQueryInterface(REFIID riid, __deref_out void **ppv); - STDMETHODIMP_(ULONG) NonDelegatingRelease(); - STDMETHODIMP_(ULONG) NonDelegatingAddRef(); - STDMETHODIMP SetPageSite(__in_opt LPPROPERTYPAGESITE pPageSite); - STDMETHODIMP Activate(HWND hwndParent, LPCRECT prect,BOOL fModal); - STDMETHODIMP Deactivate(void); - STDMETHODIMP GetPageInfo(__out LPPROPPAGEINFO pPageInfo); - STDMETHODIMP SetObjects(ULONG cObjects, __in_ecount_opt(cObjects) LPUNKNOWN *ppUnk); - STDMETHODIMP Show(UINT nCmdShow); - STDMETHODIMP Move(LPCRECT prect); - STDMETHODIMP IsPageDirty(void) { return m_bDirty ? S_OK : S_FALSE; } - STDMETHODIMP Apply(void); - STDMETHODIMP Help(LPCWSTR lpszHelpDir) { return E_NOTIMPL; } - STDMETHODIMP TranslateAccelerator(__inout LPMSG lpMsg) { return E_NOTIMPL; } -}; - -#endif // __CPROP__ - diff --git a/UnityWebcam/UnityCamService/includes/ctlutil.h b/UnityWebcam/UnityCamService/includes/ctlutil.h deleted file mode 100644 index e3f7085..0000000 --- a/UnityWebcam/UnityCamService/includes/ctlutil.h +++ /dev/null @@ -1,923 +0,0 @@ -//------------------------------------------------------------------------------ -// File: CtlUtil.h -// -// Desc: DirectShow base classes. -// -// Copyright (c) 1992-2001 Microsoft Corporation. All rights reserved. -//------------------------------------------------------------------------------ - - -// Base classes implementing IDispatch parsing for the basic control dual -// interfaces. Derive from these and implement just the custom method and -// property methods. We also implement CPosPassThru that can be used by -// renderers and transforms to pass by IMediaPosition and IMediaSeeking - -#ifndef __CTLUTIL__ -#define __CTLUTIL__ - -// OLE Automation has different ideas of TRUE and FALSE - -#define OATRUE (-1) -#define OAFALSE (0) - - -// It's possible that we could replace this class with CreateStdDispatch - -class CBaseDispatch -{ - ITypeInfo * m_pti; - -public: - - CBaseDispatch() : m_pti(NULL) {} - ~CBaseDispatch(); - - /* IDispatch methods */ - STDMETHODIMP GetTypeInfoCount(__out UINT * pctinfo); - - STDMETHODIMP GetTypeInfo( - REFIID riid, - UINT itinfo, - LCID lcid, - __deref_out ITypeInfo ** pptinfo); - - STDMETHODIMP GetIDsOfNames( - REFIID riid, - __in_ecount(cNames) LPOLESTR * rgszNames, - UINT cNames, - LCID lcid, - __out_ecount(cNames) DISPID * rgdispid); -}; - - -class AM_NOVTABLE CMediaControl : - public IMediaControl, - public CUnknown -{ - CBaseDispatch m_basedisp; - -public: - - CMediaControl(const TCHAR *, LPUNKNOWN); - - DECLARE_IUNKNOWN - - // override this to publicise our interfaces - STDMETHODIMP NonDelegatingQueryInterface(REFIID riid, __deref_out void **ppv); - - /* IDispatch methods */ - STDMETHODIMP GetTypeInfoCount(__out UINT * pctinfo); - - STDMETHODIMP GetTypeInfo( - UINT itinfo, - LCID lcid, - __deref_out ITypeInfo ** pptinfo); - - STDMETHODIMP GetIDsOfNames( - REFIID riid, - __in_ecount(cNames) LPOLESTR * rgszNames, - UINT cNames, - LCID lcid, - __out_ecount(cNames) DISPID * rgdispid); - - STDMETHODIMP Invoke( - DISPID dispidMember, - REFIID riid, - LCID lcid, - WORD wFlags, - __in DISPPARAMS * pdispparams, - __out_opt VARIANT * pvarResult, - __out_opt EXCEPINFO * pexcepinfo, - __out_opt UINT * puArgErr); -}; - - -class AM_NOVTABLE CMediaEvent : - public IMediaEventEx, - public CUnknown -{ - CBaseDispatch m_basedisp; - -public: - - CMediaEvent(__in_opt LPCTSTR, __in_opt LPUNKNOWN); - - DECLARE_IUNKNOWN - - // override this to publicise our interfaces - STDMETHODIMP NonDelegatingQueryInterface(REFIID riid, __deref_out void **ppv); - - /* IDispatch methods */ - STDMETHODIMP GetTypeInfoCount(__out UINT * pctinfo); - - STDMETHODIMP GetTypeInfo( - UINT itinfo, - LCID lcid, - __deref_out ITypeInfo ** pptinfo); - - STDMETHODIMP GetIDsOfNames( - REFIID riid, - __in_ecount(cNames) LPOLESTR * rgszNames, - UINT cNames, - LCID lcid, - __out_ecount(cNames) DISPID * rgdispid); - - STDMETHODIMP Invoke( - DISPID dispidMember, - REFIID riid, - LCID lcid, - WORD wFlags, - __in DISPPARAMS * pdispparams, - __out_opt VARIANT * pvarResult, - __out_opt EXCEPINFO * pexcepinfo, - __out_opt UINT * puArgErr); -}; - - -class AM_NOVTABLE CMediaPosition : - public IMediaPosition, - public CUnknown -{ - CBaseDispatch m_basedisp; - - -public: - - CMediaPosition(__in_opt LPCTSTR, __in_opt LPUNKNOWN); - CMediaPosition(__in_opt LPCTSTR, __in_opt LPUNKNOWN, __inout HRESULT *phr); - - DECLARE_IUNKNOWN - - // override this to publicise our interfaces - STDMETHODIMP NonDelegatingQueryInterface(REFIID riid, __deref_out void **ppv); - - /* IDispatch methods */ - STDMETHODIMP GetTypeInfoCount(__out UINT * pctinfo); - - STDMETHODIMP GetTypeInfo( - UINT itinfo, - LCID lcid, - __deref_out ITypeInfo ** pptinfo); - - STDMETHODIMP GetIDsOfNames( - REFIID riid, - __in_ecount(cNames) LPOLESTR * rgszNames, - UINT cNames, - LCID lcid, - __out_ecount(cNames) DISPID * rgdispid); - - STDMETHODIMP Invoke( - DISPID dispidMember, - REFIID riid, - LCID lcid, - WORD wFlags, - __in DISPPARAMS * pdispparams, - __out_opt VARIANT * pvarResult, - __out_opt EXCEPINFO * pexcepinfo, - __out_opt UINT * puArgErr); - -}; - - -// OA-compatibility means that we must use double as the RefTime value, -// and REFERENCE_TIME (essentially a LONGLONG) within filters. -// this class converts between the two - -class COARefTime : public CRefTime { -public: - - COARefTime() { - }; - - COARefTime(CRefTime t) - : CRefTime(t) - { - }; - - COARefTime(REFERENCE_TIME t) - : CRefTime(t) - { - }; - - COARefTime(double d) { - m_time = (LONGLONG) (d * 10000000); - }; - - operator double() { - return double(m_time) / 10000000; - }; - - operator REFERENCE_TIME() { - return m_time; - }; - - COARefTime& operator=(const double& rd) { - m_time = (LONGLONG) (rd * 10000000); - return *this; - } - - COARefTime& operator=(const REFERENCE_TIME& rt) { - m_time = rt; - return *this; - } - - inline BOOL operator==(const COARefTime& rt) - { - return m_time == rt.m_time; - }; - - inline BOOL operator!=(const COARefTime& rt) - { - return m_time != rt.m_time; - }; - - inline BOOL operator < (const COARefTime& rt) - { - return m_time < rt.m_time; - }; - - inline BOOL operator > (const COARefTime& rt) - { - return m_time > rt.m_time; - }; - - inline BOOL operator >= (const COARefTime& rt) - { - return m_time >= rt.m_time; - }; - - inline BOOL operator <= (const COARefTime& rt) - { - return m_time <= rt.m_time; - }; - - inline COARefTime operator+(const COARefTime& rt) - { - return COARefTime(m_time + rt.m_time); - }; - - inline COARefTime operator-(const COARefTime& rt) - { - return COARefTime(m_time - rt.m_time); - }; - - inline COARefTime operator*(LONG l) - { - return COARefTime(m_time * l); - }; - - inline COARefTime operator/(LONG l) - { - return COARefTime(m_time / l); - }; - -private: - // Prevent bugs from constructing from LONG (which gets - // converted to double and then multiplied by 10000000 - COARefTime(LONG); - LONG operator=(LONG); -}; - - -// A utility class that handles IMediaPosition and IMediaSeeking on behalf -// of single-input pin renderers, or transform filters. -// -// Renderers will expose this from the filter; transform filters will -// expose it from the output pin and not the renderer. -// -// Create one of these, giving it your IPin* for your input pin, and delegate -// all IMediaPosition methods to it. It will query the input pin for -// IMediaPosition and respond appropriately. -// -// Call ForceRefresh if the pin connection changes. -// -// This class no longer caches the upstream IMediaPosition or IMediaSeeking -// it acquires it on each method call. This means ForceRefresh is not needed. -// The method is kept for source compatibility and to minimise the changes -// if we need to put it back later for performance reasons. - -class CPosPassThru : public IMediaSeeking, public CMediaPosition -{ - IPin *m_pPin; - - HRESULT GetPeer(__deref_out IMediaPosition **ppMP); - HRESULT GetPeerSeeking(__deref_out IMediaSeeking **ppMS); - -public: - - CPosPassThru(__in_opt LPCTSTR, __in_opt LPUNKNOWN, __inout HRESULT*, IPin *); - DECLARE_IUNKNOWN - - HRESULT ForceRefresh() { - return S_OK; - }; - - // override to return an accurate current position - virtual HRESULT GetMediaTime(__out LONGLONG *pStartTime, __out_opt LONGLONG *pEndTime) { - return E_FAIL; - } - - STDMETHODIMP NonDelegatingQueryInterface(REFIID riid,__deref_out void **ppv); - - // IMediaSeeking methods - STDMETHODIMP GetCapabilities( __out DWORD * pCapabilities ); - STDMETHODIMP CheckCapabilities( __inout DWORD * pCapabilities ); - STDMETHODIMP SetTimeFormat(const GUID * pFormat); - STDMETHODIMP GetTimeFormat(__out GUID *pFormat); - STDMETHODIMP IsUsingTimeFormat(const GUID * pFormat); - STDMETHODIMP IsFormatSupported( const GUID * pFormat); - STDMETHODIMP QueryPreferredFormat( __out GUID *pFormat); - STDMETHODIMP ConvertTimeFormat(__out LONGLONG * pTarget, - __in_opt const GUID * pTargetFormat, - LONGLONG Source, - __in_opt const GUID * pSourceFormat ); - STDMETHODIMP SetPositions( __inout_opt LONGLONG * pCurrent, DWORD CurrentFlags - , __inout_opt LONGLONG * pStop, DWORD StopFlags ); - - STDMETHODIMP GetPositions( __out_opt LONGLONG * pCurrent, __out_opt LONGLONG * pStop ); - STDMETHODIMP GetCurrentPosition( __out LONGLONG * pCurrent ); - STDMETHODIMP GetStopPosition( __out LONGLONG * pStop ); - STDMETHODIMP SetRate( double dRate); - STDMETHODIMP GetRate( __out double * pdRate); - STDMETHODIMP GetDuration( __out LONGLONG *pDuration); - STDMETHODIMP GetAvailable( __out_opt LONGLONG *pEarliest, __out_opt LONGLONG *pLatest ); - STDMETHODIMP GetPreroll( __out LONGLONG *pllPreroll ); - - // IMediaPosition properties - STDMETHODIMP get_Duration(__out REFTIME * plength); - STDMETHODIMP put_CurrentPosition(REFTIME llTime); - STDMETHODIMP get_StopTime(__out REFTIME * pllTime); - STDMETHODIMP put_StopTime(REFTIME llTime); - STDMETHODIMP get_PrerollTime(__out REFTIME * pllTime); - STDMETHODIMP put_PrerollTime(REFTIME llTime); - STDMETHODIMP get_Rate(__out double * pdRate); - STDMETHODIMP put_Rate(double dRate); - STDMETHODIMP get_CurrentPosition(__out REFTIME * pllTime); - STDMETHODIMP CanSeekForward(__out LONG *pCanSeekForward); - STDMETHODIMP CanSeekBackward(__out LONG *pCanSeekBackward); - -private: - HRESULT GetSeekingLongLong( HRESULT (__stdcall IMediaSeeking::*pMethod)( LONGLONG * ), - __out LONGLONG * pll ); -}; - - -// Adds the ability to return a current position - -class CRendererPosPassThru : public CPosPassThru -{ - CCritSec m_PositionLock; // Locks access to our position - LONGLONG m_StartMedia; // Start media time last seen - LONGLONG m_EndMedia; // And likewise the end media - BOOL m_bReset; // Have media times been set - -public: - - // Used to help with passing media times through graph - - CRendererPosPassThru(__in_opt LPCTSTR, __in_opt LPUNKNOWN, __inout HRESULT*, IPin *); - HRESULT RegisterMediaTime(IMediaSample *pMediaSample); - HRESULT RegisterMediaTime(LONGLONG StartTime,LONGLONG EndTime); - HRESULT GetMediaTime(__out LONGLONG *pStartTime,__out_opt LONGLONG *pEndTime); - HRESULT ResetMediaTime(); - HRESULT EOS(); -}; - -STDAPI CreatePosPassThru( - __in_opt LPUNKNOWN pAgg, - BOOL bRenderer, - IPin *pPin, - __deref_out IUnknown **ppPassThru -); - -// A class that handles the IDispatch part of IBasicAudio and leaves the -// properties and methods themselves pure virtual. - -class AM_NOVTABLE CBasicAudio : public IBasicAudio, public CUnknown -{ - CBaseDispatch m_basedisp; - -public: - - CBasicAudio(__in_opt LPCTSTR, __in_opt LPUNKNOWN); - - DECLARE_IUNKNOWN - - // override this to publicise our interfaces - STDMETHODIMP NonDelegatingQueryInterface(REFIID riid, __deref_out void **ppv); - - /* IDispatch methods */ - STDMETHODIMP GetTypeInfoCount(__out UINT * pctinfo); - - STDMETHODIMP GetTypeInfo( - UINT itinfo, - LCID lcid, - __deref_out ITypeInfo ** pptinfo); - - STDMETHODIMP GetIDsOfNames( - REFIID riid, - __in_ecount(cNames) LPOLESTR * rgszNames, - UINT cNames, - LCID lcid, - __out_ecount(cNames) DISPID * rgdispid); - - STDMETHODIMP Invoke( - DISPID dispidMember, - REFIID riid, - LCID lcid, - WORD wFlags, - __in DISPPARAMS * pdispparams, - __out_opt VARIANT * pvarResult, - __out_opt EXCEPINFO * pexcepinfo, - __out_opt UINT * puArgErr); -}; - - -// A class that handles the IDispatch part of IBasicVideo and leaves the -// properties and methods themselves pure virtual. - -class AM_NOVTABLE CBaseBasicVideo : public IBasicVideo2, public CUnknown -{ - CBaseDispatch m_basedisp; - -public: - - CBaseBasicVideo(__in_opt LPCTSTR, __in_opt LPUNKNOWN); - - DECLARE_IUNKNOWN - - // override this to publicise our interfaces - STDMETHODIMP NonDelegatingQueryInterface(REFIID riid, __deref_out void **ppv); - - /* IDispatch methods */ - STDMETHODIMP GetTypeInfoCount(__out UINT * pctinfo); - - STDMETHODIMP GetTypeInfo( - UINT itinfo, - LCID lcid, - __deref_out ITypeInfo ** pptinfo); - - STDMETHODIMP GetIDsOfNames( - REFIID riid, - __in_ecount(cNames) LPOLESTR * rgszNames, - UINT cNames, - LCID lcid, - __out_ecount(cNames) DISPID * rgdispid); - - STDMETHODIMP Invoke( - DISPID dispidMember, - REFIID riid, - LCID lcid, - WORD wFlags, - __in DISPPARAMS * pdispparams, - __out_opt VARIANT * pvarResult, - __out_opt EXCEPINFO * pexcepinfo, - __out_opt UINT * puArgErr); - - STDMETHODIMP GetPreferredAspectRatio( - __out long *plAspectX, - __out long *plAspectY) - { - return E_NOTIMPL; - } -}; - - -// A class that handles the IDispatch part of IVideoWindow and leaves the -// properties and methods themselves pure virtual. - -class AM_NOVTABLE CBaseVideoWindow : public IVideoWindow, public CUnknown -{ - CBaseDispatch m_basedisp; - -public: - - CBaseVideoWindow(__in_opt LPCTSTR, __in_opt LPUNKNOWN); - - DECLARE_IUNKNOWN - - // override this to publicise our interfaces - STDMETHODIMP NonDelegatingQueryInterface(REFIID riid, __deref_out void **ppv); - - /* IDispatch methods */ - STDMETHODIMP GetTypeInfoCount(__out UINT * pctinfo); - - STDMETHODIMP GetTypeInfo( - UINT itinfo, - LCID lcid, - __deref_out ITypeInfo ** pptinfo); - - STDMETHODIMP GetIDsOfNames( - REFIID riid, - __in_ecount(cNames) LPOLESTR * rgszNames, - UINT cNames, - LCID lcid, - __out_ecount(cNames) DISPID * rgdispid); - - STDMETHODIMP Invoke( - DISPID dispidMember, - REFIID riid, - LCID lcid, - WORD wFlags, - __in DISPPARAMS * pdispparams, - __out_opt VARIANT * pvarResult, - __out_opt EXCEPINFO * pexcepinfo, - __out_opt UINT * puArgErr); -}; - - -// abstract class to help source filters with their implementation -// of IMediaPosition. Derive from this and set the duration (and stop -// position). Also override NotifyChange to do something when the properties -// change. - -class AM_NOVTABLE CSourcePosition : public CMediaPosition -{ - -public: - CSourcePosition(__in_opt LPCTSTR, __in_opt LPUNKNOWN, __inout HRESULT*, __in CCritSec *); - - // IMediaPosition methods - STDMETHODIMP get_Duration(__out REFTIME * plength); - STDMETHODIMP put_CurrentPosition(REFTIME llTime); - STDMETHODIMP get_StopTime(__out REFTIME * pllTime); - STDMETHODIMP put_StopTime(REFTIME llTime); - STDMETHODIMP get_PrerollTime(__out REFTIME * pllTime); - STDMETHODIMP put_PrerollTime(REFTIME llTime); - STDMETHODIMP get_Rate(__out double * pdRate); - STDMETHODIMP put_Rate(double dRate); - STDMETHODIMP CanSeekForward(__out LONG *pCanSeekForward); - STDMETHODIMP CanSeekBackward(__out LONG *pCanSeekBackward); - - // override if you can return the data you are actually working on - STDMETHODIMP get_CurrentPosition(__out REFTIME * pllTime) { - return E_NOTIMPL; - }; - -protected: - - // we call this to notify changes. Override to handle them - virtual HRESULT ChangeStart() PURE; - virtual HRESULT ChangeStop() PURE; - virtual HRESULT ChangeRate() PURE; - - COARefTime m_Duration; - COARefTime m_Start; - COARefTime m_Stop; - double m_Rate; - - CCritSec * m_pLock; -}; - -class AM_NOVTABLE CSourceSeeking : - public IMediaSeeking, - public CUnknown -{ - -public: - - DECLARE_IUNKNOWN; - STDMETHODIMP NonDelegatingQueryInterface(REFIID riid, __deref_out void **ppv); - - // IMediaSeeking methods - - STDMETHODIMP IsFormatSupported(const GUID * pFormat); - STDMETHODIMP QueryPreferredFormat(__out GUID *pFormat); - STDMETHODIMP SetTimeFormat(const GUID * pFormat); - STDMETHODIMP IsUsingTimeFormat(const GUID * pFormat); - STDMETHODIMP GetTimeFormat(__out GUID *pFormat); - STDMETHODIMP GetDuration(__out LONGLONG *pDuration); - STDMETHODIMP GetStopPosition(__out LONGLONG *pStop); - STDMETHODIMP GetCurrentPosition(__out LONGLONG *pCurrent); - STDMETHODIMP GetCapabilities( __out DWORD * pCapabilities ); - STDMETHODIMP CheckCapabilities( __inout DWORD * pCapabilities ); - STDMETHODIMP ConvertTimeFormat( __out LONGLONG * pTarget, - __in_opt const GUID * pTargetFormat, - LONGLONG Source, - __in_opt const GUID * pSourceFormat ); - - STDMETHODIMP SetPositions( __inout_opt LONGLONG * pCurrent, DWORD CurrentFlags - , __inout_opt LONGLONG * pStop, DWORD StopFlags ); - - STDMETHODIMP GetPositions( __out_opt LONGLONG * pCurrent, __out_opt LONGLONG * pStop ); - - STDMETHODIMP GetAvailable( __out_opt LONGLONG * pEarliest, __out_opt LONGLONG * pLatest ); - STDMETHODIMP SetRate( double dRate); - STDMETHODIMP GetRate( __out double * pdRate); - STDMETHODIMP GetPreroll(__out LONGLONG *pPreroll); - - -protected: - - // ctor - CSourceSeeking(__in_opt LPCTSTR, __in_opt LPUNKNOWN, __inout HRESULT*, __in CCritSec *); - - // we call this to notify changes. Override to handle them - virtual HRESULT ChangeStart() PURE; - virtual HRESULT ChangeStop() PURE; - virtual HRESULT ChangeRate() PURE; - - CRefTime m_rtDuration; // length of stream - CRefTime m_rtStart; // source will start here - CRefTime m_rtStop; // source will stop here - double m_dRateSeeking; - - // seeking capabilities - DWORD m_dwSeekingCaps; - - CCritSec * m_pLock; -}; - - -// Base classes supporting Deferred commands. - -// Deferred commands are queued by calls to methods on the IQueueCommand -// interface, exposed by the filtergraph and by some filters. A successful -// call to one of these methods will return an IDeferredCommand interface -// representing the queued command. -// -// A CDeferredCommand object represents a single deferred command, and exposes -// the IDeferredCommand interface as well as other methods permitting time -// checks and actual execution. It contains a reference to the CCommandQueue -// object on which it is queued. -// -// CCommandQueue is a base class providing a queue of CDeferredCommand -// objects, and methods to add, remove, check status and invoke the queued -// commands. A CCommandQueue object would be part of an object that -// implemented IQueueCommand. - -class CCmdQueue; - -// take a copy of the params and store them. Release any allocated -// memory in destructor - -class CDispParams : public DISPPARAMS -{ -public: - CDispParams(UINT nArgs, __in_ecount(nArgs) VARIANT* pArgs, __inout_opt HRESULT *phr = NULL); - ~CDispParams(); -}; - - -// CDeferredCommand lifetime is controlled by refcounts. Caller of -// InvokeAt.. gets a refcounted interface pointer, and the CCmdQueue -// object also holds a refcount on us. Calling Cancel or Invoke takes -// us off the CCmdQueue and thus reduces the refcount by 1. Once taken -// off the queue we cannot be put back on the queue. - -class CDeferredCommand - : public CUnknown, - public IDeferredCommand -{ -public: - - CDeferredCommand( - __inout CCmdQueue * pQ, - __in_opt LPUNKNOWN pUnk, // aggregation outer unk - __inout HRESULT * phr, - __in LPUNKNOWN pUnkExecutor, // object that will execute this cmd - REFTIME time, - __in GUID* iid, - long dispidMethod, - short wFlags, - long cArgs, - __in_ecount(cArgs) VARIANT* pDispParams, - __out VARIANT* pvarResult, - __out short* puArgErr, - BOOL bStream - ); - - DECLARE_IUNKNOWN - - // override this to publicise our interfaces - STDMETHODIMP NonDelegatingQueryInterface(REFIID riid, __out void **ppv); - - // IDeferredCommand methods - STDMETHODIMP Cancel(); - STDMETHODIMP Confidence( - __out LONG* pConfidence); - STDMETHODIMP Postpone( - REFTIME newtime); - STDMETHODIMP GetHResult( - __out HRESULT* phrResult); - - // other public methods - - HRESULT Invoke(); - - // access methods - - // returns TRUE if streamtime, FALSE if presentation time - BOOL IsStreamTime() { - return m_bStream; - }; - - CRefTime GetTime() { - return m_time; - }; - - REFIID GetIID() { - return *m_iid; - }; - - long GetMethod() { - return m_dispidMethod; - }; - - short GetFlags() { - return m_wFlags; - }; - - DISPPARAMS* GetParams() { - return &m_DispParams; - }; - - VARIANT* GetResult() { - return m_pvarResult; - }; - -protected: - - CCmdQueue* m_pQueue; - - // pUnk for the interface that we will execute the command on - LPUNKNOWN m_pUnk; - - // stored command data - REFERENCE_TIME m_time; - GUID* m_iid; - long m_dispidMethod; - short m_wFlags; - VARIANT* m_pvarResult; - BOOL m_bStream; - CDispParams m_DispParams; - DISPID m_DispId; // For get and put - - // we use this for ITypeInfo access - CBaseDispatch m_Dispatch; - - // save retval here - HRESULT m_hrResult; -}; - - -// a list of CDeferredCommand objects. this is a base class providing -// the basics of access to the list. If you want to use CDeferredCommand -// objects then your queue needs to be derived from this class. - -class AM_NOVTABLE CCmdQueue -{ -public: - CCmdQueue(__inout_opt HRESULT *phr = NULL); - virtual ~CCmdQueue(); - - // returns a new CDeferredCommand object that will be initialised with - // the parameters and will be added to the queue during construction. - // returns S_OK if successfully created otherwise an error and - // no object has been queued. - virtual HRESULT New( - __out CDeferredCommand **ppCmd, - __in LPUNKNOWN pUnk, - REFTIME time, - __in GUID* iid, - long dispidMethod, - short wFlags, - long cArgs, - __in_ecount(cArgs) VARIANT* pDispParams, - __out VARIANT* pvarResult, - __out short* puArgErr, - BOOL bStream - ); - - // called by the CDeferredCommand object to add and remove itself - // from the queue - virtual HRESULT Insert(__in CDeferredCommand* pCmd); - virtual HRESULT Remove(__in CDeferredCommand* pCmd); - - // Command-Due Checking - // - // There are two schemes of synchronisation: coarse and accurate. In - // coarse mode, you wait till the time arrives and then execute the cmd. - // In accurate mode, you wait until you are processing the sample that - // will appear at the time, and then execute the command. It's up to the - // filter which one it will implement. The filtergraph will always - // implement coarse mode for commands queued at the filtergraph. - // - // If you want coarse sync, you probably want to wait until there is a - // command due, and then execute it. You can do this by calling - // GetDueCommand. If you have several things to wait for, get the - // event handle from GetDueHandle() and when this is signalled then call - // GetDueCommand. Stream time will only advance between calls to Run and - // EndRun. Note that to avoid an extra thread there is no guarantee that - // if the handle is set there will be a command ready. Each time the - // event is signalled, call GetDueCommand (probably with a 0 timeout); - // This may return E_ABORT. - // - // If you want accurate sync, you must call GetCommandDueFor, passing - // as a parameter the stream time of the samples you are about to process. - // This will return: - // -- a stream-time command due at or before that stream time - // -- a presentation-time command due at or before the - // time that stream time will be presented (only between Run - // and EndRun calls, since outside of this, the mapping from - // stream time to presentation time is not known. - // -- any presentation-time command due now. - // This means that if you want accurate synchronisation on samples that - // might be processed during Paused mode, you need to use - // stream-time commands. - // - // In all cases, commands remain queued until Invoked or Cancelled. The - // setting and resetting of the event handle is managed entirely by this - // queue object. - - // set the clock used for timing - virtual HRESULT SetSyncSource(__in_opt IReferenceClock*); - - // switch to run mode. Streamtime to Presentation time mapping known. - virtual HRESULT Run(REFERENCE_TIME tStreamTimeOffset); - - // switch to Stopped or Paused mode. Time mapping not known. - virtual HRESULT EndRun(); - - // return a pointer to the next due command. Blocks for msTimeout - // milliseconds until there is a due command. - // Stream-time commands will only become due between Run and Endrun calls. - // The command remains queued until invoked or cancelled. - // Returns E_ABORT if timeout occurs, otherwise S_OK (or other error). - // Returns an AddRef-ed object - virtual HRESULT GetDueCommand(__out CDeferredCommand ** ppCmd, long msTimeout); - - // return the event handle that will be signalled whenever - // there are deferred commands due for execution (when GetDueCommand - // will not block). - HANDLE GetDueHandle() { - return HANDLE(m_evDue); - }; - - // return a pointer to a command that will be due for a given time. - // Pass in a stream time here. The stream time offset will be passed - // in via the Run method. - // Commands remain queued until invoked or cancelled. - // This method will not block. It will report VFW_E_NOT_FOUND if there - // are no commands due yet. - // Returns an AddRef-ed object - virtual HRESULT GetCommandDueFor(REFERENCE_TIME tStream, __out CDeferredCommand**ppCmd); - - // check if a given time is due (TRUE if it is due yet) - BOOL CheckTime(CRefTime time, BOOL bStream) { - - // if no clock, nothing is due! - if (!m_pClock) { - return FALSE; - } - - // stream time - if (bStream) { - - // not valid if not running - if (!m_bRunning) { - return FALSE; - } - // add on known stream time offset to get presentation time - time += m_StreamTimeOffset; - } - - CRefTime Now; - m_pClock->GetTime((REFERENCE_TIME*)&Now); - return (time <= Now); - }; - -protected: - - // protect access to lists etc - CCritSec m_Lock; - - // commands queued in presentation time are stored here - CGenericList m_listPresentation; - - // commands queued in stream time are stored here - CGenericList m_listStream; - - // set when any commands are due - CAMEvent m_evDue; - - // creates an advise for the earliest time required, if any - void SetTimeAdvise(void); - - // advise id from reference clock (0 if no outstanding advise) - DWORD_PTR m_dwAdvise; - - // advise time is for this presentation time - CRefTime m_tCurrentAdvise; - - // the reference clock we are using (addrefed) - IReferenceClock* m_pClock; - - // true when running - BOOL m_bRunning; - - // contains stream time offset when m_bRunning is true - CRefTime m_StreamTimeOffset; -}; - -#endif // __CTLUTIL__ diff --git a/UnityWebcam/UnityCamService/includes/ddmm.h b/UnityWebcam/UnityCamService/includes/ddmm.h deleted file mode 100644 index c773d58..0000000 --- a/UnityWebcam/UnityCamService/includes/ddmm.h +++ /dev/null @@ -1,28 +0,0 @@ -//------------------------------------------------------------------------------ -// File: DDMM.h -// -// Desc: DirectShow base classes - efines routines for using DirectDraw -// on a multimonitor system. -// -// Copyright (c) 1995-2001 Microsoft Corporation. All rights reserved. -//------------------------------------------------------------------------------ - - -#ifdef __cplusplus -extern "C" { /* Assume C declarations for C++ */ -#endif /* __cplusplus */ - -// DDRAW.H might not include these -#ifndef DDENUM_ATTACHEDSECONDARYDEVICES -#define DDENUM_ATTACHEDSECONDARYDEVICES 0x00000001L -#endif - -typedef HRESULT (*PDRAWCREATE)(IID *,LPDIRECTDRAW *,LPUNKNOWN); -typedef HRESULT (*PDRAWENUM)(LPDDENUMCALLBACKA, LPVOID); - -IDirectDraw * DirectDrawCreateFromDevice(__in_opt LPSTR, PDRAWCREATE, PDRAWENUM); -IDirectDraw * DirectDrawCreateFromDeviceEx(__in_opt LPSTR, PDRAWCREATE, LPDIRECTDRAWENUMERATEEXA); - -#ifdef __cplusplus -} -#endif /* __cplusplus */ diff --git a/UnityWebcam/UnityCamService/includes/dllsetup.h b/UnityWebcam/UnityCamService/includes/dllsetup.h deleted file mode 100644 index aaac2ec..0000000 --- a/UnityWebcam/UnityCamService/includes/dllsetup.h +++ /dev/null @@ -1,46 +0,0 @@ -//------------------------------------------------------------------------------ -// File: DllSetup.h -// -// Desc: DirectShow base classes. -// -// Copyright (c) 1992-2001 Microsoft Corporation. All rights reserved. -//------------------------------------------------------------------------------ - - -// To be self registering, OLE servers must -// export functions named DllRegisterServer -// and DllUnregisterServer. To allow use of -// custom and default implementations the -// defaults are named AMovieDllRegisterServer -// and AMovieDllUnregisterServer. -// -// To the use the default implementation you -// must provide stub functions. -// -// i.e. STDAPI DllRegisterServer() -// { -// return AMovieDllRegisterServer(); -// } -// -// STDAPI DllUnregisterServer() -// { -// return AMovieDllUnregisterServer(); -// } -// -// -// AMovieDllRegisterServer calls IAMovieSetup.Register(), and -// AMovieDllUnregisterServer calls IAMovieSetup.Unregister(). - -STDAPI AMovieDllRegisterServer2( BOOL ); -STDAPI AMovieDllRegisterServer(); -STDAPI AMovieDllUnregisterServer(); - -// helper functions -STDAPI EliminateSubKey( HKEY, LPCTSTR ); - - -STDAPI -AMovieSetupRegisterFilter2( const AMOVIESETUP_FILTER * const psetupdata - , IFilterMapper2 * pIFM2 - , BOOL bRegister ); - diff --git a/UnityWebcam/UnityCamService/includes/dxmperf.h b/UnityWebcam/UnityCamService/includes/dxmperf.h deleted file mode 100644 index dc58ad7..0000000 --- a/UnityWebcam/UnityCamService/includes/dxmperf.h +++ /dev/null @@ -1,250 +0,0 @@ -//------------------------------------------------------------------------------ -// File: DXMPerf.h -// -// Desc: Macros for DirectShow performance logging. -// -// Copyright (c) 1992-2001 Microsoft Corporation. All rights reserved. -//------------------------------------------------------------------------------ - - -#ifndef _DXMPERF_H_ -#define _DXMPERF_H_ - -#include -#include "perflog.h" - -#ifdef _IA64_ -extern "C" unsigned __int64 __getReg( int whichReg ); -#pragma intrinsic(__getReg) -#endif // _IA64_ - - -inline ULONGLONG _RDTSC( void ) { -#ifdef _X86_ - LARGE_INTEGER li; - __asm { - _emit 0x0F - _emit 0x31 - mov li.LowPart,eax - mov li.HighPart,edx - } - return li.QuadPart; - -#if 0 // This isn't tested yet - -#elif defined (_IA64_) - -#define INL_REGID_APITC 3116 - return __getReg( INL_REGID_APITC ); - -#endif // 0 - -#else // unsupported platform - // not implemented on non x86/IA64 platforms - return 0; -#endif // _X86_/_IA64_ -} - -#define DXMPERF_VIDEOREND 0x00000001 -#define DXMPERF_AUDIOGLITCH 0x00000002 -//#define GETTIME_BIT 0x00000001 -//#define AUDIOREND_BIT 0x00000004 -//#define FRAMEDROP_BIT 0x00000008 -#define AUDIOBREAK_BIT 0x00000010 -#define DXMPERF_AUDIORECV 0x00000020 -#define DXMPERF_AUDIOSLAVE 0x00000040 -#define DXMPERF_AUDIOBREAK 0x00000080 - -#define PERFLOG_CTOR( name, iface ) -#define PERFLOG_DTOR( name, iface ) -#define PERFLOG_DELIVER( name, source, dest, sample, pmt ) -#define PERFLOG_RECEIVE( name, source, dest, sample, pmt ) -#define PERFLOG_RUN( name, iface, time, oldstate ) -#define PERFLOG_PAUSE( name, iface, oldstate ) -#define PERFLOG_STOP( name, iface, oldstate ) -#define PERFLOG_JOINGRAPH( name, iface, graph ) -#define PERFLOG_GETBUFFER( allocator, sample ) -#define PERFLOG_RELBUFFER( allocator, sample ) -#define PERFLOG_CONNECT( connector, connectee, status, pmt ) -#define PERFLOG_RXCONNECT( connector, connectee, status, pmt ) -#define PERFLOG_DISCONNECT( disconnector, disconnectee, status ) - -#define PERFLOG_GETTIME( clock, time ) /*{ \ - PERFINFO_WMI_GETTIME perfData; \ - if (NULL != g_pTraceEvent) { \ - memset( &perfData, 0, sizeof( perfData ) ); \ - perfData.header.Size = sizeof( perfData ); \ - perfData.header.Flags = WNODE_FLAG_TRACED_GUID; \ - perfData.header.Guid = GUID_GETTIME; \ - perfData.data.cycleCounter = _RDTSC(); \ - perfData.data.dshowClock = (ULONGLONG) (time); \ - if (g_perfMasks[GETTIME_INDEX] & GETTIME_BIT) \ - (*g_pTraceEvent)( g_traceHandle, (PEVENT_TRACE_HEADER) &perfData ); \ - } \ - }*/ - -#define PERFLOG_AUDIOREND( clocktime, sampletime, psample, bytetime, cbytes ) /*{ \ - PERFINFO_WMI_AVREND perfData; \ - if (NULL != g_pTraceEvent) { \ - memset( &perfData, 0, sizeof( perfData ) ); \ - perfData.header.Size = sizeof( perfData ); \ - perfData.header.Flags = WNODE_FLAG_TRACED_GUID; \ - perfData.header.Guid = GUID_AUDIOREND; \ - perfData.data.cycleCounter = _RDTSC(); \ - perfData.data.dshowClock = (clocktime); \ - perfData.data.sampleTime = (sampletime); \ - if (g_perfMasks[AUDIOREND_INDEX] & AUDIOREND_BIT) \ - (*g_pTraceEvent)( g_traceHandle, (PEVENT_TRACE_HEADER) &perfData ); \ - } \ - }*/ - -#define PERFLOG_AUDIORECV(StreamTime,SampleStart,SampleStop,Discontinuity,Duration) \ - if (PerflogEnableFlags & DXMPERF_AUDIORECV) { \ - PERFINFO_WMI_AUDIORECV perfData; \ - memset( &perfData, 0, sizeof( perfData ) ); \ - perfData.header.Size = sizeof( perfData ); \ - perfData.header.Flags = WNODE_FLAG_TRACED_GUID; \ - perfData.header.Guid = GUID_AUDIORECV; \ - perfData.data.streamTime = StreamTime; \ - perfData.data.sampleStart = SampleStart; \ - perfData.data.sampleStop = SampleStop; \ - perfData.data.discontinuity = Discontinuity; \ - perfData.data.hwduration = Duration; \ - PerflogTraceEvent((PEVENT_TRACE_HEADER) &perfData); \ - } - -#define PERFLOG_AUDIOSLAVE(MasterClock,SlaveClock,ErrorAccum,LastHighErrorSeen,LastLowErrorSeen) \ - if (PerflogEnableFlags & DXMPERF_AUDIOSLAVE) { \ - PERFINFO_WMI_AUDIOSLAVE perfData; \ - memset( &perfData, 0, sizeof( perfData ) ); \ - perfData.header.Size = sizeof( perfData ); \ - perfData.header.Flags = WNODE_FLAG_TRACED_GUID; \ - perfData.header.Guid = GUID_AUDIOSLAVE; \ - perfData.data.masterClock = MasterClock; \ - perfData.data.slaveClock = SlaveClock; \ - perfData.data.errorAccum = ErrorAccum; \ - perfData.data.lastHighErrorSeen = LastHighErrorSeen;\ - perfData.data.lastLowErrorSeen = LastLowErrorSeen; \ - PerflogTraceEvent((PEVENT_TRACE_HEADER) &perfData); \ - } - -#define PERFLOG_AUDIOADDBREAK(IterNextWrite,OffsetNextWrite,IterWrite,OffsetWrite) \ - if (PerflogEnableFlags & DXMPERF_AUDIOBREAK) { \ - PERFINFO_WMI_AUDIOADDBREAK perfData; \ - memset( &perfData, 0, sizeof( perfData ) ); \ - perfData.header.Size = sizeof( perfData ); \ - perfData.header.Flags = WNODE_FLAG_TRACED_GUID; \ - perfData.header.Guid = GUID_AUDIOADDBREAK; \ - perfData.data.iterNextWrite = IterNextWrite; \ - perfData.data.offsetNextWrite = OffsetNextWrite; \ - perfData.data.iterWrite = IterWrite; \ - perfData.data.offsetWrite = OffsetWrite; \ - PerflogTraceEvent((PEVENT_TRACE_HEADER) &perfData); \ - } - -#define PERFLOG_VIDEOREND( sampletime, clocktime, psample ) \ - if (PerflogEnableFlags & DXMPERF_VIDEOREND) { \ - PERFINFO_WMI_AVREND perfData; \ - memset( &perfData, 0, sizeof( perfData ) ); \ - perfData.header.Size = sizeof( perfData ); \ - perfData.header.Flags = WNODE_FLAG_TRACED_GUID; \ - perfData.header.Guid = GUID_VIDEOREND; \ - perfData.data.cycleCounter = _RDTSC(); \ - perfData.data.dshowClock = (clocktime); \ - perfData.data.sampleTime = (sampletime); \ - PerflogTraceEvent ((PEVENT_TRACE_HEADER) &perfData); \ - } - -#define PERFLOG_AUDIOGLITCH( instance, glitchtype, currenttime, previoustime ) \ - if (PerflogEnableFlags & DXMPERF_AUDIOGLITCH) { \ - PERFINFO_WMI_AUDIOGLITCH perfData; \ - memset( &perfData, 0, sizeof( perfData ) ); \ - perfData.header.Size = sizeof( perfData ); \ - perfData.header.Flags = WNODE_FLAG_TRACED_GUID; \ - perfData.header.Guid = GUID_DSOUNDGLITCH; \ - perfData.data.cycleCounter = _RDTSC(); \ - perfData.data.glitchType = (glitchtype); \ - perfData.data.sampleTime = (currenttime); \ - perfData.data.previousTime = (previoustime); \ - perfData.data.instanceId = (instance); \ - PerflogTraceEvent ((PEVENT_TRACE_HEADER) &perfData); \ - } - -#define PERFLOG_FRAMEDROP( sampletime, clocktime, psample, renderer ) /*{ \ - PERFINFO_WMI_FRAMEDROP perfData; \ - if (NULL != g_pTraceEvent) { \ - memset( &perfData, 0, sizeof( perfData ) ); \ - perfData.header.Size = sizeof( perfData ); \ - perfData.header.Flags = WNODE_FLAG_TRACED_GUID; \ - perfData.header.Guid = GUID_FRAMEDROP; \ - perfData.data.cycleCounter = _RDTSC(); \ - perfData.data.dshowClock = (clocktime); \ - perfData.data.frameTime = (sampletime); \ - if (g_perfMasks[FRAMEDROP_INDEX] & FRAMEDROP_BIT) \ - (*g_pTraceEvent)( g_traceHandle, (PEVENT_TRACE_HEADER) &perfData ); \ - } \ - }*/ - -/* -#define PERFLOG_AUDIOBREAK( nextwrite, writepos, msecs ) { \ - PERFINFO_WMI_AUDIOBREAK perfData; \ - if (NULL != g_pTraceEvent) { \ - memset( &perfData, 0, sizeof( perfData ) ); \ - perfData.header.Size = sizeof( perfData ); \ - perfData.header.Flags = WNODE_FLAG_TRACED_GUID; \ - perfData.header.Guid = GUID_AUDIOBREAK; \ - perfData.data.cycleCounter = _RDTSC(); \ - perfData.data.dshowClock = (writepos); \ - perfData.data.sampleTime = (nextwrite); \ - perfData.data.sampleDuration = (msecs); \ - if (g_perfMasks[AUDIOBREAK_INDEX] & AUDIOBREAK_BIT) \ - (*g_pTraceEvent)( g_traceHandle, (PEVENT_TRACE_HEADER) &perfData ); \ - } \ - } -*/ - -#define PERFLOG_AUDIOBREAK( nextwrite, writepos, msecs ) \ - if (PerflogEnableFlags & AUDIOBREAK_BIT) { \ - PERFINFO_WMI_AUDIOBREAK perfData; \ - memset( &perfData, 0, sizeof( perfData ) ); \ - perfData.header.Size = sizeof( perfData ); \ - perfData.header.Flags = WNODE_FLAG_TRACED_GUID; \ - perfData.header.Guid = GUID_AUDIOBREAK; \ - perfData.data.cycleCounter = _RDTSC(); \ - perfData.data.dshowClock = (writepos); \ - perfData.data.sampleTime = (nextwrite); \ - perfData.data.sampleDuration = (msecs); \ - PerflogTraceEvent ((PEVENT_TRACE_HEADER) &perfData); \ - } \ - - -inline -VOID PERFLOG_STREAMTRACE( - ULONG Level, - ULONG Id, - ULONGLONG DShowClock, - ULONGLONG Data1, - ULONGLONG Data2, - ULONGLONG Data3, - ULONGLONG Data4 - ) -{ - if (Level <= PerflogModuleLevel) - { - PERFINFO_WMI_STREAMTRACE perfData; - memset( &perfData, 0, sizeof( perfData ) ); - perfData.header.Size = sizeof( perfData ); - perfData.header.Flags = WNODE_FLAG_TRACED_GUID; - perfData.header.Guid = GUID_STREAMTRACE; - perfData.data.dshowClock = DShowClock; - perfData.data.id = Id; - perfData.data.data[0] = Data1; - perfData.data.data[1] = Data2; - perfData.data.data[2] = Data3; - perfData.data.data[3] = Data4; - PerflogTraceEvent((PEVENT_TRACE_HEADER) &perfData); - } -} - - -#endif // _DXMPERF_H_ diff --git a/UnityWebcam/UnityCamService/includes/fourcc.h b/UnityWebcam/UnityCamService/includes/fourcc.h deleted file mode 100644 index f4f71e9..0000000 --- a/UnityWebcam/UnityCamService/includes/fourcc.h +++ /dev/null @@ -1,101 +0,0 @@ -//------------------------------------------------------------------------------ -// File: FourCC.h -// -// Desc: DirectShow base classes. -// -// Copyright (c) 1992-2001 Microsoft Corporation. All rights reserved. -//------------------------------------------------------------------------------ - - -// FOURCCMap -// -// provides a mapping between old-style multimedia format DWORDs -// and new-style GUIDs. -// -// A range of 4 billion GUIDs has been allocated to ensure that this -// mapping can be done straightforwardly one-to-one in both directions. -// -// January 95 - - -#ifndef __FOURCC__ -#define __FOURCC__ - - -// Multimedia format types are marked with DWORDs built from four 8-bit -// chars and known as FOURCCs. New multimedia AM_MEDIA_TYPE definitions include -// a subtype GUID. In order to simplify the mapping, GUIDs in the range: -// XXXXXXXX-0000-0010-8000-00AA00389B71 -// are reserved for FOURCCs. - -class FOURCCMap : public GUID -{ - -public: - FOURCCMap(); - FOURCCMap(DWORD Fourcc); - FOURCCMap(const GUID *); - - - DWORD GetFOURCC(void); - void SetFOURCC(DWORD fourcc); - void SetFOURCC(const GUID *); - -private: - void InitGUID(); -}; - -#define GUID_Data2 0 -#define GUID_Data3 0x10 -#define GUID_Data4_1 0xaa000080 -#define GUID_Data4_2 0x719b3800 - -inline void -FOURCCMap::InitGUID() { - Data2 = GUID_Data2; - Data3 = GUID_Data3; - ((DWORD *)Data4)[0] = GUID_Data4_1; - ((DWORD *)Data4)[1] = GUID_Data4_2; -} - -inline -FOURCCMap::FOURCCMap() { - InitGUID(); - SetFOURCC( DWORD(0)); -} - -inline -FOURCCMap::FOURCCMap(DWORD fourcc) -{ - InitGUID(); - SetFOURCC(fourcc); -} - -inline -FOURCCMap::FOURCCMap(const GUID * pGuid) -{ - InitGUID(); - SetFOURCC(pGuid); -} - -inline void -FOURCCMap::SetFOURCC(const GUID * pGuid) -{ - FOURCCMap * p = (FOURCCMap*) pGuid; - SetFOURCC(p->GetFOURCC()); -} - -inline void -FOURCCMap::SetFOURCC(DWORD fourcc) -{ - Data1 = fourcc; -} - -inline DWORD -FOURCCMap::GetFOURCC(void) -{ - return Data1; -} - -#endif /* __FOURCC__ */ - diff --git a/UnityWebcam/UnityCamService/includes/measure.h b/UnityWebcam/UnityCamService/includes/measure.h deleted file mode 100644 index 0babc86..0000000 --- a/UnityWebcam/UnityCamService/includes/measure.h +++ /dev/null @@ -1,222 +0,0 @@ -//------------------------------------------------------------------------------ -// File: Measure.h -// -// Desc: DirectShow base classes. -// -// Copyright (c) 1992-2001 Microsoft Corporation. All rights reserved. -//------------------------------------------------------------------------------ - - -/* - The idea is to pepper the source code with interesting measurements and - have the last few thousand of these recorded in a circular buffer that - can be post-processed to give interesting numbers. - - WHAT THE LOG LOOKS LIKE: - - Time (sec) Type Delta Incident_Name - 0.055,41 NOTE -. Incident Nine - Another note - 0.055,42 NOTE 0.000,01 Incident Nine - Another note - 0.055,44 NOTE 0.000,02 Incident Nine - Another note - 0.055,45 STOP -. Incident Eight - Also random - 0.055,47 START -. Incident Seven - Random - 0.055,49 NOTE 0.000,05 Incident Nine - Another note - ------- ---------------- - 0.125,60 STOP 0.000,03 Msr_Stop - 0.125,62 START -. Msr_Start - 0.125,63 START -. Incident Two - Start/Stop - 0.125,65 STOP 0.000,03 Msr_Start - 0.125,66 START -. Msr_Stop - 0.125,68 STOP 0.000,05 Incident Two - Start/Stop - 0.125,70 STOP 0.000,04 Msr_Stop - 0.125,72 START -. Msr_Start - 0.125,73 START -. Incident Two - Start/Stop - 0.125,75 STOP 0.000,03 Msr_Start - 0.125,77 START -. Msr_Stop - 0.125,78 STOP 0.000,05 Incident Two - Start/Stop - 0.125,80 STOP 0.000,03 Msr_Stop - 0.125,81 NOTE -. Incident Three - single Note - 0.125,83 START -. Incident Four - Start, no stop - 0.125,85 START -. Incident Five - Single Start/Stop - 0.125,87 STOP 0.000,02 Incident Five - Single Start/Stop - -Number Average StdDev Smallest Largest Incident_Name - 10 0.000,58 0.000,10 0.000,55 0.000,85 Incident One - Note - 50 0.000,05 0.000,00 0.000,05 0.000,05 Incident Two - Start/Stop - 1 -. -. -. -. Incident Three - single Note - 0 -. -. -. -. Incident Four - Start, no stop - 1 0.000,02 -. 0.000,02 0.000,02 Incident Five - Single Start/Stop - 0 -. -. -. -. Incident Six - zero occurrences - 100 0.000,25 0.000,12 0.000,02 0.000,62 Incident Seven - Random - 100 0.000,79 0.000,48 0.000,02 0.001,92 Incident Eight - Also random - 5895 0.000,01 0.000,01 0.000,01 0.000,56 Incident Nine - Another note - 10 0.000,03 0.000,00 0.000,03 0.000,04 Msr_Note - 50 0.000,03 0.000,00 0.000,03 0.000,04 Msr_Start - 50 0.000,04 0.000,03 0.000,03 0.000,31 Msr_Stop - - WHAT IT MEANS: - The log shows what happened and when. Each line shows the time at which - something happened (see WHAT YOU CODE below) what it was that happened - and (if approporate) the time since the corresponding previous event - (that's the delta column). - - The statistics show how many times each event occurred, what the average - delta time was, also the standard deviation, largest and smalles delta. - - WHAT YOU CODE: - - Before anything else executes: - register your ids - - int id1 = Msr_Register("Incident One - Note"); - int id2 = Msr_Register("Incident Two - Start/Stop"); - int id3 = Msr_Register("Incident Three - single Note"); - etc. - - At interesting moments: - - // To measure a repetitive event - e.g. end of bitblt to screen - Msr_Note(Id9); // e.g. "video frame hiting the screen NOW!" - - or - - // To measure an elapsed time e.g. time taken to decode an MPEG B-frame - Msr_Start(Id2); // e.g. "Starting to decode MPEG B-frame" - . . . - MsrStop(Id2); // "Finished MPEG decode" - - At the end: - - HANDLE hFile; - hFile = CreateFile("Perf.log", GENERIC_WRITE, 0, NULL, CREATE_ALWAYS, 0, NULL); - Msr_Dump(hFile); // This writes the log out to the file - CloseHandle(hFile); - - or - - Msr_Dump(NULL); // This writes it to DbgLog((LOG_TRACE,0, ... )); - // but if you are writing it out to the debugger - // then the times are probably all garbage because - // the debugger can make things run awfully slow. - - A given id should be used either for start / stop or Note calls. If Notes - are mixed in with Starts and Stops their statistics will be gibberish. - - If you code the calls in upper case i.e. MSR_START(idMunge); then you get - macros which will turn into nothing unless PERF is defined. - - You can reset the statistical counts for a given id by calling Reset(Id). - They are reset by default at the start. - It logs Reset as a special incident, so you can see it in the log. - - The log is a circular buffer in storage (to try to minimise disk I/O). - It overwrites the oldest entries once full. The statistics include ALL - incidents since the last Reset, whether still visible in the log or not. -*/ - -#ifndef __MEASURE__ -#define __MEASURE__ - -#ifdef PERF -#define MSR_INIT() Msr_Init() -#define MSR_TERMINATE() Msr_Terminate() -#define MSR_REGISTER(a) Msr_Register(a) -#define MSR_RESET(a) Msr_Reset(a) -#define MSR_CONTROL(a) Msr_Control(a) -#define MSR_START(a) Msr_Start(a) -#define MSR_STOP(a) Msr_Stop(a) -#define MSR_NOTE(a) Msr_Note(a) -#define MSR_INTEGER(a,b) Msr_Integer(a,b) -#define MSR_DUMP(a) Msr_Dump(a) -#define MSR_DUMPSTATS(a) Msr_DumpStats(a) -#else -#define MSR_INIT() ((void)0) -#define MSR_TERMINATE() ((void)0) -#define MSR_REGISTER(a) 0 -#define MSR_RESET(a) ((void)0) -#define MSR_CONTROL(a) ((void)0) -#define MSR_START(a) ((void)0) -#define MSR_STOP(a) ((void)0) -#define MSR_NOTE(a) ((void)0) -#define MSR_INTEGER(a,b) ((void)0) -#define MSR_DUMP(a) ((void)0) -#define MSR_DUMPSTATS(a) ((void)0) -#endif - -#ifdef __cplusplus -extern "C" { -#endif - -// This must be called first - (called by the DllEntry) - -void WINAPI Msr_Init(void); - - -// Call this last to clean up (or just let it fall off the end - who cares?) - -void WINAPI Msr_Terminate(void); - - -// Call this to get an Id for an "incident" that you can pass to Start, Stop or Note -// everything that's logged is called an "incident". - -int WINAPI Msr_Register(__in LPTSTR Incident); - - -// Reset the statistical counts for an incident - -void WINAPI Msr_Reset(int Id); - - -// Reset all the counts for all incidents -#define MSR_RESET_ALL 0 -#define MSR_PAUSE 1 -#define MSR_RUN 2 - -void WINAPI Msr_Control(int iAction); - - -// log the start of an operation - -void WINAPI Msr_Start(int Id); - - -// log the end of an operation - -void WINAPI Msr_Stop(int Id); - - -// log a one-off or repetitive operation - -void WINAPI Msr_Note(int Id); - - -// log an integer (on which we can see statistics later) -void WINAPI Msr_Integer(int Id, int n); - - -// print out all the vaialable log (it may have wrapped) and then the statistics. -// When the log wraps you lose log but the statistics are still complete. -// hFIle==NULL => use DbgLog -// otherwise hFile must have come from CreateFile or OpenFile. - -void WINAPI Msr_Dump(HANDLE hFile); - - -// just dump the statistics - never mind the log - -void WINAPI Msr_DumpStats(HANDLE hFile); - -// Type definitions in case you want to declare a pointer to the dump functions -// (makes it a trifle easier to do dynamic linking -// i.e. LoadModule, GetProcAddress and call that) - -// Typedefs so can declare MSR_DUMPPROC *MsrDumpStats; or whatever -typedef void WINAPI MSR_DUMPPROC(HANDLE hFile); -typedef void WINAPI MSR_CONTROLPROC(int iAction); - - -#ifdef __cplusplus -} -#endif - -#endif // __MEASURE__ diff --git a/UnityWebcam/UnityCamService/includes/msgthrd.h b/UnityWebcam/UnityCamService/includes/msgthrd.h deleted file mode 100644 index 208f03c..0000000 --- a/UnityWebcam/UnityCamService/includes/msgthrd.h +++ /dev/null @@ -1,120 +0,0 @@ -//------------------------------------------------------------------------------ -// File: MsgThrd.h -// -// Desc: DirectShow base classes - provides support for a worker thread -// class to which one can asynchronously post messages. -// -// Copyright (c) 1992-2001 Microsoft Corporation. All rights reserved. -//------------------------------------------------------------------------------ - - -// Message class - really just a structure. -// -class CMsg { -public: - UINT uMsg; - DWORD dwFlags; - LPVOID lpParam; - CAMEvent *pEvent; - - CMsg(UINT u, DWORD dw, __inout_opt LPVOID lp, __in_opt CAMEvent *pEvnt) - : uMsg(u), dwFlags(dw), lpParam(lp), pEvent(pEvnt) {} - - CMsg() - : uMsg(0), dwFlags(0L), lpParam(NULL), pEvent(NULL) {} -}; - -// This is the actual thread class. It exports all the usual thread control -// functions. The created thread is different from a normal WIN32 thread in -// that it is prompted to perform particaular tasks by responding to messages -// posted to its message queue. -// -class AM_NOVTABLE CMsgThread { -private: - static DWORD WINAPI DefaultThreadProc(__inout LPVOID lpParam); - DWORD m_ThreadId; - HANDLE m_hThread; - -protected: - - // if you want to override GetThreadMsg to block on other things - // as well as this queue, you need access to this - CGenericList m_ThreadQueue; - CCritSec m_Lock; - HANDLE m_hSem; - LONG m_lWaiting; - -public: - CMsgThread() - : m_ThreadId(0), - m_hThread(NULL), - m_lWaiting(0), - m_hSem(NULL), - // make a list with a cache of 5 items - m_ThreadQueue(NAME("MsgThread list"), 5) - { - } - - ~CMsgThread(); - // override this if you want to block on other things as well - // as the message loop - void virtual GetThreadMsg(__out CMsg *msg); - - // override this if you want to do something on thread startup - virtual void OnThreadInit() { - }; - - BOOL CreateThread(); - - BOOL WaitForThreadExit(__out LPDWORD lpdwExitCode) { - if (m_hThread != NULL) { - WaitForSingleObject(m_hThread, INFINITE); - return GetExitCodeThread(m_hThread, lpdwExitCode); - } - return FALSE; - } - - DWORD ResumeThread() { - return ::ResumeThread(m_hThread); - } - - DWORD SuspendThread() { - return ::SuspendThread(m_hThread); - } - - int GetThreadPriority() { - return ::GetThreadPriority(m_hThread); - } - - BOOL SetThreadPriority(int nPriority) { - return ::SetThreadPriority(m_hThread, nPriority); - } - - HANDLE GetThreadHandle() { - return m_hThread; - } - - DWORD GetThreadId() { - return m_ThreadId; - } - - - void PutThreadMsg(UINT uMsg, DWORD dwMsgFlags, - __in_opt LPVOID lpMsgParam, __in_opt CAMEvent *pEvent = NULL) { - CAutoLock lck(&m_Lock); - CMsg* pMsg = new CMsg(uMsg, dwMsgFlags, lpMsgParam, pEvent); - m_ThreadQueue.AddTail(pMsg); - if (m_lWaiting != 0) { - ReleaseSemaphore(m_hSem, m_lWaiting, 0); - m_lWaiting = 0; - } - } - - // This is the function prototype of the function that the client - // supplies. It is always called on the created thread, never on - // the creator thread. - // - virtual LRESULT ThreadMessageProc( - UINT uMsg, DWORD dwFlags, __inout_opt LPVOID lpParam, __in_opt CAMEvent *pEvent) = 0; -}; - diff --git a/UnityWebcam/UnityCamService/includes/mtype.h b/UnityWebcam/UnityCamService/includes/mtype.h deleted file mode 100644 index 9402f06..0000000 --- a/UnityWebcam/UnityCamService/includes/mtype.h +++ /dev/null @@ -1,89 +0,0 @@ -//------------------------------------------------------------------------------ -// File: MtType.h -// -// Desc: DirectShow base classes - defines a class that holds and manages -// media type information. -// -// Copyright (c) 1992-2001 Microsoft Corporation. All rights reserved. -//------------------------------------------------------------------------------ - - -#ifndef __MTYPE__ -#define __MTYPE__ - -/* Helper class that derived pin objects can use to compare media - types etc. Has same data members as the struct AM_MEDIA_TYPE defined - in the streams IDL file, but also has (non-virtual) functions */ - -class CMediaType : public _AMMediaType { - -public: - - ~CMediaType(); - CMediaType(); - CMediaType(const GUID * majortype); - CMediaType(const AM_MEDIA_TYPE&, __out_opt HRESULT* phr = NULL); - CMediaType(const CMediaType&, __out_opt HRESULT* phr = NULL); - - CMediaType& operator=(const CMediaType&); - CMediaType& operator=(const AM_MEDIA_TYPE&); - - BOOL operator == (const CMediaType&) const; - BOOL operator != (const CMediaType&) const; - - HRESULT Set(const CMediaType& rt); - HRESULT Set(const AM_MEDIA_TYPE& rt); - - BOOL IsValid() const; - - const GUID *Type() const { return &majortype;} ; - void SetType(const GUID *); - const GUID *Subtype() const { return &subtype;} ; - void SetSubtype(const GUID *); - - BOOL IsFixedSize() const {return bFixedSizeSamples; }; - BOOL IsTemporalCompressed() const {return bTemporalCompression; }; - ULONG GetSampleSize() const; - - void SetSampleSize(ULONG sz); - void SetVariableSize(); - void SetTemporalCompression(BOOL bCompressed); - - // read/write pointer to format - can't change length without - // calling SetFormat, AllocFormatBuffer or ReallocFormatBuffer - - BYTE* Format() const {return pbFormat; }; - ULONG FormatLength() const { return cbFormat; }; - - void SetFormatType(const GUID *); - const GUID *FormatType() const {return &formattype; }; - BOOL SetFormat(__in_bcount(length) BYTE *pFormat, ULONG length); - void ResetFormatBuffer(); - BYTE* AllocFormatBuffer(ULONG length); - BYTE* ReallocFormatBuffer(ULONG length); - - void InitMediaType(); - - BOOL MatchesPartial(const CMediaType* ppartial) const; - BOOL IsPartiallySpecified(void) const; -}; - - -/* General purpose functions to copy and delete a task allocated AM_MEDIA_TYPE - structure which is useful when using the IEnumMediaFormats interface as - the implementation allocates the structures which you must later delete */ - -void WINAPI DeleteMediaType(__inout_opt AM_MEDIA_TYPE *pmt); -AM_MEDIA_TYPE * WINAPI CreateMediaType(AM_MEDIA_TYPE const *pSrc); -HRESULT WINAPI CopyMediaType(__out AM_MEDIA_TYPE *pmtTarget, const AM_MEDIA_TYPE *pmtSource); -void WINAPI FreeMediaType(__inout AM_MEDIA_TYPE& mt); - -// Initialize a media type from a WAVEFORMATEX - -STDAPI CreateAudioMediaType( - const WAVEFORMATEX *pwfx, - __out AM_MEDIA_TYPE *pmt, - BOOL bSetFormat); - -#endif /* __MTYPE__ */ - diff --git a/UnityWebcam/UnityCamService/includes/outputq.h b/UnityWebcam/UnityCamService/includes/outputq.h deleted file mode 100644 index 7e60b53..0000000 --- a/UnityWebcam/UnityCamService/includes/outputq.h +++ /dev/null @@ -1,137 +0,0 @@ -//------------------------------------------------------------------------------ -// File: OutputQ.h -// -// Desc: DirectShow base classes - defines the COutputQueue class, which -// makes a queue of samples and sends them to an output pin. The -// class will optionally send the samples to the pin directly. -// -// Copyright (c) 1992-2001 Microsoft Corporation. All rights reserved. -//------------------------------------------------------------------------------ - - -typedef CGenericList CSampleList; - -class COutputQueue : public CCritSec -{ -public: - // Constructor - COutputQueue(IPin *pInputPin, // Pin to send stuff to - __inout HRESULT *phr, // 'Return code' - BOOL bAuto = TRUE, // Ask pin if blocks - BOOL bQueue = TRUE, // Send through queue (ignored if - // bAuto set) - LONG lBatchSize = 1, // Batch - BOOL bBatchExact = FALSE,// Batch exactly to BatchSize - LONG lListSize = // Likely number in the list - DEFAULTCACHE, - DWORD dwPriority = // Priority of thread to create - THREAD_PRIORITY_NORMAL, - bool bFlushingOpt = false // flushing optimization - ); - ~COutputQueue(); - - // enter flush state - discard all data - void BeginFlush(); // Begin flushing samples - - // re-enable receives (pass this downstream) - void EndFlush(); // Complete flush of samples - downstream - // pin guaranteed not to block at this stage - - void EOS(); // Call this on End of stream - - void SendAnyway(); // Send batched samples anyway (if bBatchExact set) - - void NewSegment( - REFERENCE_TIME tStart, - REFERENCE_TIME tStop, - double dRate); - - HRESULT Receive(IMediaSample *pSample); - - // do something with these media samples - HRESULT ReceiveMultiple ( - __in_ecount(nSamples) IMediaSample **pSamples, - long nSamples, - __out long *nSamplesProcessed); - - void Reset(); // Reset m_hr ready for more data - - // See if its idle or not - BOOL IsIdle(); - - // give the class an event to fire after everything removed from the queue - void SetPopEvent(HANDLE hEvent); - -protected: - static DWORD WINAPI InitialThreadProc(__in LPVOID pv); - DWORD ThreadProc(); - BOOL IsQueued() - { - return m_List != NULL; - }; - - // The critical section MUST be held when this is called - void QueueSample(IMediaSample *pSample); - - BOOL IsSpecialSample(IMediaSample *pSample) - { - return (DWORD_PTR)pSample > (DWORD_PTR)(LONG_PTR)(-16); - }; - - // Remove and Release() batched and queued samples - void FreeSamples(); - - // Notify the thread there is something to do - void NotifyThread(); - - -protected: - // Queue 'messages' - #define SEND_PACKET ((IMediaSample *)(LONG_PTR)(-2)) // Send batch - #define EOS_PACKET ((IMediaSample *)(LONG_PTR)(-3)) // End of stream - #define RESET_PACKET ((IMediaSample *)(LONG_PTR)(-4)) // Reset m_hr - #define NEW_SEGMENT ((IMediaSample *)(LONG_PTR)(-5)) // send NewSegment - - // new segment packet is always followed by one of these - struct NewSegmentPacket { - REFERENCE_TIME tStart; - REFERENCE_TIME tStop; - double dRate; - }; - - // Remember input stuff - IPin * const m_pPin; - IMemInputPin * m_pInputPin; - BOOL const m_bBatchExact; - LONG const m_lBatchSize; - - CSampleList * m_List; - HANDLE m_hSem; - CAMEvent m_evFlushComplete; - HANDLE m_hThread; - __field_ecount_opt(m_lBatchSize) IMediaSample ** m_ppSamples; - __range(0, m_lBatchSize) LONG m_nBatched; - - // Wait optimization - LONG m_lWaiting; - // Flush synchronization - BOOL m_bFlushing; - - // flushing optimization. some downstream filters have trouble - // with the queue's flushing optimization. other rely on it - BOOL m_bFlushed; - bool m_bFlushingOpt; - - // Terminate now - BOOL m_bTerminate; - - // Send anyway flag for batching - BOOL m_bSendAnyway; - - // Deferred 'return code' - HRESULT volatile m_hr; - - // an event that can be fired after every deliver - HANDLE m_hEventPop; -}; - diff --git a/UnityWebcam/UnityCamService/includes/perflog.h b/UnityWebcam/UnityCamService/includes/perflog.h deleted file mode 100644 index 05d6404..0000000 --- a/UnityWebcam/UnityCamService/includes/perflog.h +++ /dev/null @@ -1,56 +0,0 @@ -//------------------------------------------------------------------------------ -// File: perflog.h -// -// Desc: Performance logging framework. -// -// Copyright (c) 1992-2001 Microsoft Corporation. All rights reserved. -//------------------------------------------------------------------------------ - -typedef struct _PERFLOG_LOGGING_PARAMS { - GUID ControlGuid; - void (*OnStateChanged)(void); - ULONG NumberOfTraceGuids; - TRACE_GUID_REGISTRATION TraceGuids[ANYSIZE_ARRAY]; -} PERFLOG_LOGGING_PARAMS, *PPERFLOG_LOGGING_PARAMS; - -BOOL -PerflogInitIfEnabled( - IN HINSTANCE hInstance, - __in PPERFLOG_LOGGING_PARAMS LogParams - ); - -BOOL -PerflogInitialize ( - __in PPERFLOG_LOGGING_PARAMS LogParams - ); - -VOID -PerflogShutdown ( - VOID - ); - -VOID -PerflogTraceEvent ( - __in PEVENT_TRACE_HEADER Event - ); - -extern ULONG PerflogEnableFlags; -extern UCHAR PerflogEnableLevel; -extern ULONG PerflogModuleLevel; -extern TRACEHANDLE PerflogTraceHandle; -extern TRACEHANDLE PerflogRegHandle; - -#define PerflogTracingEnabled() (PerflogTraceHandle != 0) - -#define PerflogEvent( _x_ ) PerflogTraceEventLevel _x_ - -VOID -PerflogTraceEventLevel( - ULONG Level, - __in PEVENT_TRACE_HEADER Event - ); - -VOID -PerflogTraceEvent ( - __in PEVENT_TRACE_HEADER Event - ); diff --git a/UnityWebcam/UnityCamService/includes/perfstruct.h b/UnityWebcam/UnityCamService/includes/perfstruct.h deleted file mode 100644 index b57657c..0000000 --- a/UnityWebcam/UnityCamService/includes/perfstruct.h +++ /dev/null @@ -1,194 +0,0 @@ -//------------------------------------------------------------------------------ -// File: PerfStruct.h -// -// Desc: Structures for DirectShow performance logging. -// -// Copyright (c) 2000-2001 Microsoft Corporation. All rights reserved. -//------------------------------------------------------------------------------ - - -#ifndef _PERFSTRUCT_H_ -#define _PERFSTRUCT_H_ - -#include -#include - -// {28CF047A-2437-4b24-B653-B9446A419A69} -DEFINE_GUID(GUID_DSHOW_CTL, -0x28cf047a, 0x2437, 0x4b24, 0xb6, 0x53, 0xb9, 0x44, 0x6a, 0x41, 0x9a, 0x69); - -// {D0DA7AD6-AE80-4de5-AAFC-C126711E7593} -DEFINE_GUID(GUID_VIDEOREND, -0xd0da7ad6, 0xae80, 0x4de5, 0xaa, 0xfc, 0xc1, 0x26, 0x71, 0x1e, 0x75, 0x93); - -// {DC70AC3E-93E5-48db-88AB-E42064EC276A} -DEFINE_GUID(GUID_DSOUNDGLITCH, -0xdc70ac3e, 0x93e5, 0x48db, 0x88, 0xab, 0xe4, 0x20, 0x64, 0xec, 0x27, 0x6a); - -// {3d7e7d93-2fc8-4a07-a719-e0922ff2899} -DEFINE_GUID(GUID_STREAMTRACE, -0x3d7e7d93, 0x2fc8, 0x4a07, 0xa7, 0x19, 0xe0, 0x92, 0x2f, 0xf2, 0x89, 0x9e); - -// AZFIX: the following GUIDs aren't useful right now. - -// {3C33F7F5-EE54-493c-BA25-1656539C05AC} -DEFINE_GUID(GUID_GETTIME, -0x3c33f7f5, 0xee54, 0x493c, 0xba, 0x25, 0x16, 0x56, 0x53, 0x9c, 0x5, 0xac); - -// {CC44B44D-8169-4952-9E4A-A4E13295E492} -DEFINE_GUID(GUID_AUDIOREND, -0xcc44b44d, 0x8169, 0x4952, 0x9e, 0x4a, 0xa4, 0xe1, 0x32, 0x95, 0xe4, 0x92); - -// {775D19BF-4D8B-4de6-8DC9-66BAC7B310A2} -DEFINE_GUID(GUID_FRAMEDROP, -0x775d19bf, 0x4d8b, 0x4de6, 0x8d, 0xc9, 0x66, 0xba, 0xc7, 0xb3, 0x10, 0xa2); - -// {56D29065-EFBE-42dc-8C29-E325DC9C27D5} -DEFINE_GUID(GUID_AUDIOBREAK, -0x56d29065, 0xefbe, 0x42dc, 0x8c, 0x29, 0xe3, 0x25, 0xdc, 0x9c, 0x27, 0xd5); - -// {E1E6EA87-95A8-497e-BFBA-0295AEBCC707} -DEFINE_GUID(GUID_AUDIORECV, -0xe1e6ea87, 0x95a8, 0x497e, 0xbf, 0xba, 0x2, 0x95, 0xae, 0xbc, 0xc7, 0x7); - -// {10F7768A-B1E7-4242-AD90-A2D44683D9F0} -DEFINE_GUID(GUID_AUDIOSLAVE, -0x10f7768a, 0xb1e7, 0x4242, 0xad, 0x90, 0xa2, 0xd4, 0x46, 0x83, 0xd9, 0xf0); - -// {8983803D-691A-49bc-8FF6-962A39C0198F} -DEFINE_GUID(GUID_AUDIOADDBREAK, -0x8983803d, 0x691a, 0x49bc, 0x8f, 0xf6, 0x96, 0x2a, 0x39, 0xc0, 0x19, 0x8f); - -#define GLITCHTYPE_DSOUNDFIRSTGOOD 0 -#define GLITCHTYPE_DSOUNDFIRSTBAD 1 - -typedef struct PERFINFO_DSHOW_AUDIOGLITCH { - ULONGLONG cycleCounter; - DWORD glitchType; - LONGLONG sampleTime; - LONGLONG previousTime; - ULONG_PTR instanceId; -} PERFINFO_DSHOW_AUDIOGLITCH, *PPERFINFO_DSHOW_AUDIOGLITCH; - -typedef struct PERFINFO_WMI_AUDIOGLITCH { - EVENT_TRACE_HEADER header; - PERFINFO_DSHOW_AUDIOGLITCH data; -} PERFINFO_WMI_AUDIO_GLITCH, *PPERFINFO_WMI_AUDIOGLITCH; - -typedef struct PERFINFO_DSHOW_GETTIME { - ULONGLONG cycleCounter; - ULONGLONG dshowClock; -} PERFINFO_DSHOW_GETTIME, *PPERFINFO_DSHOW_GETTIME; - -typedef struct PERFINFO_WMI_GETTIME { - EVENT_TRACE_HEADER header; - PERFINFO_DSHOW_GETTIME data; -} PERFINFO_WMI_GETTIME, *PPERFINFO_WMI_GETTIME; - -typedef struct PERFINFO_DSHOW_AVREND { - ULONGLONG cycleCounter; - ULONGLONG dshowClock; - ULONGLONG sampleTime; -} PERFINFO_DSHOW_AVREND, *PPERFINFO_DSHOW_AVREND; - -typedef struct PERFINFO_WMI_AVREND { - EVENT_TRACE_HEADER header; - PERFINFO_DSHOW_AVREND data; -} PERFINFO_WMI_AVREND, *PPERFINFO_WMI_AVREND; - -typedef struct PERFINFO_DSHOW_AUDIOBREAK { - ULONGLONG cycleCounter; - ULONGLONG dshowClock; - ULONGLONG sampleTime; - ULONGLONG sampleDuration; -} PERFINFO_DSHOW_AUDIOBREAK, *PPERFINFO_DSHOW_AUDIOBREAK; - -typedef struct PERFINFO_WMI_AUDIOBREAK { - EVENT_TRACE_HEADER header; - PERFINFO_DSHOW_AUDIOBREAK data; -} PERFINFO_WMI_AUDIOBREAK, *PPERFINFO_WMI_AUDIOBREAK; - -typedef struct PERFINFO_DSHOW_FRAMEDROP { - ULONGLONG cycleCounter; - ULONGLONG dshowClock; - ULONGLONG frameTime; -} PERFINFO_DSHOW_FRAMEDROP, *PPERFINFO_DSHOW_FRAMEDROP; - -typedef struct PERFINFO_WMI_FRAMEDROP { - EVENT_TRACE_HEADER header; - PERFINFO_DSHOW_FRAMEDROP data; -} PERFINFO_WMI_FRAMEDROP, *PPERFINFO_WMI_FRAMEDROP; - -#define PERFINFO_STREAMTRACE_MPEG2DEMUX_PTS_TRANSLATION 1 -#define PERFINFO_STREAMTRACE_MPEG2DEMUX_SAMPLE_RECEIVED 2 -#define PERFINFO_STREAMTRACE_VMR_BEGIN_ADVISE 3 -#define PERFINFO_STREAMTRACE_VMR_END_ADVISE 4 -#define PERFINFO_STREAMTRACE_VMR_RECEIVE 5 -#define PERFINFO_STREAMTRACE_VMR_BEGIN_DEINTERLACE 6 -#define PERFINFO_STREAMTRACE_VMR_END_DEINTERLACE 7 -#define PERFINFO_STREAMTRACE_VMR_BEGIN_DECODE 8 -#define PERFINFO_STREAMTRACE_VMR_END_DECODE 9 -#define PERFINFO_STREAMTRACE_VMR_DROPPED_FRAME 10 -#define PERFINFO_STREAMTRACE_ENCDEC_DTFILTERINPUT 11 -#define PERFINFO_STREAMTRACE_ENCDEC_DTFILTEROUTPUT 12 -#define PERFINFO_STREAMTRACE_ENCDEC_ETFILTERINPUT 13 -#define PERFINFO_STREAMTRACE_ENCDEC_ETFILTEROUTPUT 14 -#define PERFINFO_STREAMTRACE_ENCDEC_XDSCODECINPUT 15 -#define PERFINFO_STREAMTRACE_SBE_DVRANALYSISINPUT_RECEIVE 16 -#define PERFINFO_STREAMTRACE_SBE_DVRANALYSISINPUT_DELIVER 17 -#define PERFINFO_STREAMTRACE_SBE_DVRINPUTPIN_RECEIVE 18 -#define PERFINFO_STREAMTRACE_SBE_DVROUTPUTPIN_RECEIVE 19 -#define PERFINFO_STREAMTRACE_VMR_RENDER_TIME 20 - -typedef struct _PERFINFO_DSHOW_STREAMTRACE { - ULONG id; - ULONG reserved; - ULONGLONG dshowClock; - ULONGLONG data[ 4 ]; -} PERFINFO_DSHOW_STREAMTRACE, *PPERFINFO_DSHOW_STREAMTRACE; - -typedef struct _PERFINFO_WMI_STREAMTRACE { - EVENT_TRACE_HEADER header; - PERFINFO_DSHOW_STREAMTRACE data; -} PERFINFO_WMI_STREAMTRACE, *PPERFINFO_WMI_STREAMTRACE; - - -typedef struct PERFINFO_DSHOW_AUDIORECV { - LONGLONG streamTime ; - LONGLONG sampleStart ; - LONGLONG sampleStop ; - LONGLONG hwduration ; - BOOL discontinuity ; -} PERFINFO_DSHOW_AUDIORECV, *PPERFINFO_DSHOW_AUDIORECV; - -typedef struct PERFINFO_WMI_AUDIORECV { - EVENT_TRACE_HEADER header; - PERFINFO_DSHOW_AUDIORECV data; -} PERFINFO_WMI_AUDIORECV, *PPERFINFO_WMI_AUDIORECV; - -typedef struct PERFINFO_DSHOW_AUDIOSLAVE { - LONGLONG masterClock ; - LONGLONG slaveClock ; - LONGLONG errorAccum ; - LONGLONG lastHighErrorSeen ; - LONGLONG lastLowErrorSeen ; -} PERFINFO_DSHOW_AUDIOSLAVE, *PPERFINFO_DSHOW_AUDIOSLAVE; - -typedef struct PERFINFO_WMI_AUDIOSLAVE { - EVENT_TRACE_HEADER header; - PERFINFO_DSHOW_AUDIOSLAVE data; -} PERFINFO_WMI_AUDIOSLAVE, *PPERFINFO_WMI_AUDIOSLAVE; - -typedef struct PERFINFO_DSHOW_AUDIOADDBREAK { - DWORD iterNextWrite ; - DWORD offsetNextWrite ; - DWORD iterWrite ; - DWORD offsetWrite ; -} PERFINFO_DSHOW_AUDIOADDBREAK, *PPERFINFO_DSHOW_AUDIOADDBREAK; - -typedef struct PERFINFO_WMI_AUDIOADDBREAK { - EVENT_TRACE_HEADER header; - PERFINFO_DSHOW_AUDIOADDBREAK data; -} PERFINFO_WMI_AUDIOADDBREAK, *PPERFINFO_WMI_AUDIOADDBREAK; - -#endif // _PREFSTRUCT_H_ diff --git a/UnityWebcam/UnityCamService/includes/pstream.h b/UnityWebcam/UnityCamService/includes/pstream.h deleted file mode 100644 index 2e278ab..0000000 --- a/UnityWebcam/UnityCamService/includes/pstream.h +++ /dev/null @@ -1,114 +0,0 @@ -//------------------------------------------------------------------------------ -// File: PStream.h -// -// Desc: DirectShow base classes - defines a class for persistent properties -// of filters. -// -// Copyright (c) 1992-2001 Microsoft Corporation. All rights reserved. -//------------------------------------------------------------------------------ - - -#ifndef __PSTREAM__ -#define __PSTREAM__ - -// Base class for persistent properties of filters -// (i.e. filter properties in saved graphs) - -// The simplest way to use this is: -// 1. Arrange for your filter to inherit this class -// 2. Implement in your class WriteToStream and ReadFromStream -// These will override the "do nothing" functions here. -// 3. Change your NonDelegatingQueryInterface to handle IPersistStream -// 4. Implement SizeMax to return the number of bytes of data you save. -// If you save UNICODE data, don't forget a char is 2 bytes. -// 5. Whenever your data changes, call SetDirty() -// -// At some point you may decide to alter, or extend the format of your data. -// At that point you will wish that you had a version number in all the old -// saved graphs, so that you can tell, when you read them, whether they -// represent the old or new form. To assist you in this, this class -// writes and reads a version number. -// When it writes, it calls GetSoftwareVersion() to enquire what version -// of the software we have at the moment. (In effect this is a version number -// of the data layout in the file). It writes this as the first thing in the data. -// If you want to change the version, implement (override) GetSoftwareVersion(). -// It reads this from the file into mPS_dwFileVersion before calling ReadFromStream, -// so in ReadFromStream you can check mPS_dwFileVersion to see if you are reading -// an old version file. -// Normally you should accept files whose version is no newer than the software -// version that's reading them. - - -// CPersistStream -// -// Implements IPersistStream. -// See 'OLE Programmers Reference (Vol 1):Structured Storage Overview' for -// more implementation information. -class CPersistStream : public IPersistStream { - private: - - // Internal state: - - protected: - DWORD mPS_dwFileVersion; // version number of file (being read) - BOOL mPS_fDirty; - - public: - - // IPersistStream methods - - STDMETHODIMP IsDirty() - {return (mPS_fDirty ? S_OK : S_FALSE);} // note FALSE means clean - STDMETHODIMP Load(LPSTREAM pStm); - STDMETHODIMP Save(LPSTREAM pStm, BOOL fClearDirty); - STDMETHODIMP GetSizeMax(__out ULARGE_INTEGER * pcbSize) - // Allow 24 bytes for version. - { pcbSize->QuadPart = 12*sizeof(WCHAR)+SizeMax(); return NOERROR; } - - // implementation - - CPersistStream(IUnknown *punk, __inout HRESULT *phr); - ~CPersistStream(); - - HRESULT SetDirty(BOOL fDirty) - { mPS_fDirty = fDirty; return NOERROR;} - - - // override to reveal IPersist & IPersistStream - // STDMETHODIMP NonDelegatingQueryInterface(REFIID riid, void **ppv); - - // --- IPersist --- - - // You must override this to provide your own class id - STDMETHODIMP GetClassID(__out CLSID *pClsid) PURE; - - // overrideable if you want - // file version number. Override it if you ever change format - virtual DWORD GetSoftwareVersion(void) { return 0; } - - - //========================================================================= - // OVERRIDE THESE to read and write your data - // OVERRIDE THESE to read and write your data - // OVERRIDE THESE to read and write your data - - virtual int SizeMax() {return 0;} - virtual HRESULT WriteToStream(IStream *pStream); - virtual HRESULT ReadFromStream(IStream *pStream); - //========================================================================= - - private: - -}; - - -// --- Useful helpers --- - - -// Writes an int to an IStream as UNICODE. -STDAPI WriteInt(IStream *pIStream, int n); - -// inverse of WriteInt -STDAPI_(int) ReadInt(IStream *pIStream, __out HRESULT &hr); - -#endif // __PSTREAM__ diff --git a/UnityWebcam/UnityCamService/includes/pullpin.h b/UnityWebcam/UnityCamService/includes/pullpin.h deleted file mode 100644 index db4f407..0000000 --- a/UnityWebcam/UnityCamService/includes/pullpin.h +++ /dev/null @@ -1,152 +0,0 @@ -//------------------------------------------------------------------------------ -// File: PullPin.h -// -// Desc: DirectShow base classes - defines CPullPin class. -// -// Copyright (c) 1992-2001 Microsoft Corporation. All rights reserved. -//------------------------------------------------------------------------------ - - -#ifndef __PULLPIN_H__ -#define __PULLPIN_H__ - -// -// CPullPin -// -// object supporting pulling data from an IAsyncReader interface. -// Given a start/stop position, calls a pure Receive method with each -// IMediaSample received. -// -// This is essentially for use in a MemInputPin when it finds itself -// connected to an IAsyncReader pin instead of a pushing pin. -// - -class CPullPin : public CAMThread -{ - IAsyncReader* m_pReader; - REFERENCE_TIME m_tStart; - REFERENCE_TIME m_tStop; - REFERENCE_TIME m_tDuration; - BOOL m_bSync; - - enum ThreadMsg { - TM_Pause, // stop pulling and wait for next message - TM_Start, // start pulling - TM_Exit, // stop and exit - }; - - ThreadMsg m_State; - - // override pure thread proc from CAMThread - DWORD ThreadProc(void); - - // running pull method (check m_bSync) - void Process(void); - - // clean up any cancelled i/o after a flush - void CleanupCancelled(void); - - // suspend thread from pulling, eg during seek - HRESULT PauseThread(); - - // start thread pulling - create thread if necy - HRESULT StartThread(); - - // stop and close thread - HRESULT StopThread(); - - // called from ProcessAsync to queue and collect requests - HRESULT QueueSample( - __inout REFERENCE_TIME& tCurrent, - REFERENCE_TIME tAlignStop, - BOOL bDiscontinuity); - - HRESULT CollectAndDeliver( - REFERENCE_TIME tStart, - REFERENCE_TIME tStop); - - HRESULT DeliverSample( - IMediaSample* pSample, - REFERENCE_TIME tStart, - REFERENCE_TIME tStop); - -protected: - IMemAllocator * m_pAlloc; - -public: - CPullPin(); - virtual ~CPullPin(); - - // returns S_OK if successfully connected to an IAsyncReader interface - // from this object - // Optional allocator should be proposed as a preferred allocator if - // necessary - // bSync is TRUE if we are to use sync reads instead of the - // async methods. - HRESULT Connect(IUnknown* pUnk, IMemAllocator* pAlloc, BOOL bSync); - - // disconnect any connection made in Connect - HRESULT Disconnect(); - - // agree an allocator using RequestAllocator - optional - // props param specifies your requirements (non-zero fields). - // returns an error code if fail to match requirements. - // optional IMemAllocator interface is offered as a preferred allocator - // but no error occurs if it can't be met. - virtual HRESULT DecideAllocator( - IMemAllocator* pAlloc, - __inout_opt ALLOCATOR_PROPERTIES * pProps); - - // set start and stop position. if active, will start immediately at - // the new position. Default is 0 to duration - HRESULT Seek(REFERENCE_TIME tStart, REFERENCE_TIME tStop); - - // return the total duration - HRESULT Duration(__out REFERENCE_TIME* ptDuration); - - // start pulling data - HRESULT Active(void); - - // stop pulling data - HRESULT Inactive(void); - - // helper functions - LONGLONG AlignDown(LONGLONG ll, LONG lAlign) { - // aligning downwards is just truncation - return ll & ~(lAlign-1); - }; - - LONGLONG AlignUp(LONGLONG ll, LONG lAlign) { - // align up: round up to next boundary - return (ll + (lAlign -1)) & ~(lAlign -1); - }; - - // GetReader returns the (addrefed) IAsyncReader interface - // for SyncRead etc - IAsyncReader* GetReader() { - m_pReader->AddRef(); - return m_pReader; - }; - - // -- pure -- - - // override this to handle data arrival - // return value other than S_OK will stop data - virtual HRESULT Receive(IMediaSample*) PURE; - - // override this to handle end-of-stream - virtual HRESULT EndOfStream(void) PURE; - - // called on runtime errors that will have caused pulling - // to stop - // these errors are all returned from the upstream filter, who - // will have already reported any errors to the filtergraph. - virtual void OnError(HRESULT hr) PURE; - - // flush this pin and all downstream - virtual HRESULT BeginFlush() PURE; - virtual HRESULT EndFlush() PURE; - -}; - -#endif //__PULLPIN_H__ diff --git a/UnityWebcam/UnityCamService/includes/refclock.h b/UnityWebcam/UnityCamService/includes/refclock.h deleted file mode 100644 index df822e0..0000000 --- a/UnityWebcam/UnityCamService/includes/refclock.h +++ /dev/null @@ -1,184 +0,0 @@ -//------------------------------------------------------------------------------ -// File: RefClock.h -// -// Desc: DirectShow base classes - defines the IReferenceClock interface. -// -// Copyright (c) 1992-2001 Microsoft Corporation. All rights reserved. -//------------------------------------------------------------------------------ - - -#ifndef __BASEREFCLOCK__ -#define __BASEREFCLOCK__ - -#include - -const UINT RESOLUTION = 1; /* High resolution timer */ -const INT ADVISE_CACHE = 4; /* Default cache size */ -const LONGLONG MAX_TIME = 0x7FFFFFFFFFFFFFFF; /* Maximum LONGLONG value */ - -inline LONGLONG WINAPI ConvertToMilliseconds(const REFERENCE_TIME& RT) -{ - /* This converts an arbitrary value representing a reference time - into a MILLISECONDS value for use in subsequent system calls */ - - return (RT / (UNITS / MILLISECONDS)); -} - -/* This class hierarchy will support an IReferenceClock interface so - that an audio card (or other externally driven clock) can update the - system wide clock that everyone uses. - - The interface will be pretty thin with probably just one update method - This interface has not yet been defined. - */ - -/* This abstract base class implements the IReferenceClock - * interface. Classes that actually provide clock signals (from - * whatever source) have to be derived from this class. - * - * The abstract class provides implementations for: - * CUnknown support - * locking support (CCritSec) - * client advise code (creates a thread) - * - * Question: what can we do about quality? Change the timer - * resolution to lower the system load? Up the priority of the - * timer thread to force more responsive signals? - * - * During class construction we create a worker thread that is destroyed during - * destuction. This thread executes a series of WaitForSingleObject calls, - * waking up when a command is given to the thread or the next wake up point - * is reached. The wakeup points are determined by clients making Advise - * calls. - * - * Each advise call defines a point in time when they wish to be notified. A - * periodic advise is a series of these such events. We maintain a list of - * advise links and calculate when the nearest event notification is due for. - * We then call WaitForSingleObject with a timeout equal to this time. The - * handle we wait on is used by the class to signal that something has changed - * and that we must reschedule the next event. This typically happens when - * someone comes in and asks for an advise link while we are waiting for an - * event to timeout. - * - * While we are modifying the list of advise requests we - * are protected from interference through a critical section. Clients are NOT - * advised through callbacks. One shot clients have an event set, while - * periodic clients have a semaphore released for each event notification. A - * semaphore allows a client to be kept up to date with the number of events - * actually triggered and be assured that they can't miss multiple events being - * set. - * - * Keeping track of advises is taken care of by the CAMSchedule class. - */ - -class CBaseReferenceClock -: public CUnknown, public IReferenceClock, public CCritSec, public IReferenceClockTimerControl -{ -protected: - virtual ~CBaseReferenceClock(); // Don't let me be created on the stack! -public: - CBaseReferenceClock(__in_opt LPCTSTR pName, - __inout_opt LPUNKNOWN pUnk, - __inout HRESULT *phr, - __inout_opt CAMSchedule * pSched = 0 ); - - STDMETHODIMP NonDelegatingQueryInterface(REFIID riid, __deref_out void ** ppv); - - DECLARE_IUNKNOWN - - /* IReferenceClock methods */ - // Derived classes must implement GetPrivateTime(). All our GetTime - // does is call GetPrivateTime and then check so that time does not - // go backwards. A return code of S_FALSE implies that the internal - // clock has gone backwards and GetTime time has halted until internal - // time has caught up. (Don't know if this will be much use to folk, - // but it seems odd not to use the return code for something useful.) - STDMETHODIMP GetTime(__out REFERENCE_TIME *pTime); - // When this is called, it sets m_rtLastGotTime to the time it returns. - - /* Provide standard mechanisms for scheduling events */ - - /* Ask for an async notification that a time has elapsed */ - STDMETHODIMP AdviseTime( - REFERENCE_TIME baseTime, // base reference time - REFERENCE_TIME streamTime, // stream offset time - HEVENT hEvent, // advise via this event - __out DWORD_PTR *pdwAdviseCookie// where your cookie goes - ); - - /* Ask for an asynchronous periodic notification that a time has elapsed */ - STDMETHODIMP AdvisePeriodic( - REFERENCE_TIME StartTime, // starting at this time - REFERENCE_TIME PeriodTime, // time between notifications - HSEMAPHORE hSemaphore, // advise via a semaphore - __out DWORD_PTR *pdwAdviseCookie// where your cookie goes - ); - - /* Cancel a request for notification(s) - if the notification was - * a one shot timer then this function doesn't need to be called - * as the advise is automatically cancelled, however it does no - * harm to explicitly cancel a one-shot advise. It is REQUIRED that - * clients call Unadvise to clear a Periodic advise setting. - */ - - STDMETHODIMP Unadvise(DWORD_PTR dwAdviseCookie); - - /* Methods for the benefit of derived classes or outer objects */ - - // GetPrivateTime() is the REAL clock. GetTime is just a cover for - // it. Derived classes will probably override this method but not - // GetTime() itself. - // The important point about GetPrivateTime() is it's allowed to go - // backwards. Our GetTime() will keep returning the LastGotTime - // until GetPrivateTime() catches up. - virtual REFERENCE_TIME GetPrivateTime(); - - /* Provide a method for correcting drift */ - STDMETHODIMP SetTimeDelta( const REFERENCE_TIME& TimeDelta ); - - CAMSchedule * GetSchedule() const { return m_pSchedule; } - - // IReferenceClockTimerControl methods - // - // Setting a default of 0 disables the default of 1ms - STDMETHODIMP SetDefaultTimerResolution( - REFERENCE_TIME timerResolution // in 100ns - ); - STDMETHODIMP GetDefaultTimerResolution( - __out REFERENCE_TIME* pTimerResolution // in 100ns - ); - -private: - REFERENCE_TIME m_rtPrivateTime; // Current best estimate of time - DWORD m_dwPrevSystemTime; // Last vaule we got from timeGetTime - REFERENCE_TIME m_rtLastGotTime; // Last time returned by GetTime - REFERENCE_TIME m_rtNextAdvise; // Time of next advise - UINT m_TimerResolution; - -#ifdef PERF - int m_idGetSystemTime; -#endif - -// Thread stuff -public: - void TriggerThread() // Wakes thread up. Need to do this if - { // time to next advise needs reevaluating. - EXECUTE_ASSERT(SetEvent(m_pSchedule->GetEvent())); - } - - -private: - BOOL m_bAbort; // Flag used for thread shutdown - HANDLE m_hThread; // Thread handle - - HRESULT AdviseThread(); // Method in which the advise thread runs - static DWORD __stdcall AdviseThreadFunction(__in LPVOID); // Function used to get there - -protected: - CAMSchedule * m_pSchedule; - - void Restart (IN REFERENCE_TIME rtMinTime = 0I64) ; -}; - -#endif - diff --git a/UnityWebcam/UnityCamService/includes/reftime.h b/UnityWebcam/UnityCamService/includes/reftime.h deleted file mode 100644 index 0ed32f6..0000000 --- a/UnityWebcam/UnityCamService/includes/reftime.h +++ /dev/null @@ -1,116 +0,0 @@ -//------------------------------------------------------------------------------ -// File: RefTime.h -// -// Desc: DirectShow base classes - defines CRefTime, a class that manages -// reference times. -// -// Copyright (c) 1992-2001 Microsoft Corporation. All rights reserved. -//------------------------------------------------------------------------------ - - -// -// CRefTime -// -// Manage reference times. -// Shares same data layout as REFERENCE_TIME, but adds some (nonvirtual) -// functions providing simple comparison, conversion and arithmetic. -// -// A reference time (at the moment) is a unit of seconds represented in -// 100ns units as is used in the Win32 FILETIME structure. BUT the time -// a REFERENCE_TIME represents is NOT the time elapsed since 1/1/1601 it -// will either be stream time or reference time depending upon context -// -// This class provides simple arithmetic operations on reference times -// -// keep non-virtual otherwise the data layout will not be the same as -// REFERENCE_TIME - - -// ----- -// note that you are safe to cast a CRefTime* to a REFERENCE_TIME*, but -// you will need to do so explicitly -// ----- - - -#ifndef __REFTIME__ -#define __REFTIME__ - - -const LONGLONG MILLISECONDS = (1000); // 10 ^ 3 -const LONGLONG NANOSECONDS = (1000000000); // 10 ^ 9 -const LONGLONG UNITS = (NANOSECONDS / 100); // 10 ^ 7 - -/* Unfortunately an inline function here generates a call to __allmul - - even for constants! -*/ -#define MILLISECONDS_TO_100NS_UNITS(lMs) \ - Int32x32To64((lMs), (UNITS / MILLISECONDS)) - -class CRefTime -{ -public: - - // *MUST* be the only data member so that this class is exactly - // equivalent to a REFERENCE_TIME. - // Also, must be *no virtual functions* - - REFERENCE_TIME m_time; - - inline CRefTime() - { - // default to 0 time - m_time = 0; - }; - - inline CRefTime(LONG msecs) - { - m_time = MILLISECONDS_TO_100NS_UNITS(msecs); - }; - - inline CRefTime(REFERENCE_TIME rt) - { - m_time = rt; - }; - - inline operator REFERENCE_TIME() const - { - return m_time; - }; - - inline CRefTime& operator=(const CRefTime& rt) - { - m_time = rt.m_time; - return *this; - }; - - inline CRefTime& operator=(const LONGLONG ll) - { - m_time = ll; - return *this; - }; - - inline CRefTime& operator+=(const CRefTime& rt) - { - return (*this = *this + rt); - }; - - inline CRefTime& operator-=(const CRefTime& rt) - { - return (*this = *this - rt); - }; - - inline LONG Millisecs(void) - { - return (LONG)(m_time / (UNITS / MILLISECONDS)); - }; - - inline LONGLONG GetUnits(void) - { - return m_time; - }; -}; - -const LONGLONG TimeZero = 0; - -#endif /* __REFTIME__ */ - diff --git a/UnityWebcam/UnityCamService/includes/renbase.h b/UnityWebcam/UnityCamService/includes/renbase.h deleted file mode 100644 index 8634c6b..0000000 --- a/UnityWebcam/UnityCamService/includes/renbase.h +++ /dev/null @@ -1,478 +0,0 @@ -//------------------------------------------------------------------------------ -// File: RenBase.h -// -// Desc: DirectShow base classes - defines a generic ActiveX base renderer -// class. -// -// Copyright (c) 1992-2001 Microsoft Corporation. All rights reserved. -//------------------------------------------------------------------------------ - - -#ifndef __RENBASE__ -#define __RENBASE__ - -// Forward class declarations - -class CBaseRenderer; -class CBaseVideoRenderer; -class CRendererInputPin; - -// This is our input pin class that channels calls to the renderer - -class CRendererInputPin : public CBaseInputPin -{ -protected: - - CBaseRenderer *m_pRenderer; - -public: - - CRendererInputPin(__inout CBaseRenderer *pRenderer, - __inout HRESULT *phr, - __in_opt LPCWSTR Name); - - // Overriden from the base pin classes - - HRESULT BreakConnect(); - HRESULT CompleteConnect(IPin *pReceivePin); - HRESULT SetMediaType(const CMediaType *pmt); - HRESULT CheckMediaType(const CMediaType *pmt); - HRESULT Active(); - HRESULT Inactive(); - - // Add rendering behaviour to interface functions - - STDMETHODIMP QueryId(__deref_out LPWSTR *Id); - STDMETHODIMP EndOfStream(); - STDMETHODIMP BeginFlush(); - STDMETHODIMP EndFlush(); - STDMETHODIMP Receive(IMediaSample *pMediaSample); - - // Helper - IMemAllocator inline *Allocator() const - { - return m_pAllocator; - } -}; - -// Main renderer class that handles synchronisation and state changes - -class CBaseRenderer : public CBaseFilter -{ -protected: - - friend class CRendererInputPin; - - friend void CALLBACK EndOfStreamTimer(UINT uID, // Timer identifier - UINT uMsg, // Not currently used - DWORD_PTR dwUser, // User information - DWORD_PTR dw1, // Windows reserved - DWORD_PTR dw2); // Is also reserved - - CRendererPosPassThru *m_pPosition; // Media seeking pass by object - CAMEvent m_RenderEvent; // Used to signal timer events - CAMEvent m_ThreadSignal; // Signalled to release worker thread - CAMEvent m_evComplete; // Signalled when state complete - BOOL m_bAbort; // Stop us from rendering more data - BOOL m_bStreaming; // Are we currently streaming - DWORD_PTR m_dwAdvise; // Timer advise cookie - IMediaSample *m_pMediaSample; // Current image media sample - BOOL m_bEOS; // Any more samples in the stream - BOOL m_bEOSDelivered; // Have we delivered an EC_COMPLETE - CRendererInputPin *m_pInputPin; // Our renderer input pin object - CCritSec m_InterfaceLock; // Critical section for interfaces - CCritSec m_RendererLock; // Controls access to internals - IQualityControl * m_pQSink; // QualityControl sink - BOOL m_bRepaintStatus; // Can we signal an EC_REPAINT - // Avoid some deadlocks by tracking filter during stop - volatile BOOL m_bInReceive; // Inside Receive between PrepareReceive - // And actually processing the sample - REFERENCE_TIME m_SignalTime; // Time when we signal EC_COMPLETE - UINT m_EndOfStreamTimer; // Used to signal end of stream - CCritSec m_ObjectCreationLock; // This lock protects the creation and - // of m_pPosition and m_pInputPin. It - // ensures that two threads cannot create - // either object simultaneously. - -public: - - CBaseRenderer(REFCLSID RenderClass, // CLSID for this renderer - __in_opt LPCTSTR pName, // Debug ONLY description - __inout_opt LPUNKNOWN pUnk, // Aggregated owner object - __inout HRESULT *phr); // General OLE return code - - ~CBaseRenderer(); - - // Overriden to say what interfaces we support and where - - virtual HRESULT GetMediaPositionInterface(REFIID riid, __deref_out void **ppv); - STDMETHODIMP NonDelegatingQueryInterface(REFIID, __deref_out void **); - - virtual HRESULT SourceThreadCanWait(BOOL bCanWait); - -#ifdef DEBUG - // Debug only dump of the renderer state - void DisplayRendererState(); -#endif - virtual HRESULT WaitForRenderTime(); - virtual HRESULT CompleteStateChange(FILTER_STATE OldState); - - // Return internal information about this filter - - BOOL IsEndOfStream() { return m_bEOS; }; - BOOL IsEndOfStreamDelivered() { return m_bEOSDelivered; }; - BOOL IsStreaming() { return m_bStreaming; }; - void SetAbortSignal(BOOL bAbort) { m_bAbort = bAbort; }; - virtual void OnReceiveFirstSample(IMediaSample *pMediaSample) { }; - CAMEvent *GetRenderEvent() { return &m_RenderEvent; }; - - // Permit access to the transition state - - void Ready() { m_evComplete.Set(); }; - void NotReady() { m_evComplete.Reset(); }; - BOOL CheckReady() { return m_evComplete.Check(); }; - - virtual int GetPinCount(); - virtual CBasePin *GetPin(int n); - FILTER_STATE GetRealState(); - void SendRepaint(); - void SendNotifyWindow(IPin *pPin,HWND hwnd); - BOOL OnDisplayChange(); - void SetRepaintStatus(BOOL bRepaint); - - // Override the filter and pin interface functions - - STDMETHODIMP Stop(); - STDMETHODIMP Pause(); - STDMETHODIMP Run(REFERENCE_TIME StartTime); - STDMETHODIMP GetState(DWORD dwMSecs, __out FILTER_STATE *State); - STDMETHODIMP FindPin(LPCWSTR Id, __deref_out IPin **ppPin); - - // These are available for a quality management implementation - - virtual void OnRenderStart(IMediaSample *pMediaSample); - virtual void OnRenderEnd(IMediaSample *pMediaSample); - virtual HRESULT OnStartStreaming() { return NOERROR; }; - virtual HRESULT OnStopStreaming() { return NOERROR; }; - virtual void OnWaitStart() { }; - virtual void OnWaitEnd() { }; - virtual void PrepareRender() { }; - -#ifdef PERF - REFERENCE_TIME m_trRenderStart; // Just before we started drawing - // Set in OnRenderStart, Used in OnRenderEnd - int m_idBaseStamp; // MSR_id for frame time stamp - int m_idBaseRenderTime; // MSR_id for true wait time - int m_idBaseAccuracy; // MSR_id for time frame is late (int) -#endif - - // Quality management implementation for scheduling rendering - - virtual BOOL ScheduleSample(IMediaSample *pMediaSample); - virtual HRESULT GetSampleTimes(IMediaSample *pMediaSample, - __out REFERENCE_TIME *pStartTime, - __out REFERENCE_TIME *pEndTime); - - virtual HRESULT ShouldDrawSampleNow(IMediaSample *pMediaSample, - __out REFERENCE_TIME *ptrStart, - __out REFERENCE_TIME *ptrEnd); - - // Lots of end of stream complexities - - void TimerCallback(); - void ResetEndOfStreamTimer(); - HRESULT NotifyEndOfStream(); - virtual HRESULT SendEndOfStream(); - virtual HRESULT ResetEndOfStream(); - virtual HRESULT EndOfStream(); - - // Rendering is based around the clock - - void SignalTimerFired(); - virtual HRESULT CancelNotification(); - virtual HRESULT ClearPendingSample(); - - // Called when the filter changes state - - virtual HRESULT Active(); - virtual HRESULT Inactive(); - virtual HRESULT StartStreaming(); - virtual HRESULT StopStreaming(); - virtual HRESULT BeginFlush(); - virtual HRESULT EndFlush(); - - // Deal with connections and type changes - - virtual HRESULT BreakConnect(); - virtual HRESULT SetMediaType(const CMediaType *pmt); - virtual HRESULT CompleteConnect(IPin *pReceivePin); - - // These look after the handling of data samples - - virtual HRESULT PrepareReceive(IMediaSample *pMediaSample); - virtual HRESULT Receive(IMediaSample *pMediaSample); - virtual BOOL HaveCurrentSample(); - virtual IMediaSample *GetCurrentSample(); - virtual HRESULT Render(IMediaSample *pMediaSample); - - // Derived classes MUST override these - virtual HRESULT DoRenderSample(IMediaSample *pMediaSample) PURE; - virtual HRESULT CheckMediaType(const CMediaType *) PURE; - - // Helper - void WaitForReceiveToComplete(); -}; - - -// CBaseVideoRenderer is a renderer class (see its ancestor class) and -// it handles scheduling of media samples so that they are drawn at the -// correct time by the reference clock. It implements a degradation -// strategy. Possible degradation modes are: -// Drop frames here (only useful if the drawing takes significant time) -// Signal supplier (upstream) to drop some frame(s) - i.e. one-off skip. -// Signal supplier to change the frame rate - i.e. ongoing skipping. -// Or any combination of the above. -// In order to determine what's useful to try we need to know what's going -// on. This is done by timing various operations (including the supplier). -// This timing is done by using timeGetTime as it is accurate enough and -// usually cheaper than calling the reference clock. It also tells the -// truth if there is an audio break and the reference clock stops. -// We provide a number of public entry points (named OnXxxStart, OnXxxEnd) -// which the rest of the renderer calls at significant moments. These do -// the timing. - -// the number of frames that the sliding averages are averaged over. -// the rule is (1024*NewObservation + (AVGPERIOD-1) * PreviousAverage)/AVGPERIOD -#define AVGPERIOD 4 -#define DO_MOVING_AVG(avg,obs) (avg = (1024*obs + (AVGPERIOD-1)*avg)/AVGPERIOD) -// Spot the bug in this macro - I can't. but it doesn't work! - -class CBaseVideoRenderer : public CBaseRenderer, // Base renderer class - public IQualProp, // Property page guff - public IQualityControl // Allow throttling -{ -protected: - - // Hungarian: - // tFoo is the time Foo in mSec (beware m_tStart from filter.h) - // trBar is the time Bar by the reference clock - - //****************************************************************** - // State variables to control synchronisation - //****************************************************************** - - // Control of sending Quality messages. We need to know whether - // we are in trouble (e.g. frames being dropped) and where the time - // is being spent. - - // When we drop a frame we play the next one early. - // The frame after that is likely to wait before drawing and counting this - // wait as spare time is unfair, so we count it as a zero wait. - // We therefore need to know whether we are playing frames early or not. - - int m_nNormal; // The number of consecutive frames - // drawn at their normal time (not early) - // -1 means we just dropped a frame. - -#ifdef PERF - BOOL m_bDrawLateFrames; // Don't drop any frames (debug and I'm - // not keen on people using it!) -#endif - - BOOL m_bSupplierHandlingQuality;// The response to Quality messages says - // our supplier is handling things. - // We will allow things to go extra late - // before dropping frames. We will play - // very early after he has dropped one. - - // Control of scheduling, frame dropping etc. - // We need to know where the time is being spent so as to tell whether - // we should be taking action here, signalling supplier or what. - // The variables are initialised to a mode of NOT dropping frames. - // They will tell the truth after a few frames. - // We typically record a start time for an event, later we get the time - // again and subtract to get the elapsed time, and we average this over - // a few frames. The average is used to tell what mode we are in. - - // Although these are reference times (64 bit) they are all DIFFERENCES - // between times which are small. An int will go up to 214 secs before - // overflow. Avoiding 64 bit multiplications and divisions seems - // worth while. - - - - // Audio-video throttling. If the user has turned up audio quality - // very high (in principle it could be any other stream, not just audio) - // then we can receive cries for help via the graph manager. In this case - // we put in a wait for some time after rendering each frame. - int m_trThrottle; - - // The time taken to render (i.e. BitBlt) frames controls which component - // needs to degrade. If the blt is expensive, the renderer degrades. - // If the blt is cheap it's done anyway and the supplier degrades. - int m_trRenderAvg; // Time frames are taking to blt - int m_trRenderLast; // Time for last frame blt - int m_tRenderStart; // Just before we started drawing (mSec) - // derived from timeGetTime. - - // When frames are dropped we will play the next frame as early as we can. - // If it was a false alarm and the machine is fast we slide gently back to - // normal timing. To do this, we record the offset showing just how early - // we really are. This will normally be negative meaning early or zero. - int m_trEarliness; - - // Target provides slow long-term feedback to try to reduce the - // average sync offset to zero. Whenever a frame is actually rendered - // early we add a msec or two, whenever late we take off a few. - // We add or take off 1/32 of the error time. - // Eventually we should be hovering around zero. For a really bad case - // where we were (say) 300mSec off, it might take 100 odd frames to - // settle down. The rate of change of this is intended to be slower - // than any other mechanism in Quartz, thereby avoiding hunting. - int m_trTarget; - - // The proportion of time spent waiting for the right moment to blt - // controls whether we bother to drop a frame or whether we reckon that - // we're doing well enough that we can stand a one-frame glitch. - int m_trWaitAvg; // Average of last few wait times - // (actually we just average how early - // we were). Negative here means LATE. - - // The average inter-frame time. - // This is used to calculate the proportion of the time used by the - // three operations (supplying us, waiting, rendering) - int m_trFrameAvg; // Average inter-frame time - int m_trDuration; // duration of last frame. - -#ifdef PERF - // Performance logging identifiers - int m_idTimeStamp; // MSR_id for frame time stamp - int m_idEarliness; // MSR_id for earliness fudge - int m_idTarget; // MSR_id for Target fudge - int m_idWaitReal; // MSR_id for true wait time - int m_idWait; // MSR_id for wait time recorded - int m_idFrameAccuracy; // MSR_id for time frame is late (int) - int m_idRenderAvg; // MSR_id for Render time recorded (int) - int m_idSchLateTime; // MSR_id for lateness at scheduler - int m_idQualityRate; // MSR_id for Quality rate requested - int m_idQualityTime; // MSR_id for Quality time requested - int m_idDecision; // MSR_id for decision code - int m_idDuration; // MSR_id for duration of a frame - int m_idThrottle; // MSR_id for audio-video throttling - //int m_idDebug; // MSR_id for trace style debugging - //int m_idSendQuality; // MSR_id for timing the notifications per se -#endif // PERF - REFERENCE_TIME m_trRememberStampForPerf; // original time stamp of frame - // with no earliness fudges etc. -#ifdef PERF - REFERENCE_TIME m_trRememberFrameForPerf; // time when previous frame rendered - - // debug... - int m_idFrameAvg; - int m_idWaitAvg; -#endif - - // PROPERTY PAGE - // This has edit fields that show the user what's happening - // These member variables hold these counts. - - int m_cFramesDropped; // cumulative frames dropped IN THE RENDERER - int m_cFramesDrawn; // Frames since streaming started seen BY THE - // RENDERER (some may be dropped upstream) - - // Next two support average sync offset and standard deviation of sync offset. - LONGLONG m_iTotAcc; // Sum of accuracies in mSec - LONGLONG m_iSumSqAcc; // Sum of squares of (accuracies in mSec) - - // Next two allow jitter calculation. Jitter is std deviation of frame time. - REFERENCE_TIME m_trLastDraw; // Time of prev frame (for inter-frame times) - LONGLONG m_iSumSqFrameTime; // Sum of squares of (inter-frame time in mSec) - LONGLONG m_iSumFrameTime; // Sum of inter-frame times in mSec - - // To get performance statistics on frame rate, jitter etc, we need - // to record the lateness and inter-frame time. What we actually need are the - // data above (sum, sum of squares and number of entries for each) but the data - // is generated just ahead of time and only later do we discover whether the - // frame was actually drawn or not. So we have to hang on to the data - int m_trLate; // hold onto frame lateness - int m_trFrame; // hold onto inter-frame time - - int m_tStreamingStart; // if streaming then time streaming started - // else time of last streaming session - // used for property page statistics -#ifdef PERF - LONGLONG m_llTimeOffset; // timeGetTime()*10000+m_llTimeOffset==ref time -#endif - -public: - - - CBaseVideoRenderer(REFCLSID RenderClass, // CLSID for this renderer - __in_opt LPCTSTR pName, // Debug ONLY description - __inout_opt LPUNKNOWN pUnk, // Aggregated owner object - __inout HRESULT *phr); // General OLE return code - - ~CBaseVideoRenderer(); - - // IQualityControl methods - Notify allows audio-video throttling - - STDMETHODIMP SetSink( IQualityControl * piqc); - STDMETHODIMP Notify( IBaseFilter * pSelf, Quality q); - - // These provide a full video quality management implementation - - void OnRenderStart(IMediaSample *pMediaSample); - void OnRenderEnd(IMediaSample *pMediaSample); - void OnWaitStart(); - void OnWaitEnd(); - HRESULT OnStartStreaming(); - HRESULT OnStopStreaming(); - void ThrottleWait(); - - // Handle the statistics gathering for our quality management - - void PreparePerformanceData(int trLate, int trFrame); - virtual void RecordFrameLateness(int trLate, int trFrame); - virtual void OnDirectRender(IMediaSample *pMediaSample); - virtual HRESULT ResetStreamingTimes(); - BOOL ScheduleSample(IMediaSample *pMediaSample); - HRESULT ShouldDrawSampleNow(IMediaSample *pMediaSample, - __inout REFERENCE_TIME *ptrStart, - __inout REFERENCE_TIME *ptrEnd); - - virtual HRESULT SendQuality(REFERENCE_TIME trLate, REFERENCE_TIME trRealStream); - STDMETHODIMP JoinFilterGraph(__inout_opt IFilterGraph * pGraph, __in_opt LPCWSTR pName); - - // - // Do estimates for standard deviations for per-frame - // statistics - // - // *piResult = (llSumSq - iTot * iTot / m_cFramesDrawn - 1) / - // (m_cFramesDrawn - 2) - // or 0 if m_cFramesDrawn <= 3 - // - HRESULT GetStdDev( - int nSamples, - __out int *piResult, - LONGLONG llSumSq, - LONGLONG iTot - ); -public: - - // IQualProp property page support - - STDMETHODIMP get_FramesDroppedInRenderer(__out int *cFramesDropped); - STDMETHODIMP get_FramesDrawn(__out int *pcFramesDrawn); - STDMETHODIMP get_AvgFrameRate(__out int *piAvgFrameRate); - STDMETHODIMP get_Jitter(__out int *piJitter); - STDMETHODIMP get_AvgSyncOffset(__out int *piAvg); - STDMETHODIMP get_DevSyncOffset(__out int *piDev); - - // Implement an IUnknown interface and expose IQualProp - - DECLARE_IUNKNOWN - STDMETHODIMP NonDelegatingQueryInterface(REFIID riid,__deref_out VOID **ppv); -}; - -#endif // __RENBASE__ - diff --git a/UnityWebcam/UnityCamService/includes/schedule.h b/UnityWebcam/UnityCamService/includes/schedule.h deleted file mode 100644 index 65ed402..0000000 --- a/UnityWebcam/UnityCamService/includes/schedule.h +++ /dev/null @@ -1,128 +0,0 @@ -//------------------------------------------------------------------------------ -// File: Schedule.h -// -// Desc: DirectShow base classes. -// -// Copyright (c) 1996-2001 Microsoft Corporation. All rights reserved. -//------------------------------------------------------------------------------ - - -#ifndef __CAMSchedule__ -#define __CAMSchedule__ - -class CAMSchedule : private CBaseObject -{ -public: - virtual ~CAMSchedule(); - // ev is the event we should fire if the advise time needs re-evaluating - CAMSchedule( HANDLE ev ); - - DWORD GetAdviseCount(); - REFERENCE_TIME GetNextAdviseTime(); - - // We need a method for derived classes to add advise packets, we return the cookie - DWORD_PTR AddAdvisePacket( const REFERENCE_TIME & time1, const REFERENCE_TIME & time2, HANDLE h, BOOL periodic ); - // And a way to cancel - HRESULT Unadvise(DWORD_PTR dwAdviseCookie); - - // Tell us the time please, and we'll dispatch the expired events. We return the time of the next event. - // NB: The time returned will be "useless" if you start adding extra Advises. But that's the problem of - // whoever is using this helper class (typically a clock). - REFERENCE_TIME Advise( const REFERENCE_TIME & rtTime ); - - // Get the event handle which will be set if advise time requires re-evaluation. - HANDLE GetEvent() const { return m_ev; } - -private: - // We define the nodes that will be used in our singly linked list - // of advise packets. The list is ordered by time, with the - // elements that will expire first at the front. - class CAdvisePacket - { - public: - CAdvisePacket() - {} - - CAdvisePacket * m_next; - DWORD_PTR m_dwAdviseCookie; - REFERENCE_TIME m_rtEventTime; // Time at which event should be set - REFERENCE_TIME m_rtPeriod; // Periodic time - HANDLE m_hNotify; // Handle to event or semephore - BOOL m_bPeriodic; // TRUE => Periodic event - - CAdvisePacket( __inout_opt CAdvisePacket * next, LONGLONG time ) : m_next(next), m_rtEventTime(time) - {} - - void InsertAfter( __inout CAdvisePacket * p ) - { - p->m_next = m_next; - m_next = p; - } - - int IsZ() const // That is, is it the node that represents the end of the list - { return m_next == 0; } - - CAdvisePacket * RemoveNext() - { - CAdvisePacket *const next = m_next; - CAdvisePacket *const new_next = next->m_next; - m_next = new_next; - return next; - } - - void DeleteNext() - { - delete RemoveNext(); - } - - CAdvisePacket * Next() const - { - CAdvisePacket * result = m_next; - if (result->IsZ()) result = 0; - return result; - } - - DWORD_PTR Cookie() const - { return m_dwAdviseCookie; } - }; - - // Structure is: - // head -> elmt1 -> elmt2 -> z -> null - // So an empty list is: head -> z -> null - // Having head & z as links makes insertaion, - // deletion and shunting much easier. - CAdvisePacket head, z; // z is both a tail and a sentry - - volatile DWORD_PTR m_dwNextCookie; // Strictly increasing - volatile DWORD m_dwAdviseCount; // Number of elements on list - - CCritSec m_Serialize; - - // AddAdvisePacket: adds the packet, returns the cookie (0 if failed) - DWORD_PTR AddAdvisePacket( __inout CAdvisePacket * pPacket ); - // Event that we should set if the packed added above will be the next to fire. - const HANDLE m_ev; - - // A Shunt is where we have changed the first element in the - // list and want it re-evaluating (i.e. repositioned) in - // the list. - void ShuntHead(); - - // Rather than delete advise packets, we cache them for future use - CAdvisePacket * m_pAdviseCache; - DWORD m_dwCacheCount; - enum { dwCacheMax = 5 }; // Don't bother caching more than five - - void Delete( __inout CAdvisePacket * pLink );// This "Delete" will cache the Link - -// Attributes and methods for debugging -public: -#ifdef DEBUG - void DumpLinkedList(); -#else - void DumpLinkedList() {} -#endif - -}; - -#endif // __CAMSchedule__ diff --git a/UnityWebcam/UnityCamService/includes/seekpt.h b/UnityWebcam/UnityCamService/includes/seekpt.h deleted file mode 100644 index 26abdf3..0000000 --- a/UnityWebcam/UnityCamService/includes/seekpt.h +++ /dev/null @@ -1,30 +0,0 @@ -//------------------------------------------------------------------------------ -// File: SeekPT.h -// -// Desc: DirectShow base classes. -// -// Copyright (c) 1992-2001 Microsoft Corporation. All rights reserved. -//------------------------------------------------------------------------------ - - -#ifndef __seekpt_h__ -#define __seekpt_h__ - - -class CSeekingPassThru : public ISeekingPassThru, public CUnknown -{ -public: - static CUnknown *CreateInstance(__inout_opt LPUNKNOWN pUnk, __inout HRESULT *phr); - CSeekingPassThru(__in_opt LPCTSTR pName, __inout_opt LPUNKNOWN pUnk, __inout HRESULT *phr); - ~CSeekingPassThru(); - - DECLARE_IUNKNOWN; - STDMETHODIMP NonDelegatingQueryInterface(REFIID riid, __deref_out void ** ppv); - - STDMETHODIMP Init(BOOL bSupportRendering, IPin *pPin); - -private: - CPosPassThru *m_pPosPassThru; -}; - -#endif diff --git a/UnityWebcam/UnityCamService/includes/source.h b/UnityWebcam/UnityCamService/includes/source.h deleted file mode 100644 index e6e451b..0000000 --- a/UnityWebcam/UnityCamService/includes/source.h +++ /dev/null @@ -1,172 +0,0 @@ -//------------------------------------------------------------------------------ -// File: Source.h -// -// Desc: DirectShow base classes - defines classes to simplify creation of -// ActiveX source filters that support continuous generation of data. -// No support is provided for IMediaControl or IMediaPosition. -// -// Copyright (c) 1992-2001 Microsoft Corporation. All rights reserved. -//------------------------------------------------------------------------------ - - -// -// Derive your source filter from CSource. -// During construction either: -// Create some CSourceStream objects to manage your pins -// Provide the user with a means of doing so eg, an IPersistFile interface. -// -// CSource provides: -// IBaseFilter interface management -// IMediaFilter interface management, via CBaseFilter -// Pin counting for CBaseFilter -// -// Derive a class from CSourceStream to manage your output pin types -// Implement GetMediaType/1 to return the type you support. If you support multiple -// types then overide GetMediaType/3, CheckMediaType and GetMediaTypeCount. -// Implement Fillbuffer() to put data into one buffer. -// -// CSourceStream provides: -// IPin management via CBaseOutputPin -// Worker thread management - -#ifndef __CSOURCE__ -#define __CSOURCE__ - -class CSourceStream; // The class that will handle each pin - - -// -// CSource -// -// Override construction to provide a means of creating -// CSourceStream derived objects - ie a way of creating pins. -class CSource : public CBaseFilter { -public: - - CSource(__in_opt LPCTSTR pName, __inout_opt LPUNKNOWN lpunk, CLSID clsid, __inout HRESULT *phr); - CSource(__in_opt LPCTSTR pName, __inout_opt LPUNKNOWN lpunk, CLSID clsid); -#ifdef UNICODE - CSource(__in_opt LPCSTR pName, __inout_opt LPUNKNOWN lpunk, CLSID clsid, __inout HRESULT *phr); - CSource(__in_opt LPCSTR pName, __inout_opt LPUNKNOWN lpunk, CLSID clsid); -#endif - ~CSource(); - - int GetPinCount(void); - CBasePin *GetPin(int n); - - // -- Utilities -- - - CCritSec* pStateLock(void) { return &m_cStateLock; } // provide our critical section - - HRESULT AddPin(__in CSourceStream *); - HRESULT RemovePin(__in CSourceStream *); - - STDMETHODIMP FindPin( - LPCWSTR Id, - __deref_out IPin ** ppPin - ); - - int FindPinNumber(__in IPin *iPin); - -protected: - - int m_iPins; // The number of pins on this filter. Updated by CSourceStream - // constructors & destructors. - CSourceStream **m_paStreams; // the pins on this filter. - - CCritSec m_cStateLock; // Lock this to serialize function accesses to the filter state - -}; - - -// -// CSourceStream -// -// Use this class to manage a stream of data that comes from a -// pin. -// Uses a worker thread to put data on the pin. -class CSourceStream : public CAMThread, public CBaseOutputPin { -public: - - CSourceStream(__in_opt LPCTSTR pObjectName, - __inout HRESULT *phr, - __inout CSource *pms, - __in_opt LPCWSTR pName); -#ifdef UNICODE - CSourceStream(__in_opt LPCSTR pObjectName, - __inout HRESULT *phr, - __inout CSource *pms, - __in_opt LPCWSTR pName); -#endif - virtual ~CSourceStream(void); // virtual destructor ensures derived class destructors are called too. - -protected: - - CSource *m_pFilter; // The parent of this stream - - // * - // * Data Source - // * - // * The following three functions: FillBuffer, OnThreadCreate/Destroy, are - // * called from within the ThreadProc. They are used in the creation of - // * the media samples this pin will provide - // * - - // Override this to provide the worker thread a means - // of processing a buffer - virtual HRESULT FillBuffer(IMediaSample *pSamp) PURE; - - // Called as the thread is created/destroyed - use to perform - // jobs such as start/stop streaming mode - // If OnThreadCreate returns an error the thread will exit. - virtual HRESULT OnThreadCreate(void) {return NOERROR;}; - virtual HRESULT OnThreadDestroy(void) {return NOERROR;}; - virtual HRESULT OnThreadStartPlay(void) {return NOERROR;}; - - // * - // * Worker Thread - // * - - HRESULT Active(void); // Starts up the worker thread - HRESULT Inactive(void); // Exits the worker thread. - -public: - // thread commands - enum Command {CMD_INIT, CMD_PAUSE, CMD_RUN, CMD_STOP, CMD_EXIT}; - HRESULT Init(void) { return CallWorker(CMD_INIT); } - HRESULT Exit(void) { return CallWorker(CMD_EXIT); } - HRESULT Run(void) { return CallWorker(CMD_RUN); } - HRESULT Pause(void) { return CallWorker(CMD_PAUSE); } - HRESULT Stop(void) { return CallWorker(CMD_STOP); } - -protected: - Command GetRequest(void) { return (Command) CAMThread::GetRequest(); } - BOOL CheckRequest(Command *pCom) { return CAMThread::CheckRequest( (DWORD *) pCom); } - - // override these if you want to add thread commands - virtual DWORD ThreadProc(void); // the thread function - - virtual HRESULT DoBufferProcessingLoop(void); // the loop executed whilst running - - - // * - // * AM_MEDIA_TYPE support - // * - - // If you support more than one media type then override these 2 functions - virtual HRESULT CheckMediaType(const CMediaType *pMediaType); - virtual HRESULT GetMediaType(int iPosition, __inout CMediaType *pMediaType); // List pos. 0-n - - // If you support only one type then override this fn. - // This will only be called by the default implementations - // of CheckMediaType and GetMediaType(int, CMediaType*) - // You must override this fn. or the above 2! - virtual HRESULT GetMediaType(__inout CMediaType *pMediaType) {return E_UNEXPECTED;} - - STDMETHODIMP QueryId( - __deref_out LPWSTR * Id - ); -}; - -#endif // __CSOURCE__ - diff --git a/UnityWebcam/UnityCamService/includes/streams.h b/UnityWebcam/UnityCamService/includes/streams.h deleted file mode 100644 index 72c6fd0..0000000 --- a/UnityWebcam/UnityCamService/includes/streams.h +++ /dev/null @@ -1,202 +0,0 @@ -//------------------------------------------------------------------------------ -// File: Streams.h -// -// Desc: DirectShow base classes - defines overall streams architecture. -// -// Copyright (c) 1992-2001 Microsoft Corporation. All rights reserved. -//------------------------------------------------------------------------------ - - -#ifndef __STREAMS__ -#define __STREAMS__ - -#ifdef _MSC_VER -// disable some level-4 warnings, use #pragma warning(enable:###) to re-enable -#pragma warning(disable:4100) // warning C4100: unreferenced formal parameter -#pragma warning(disable:4201) // warning C4201: nonstandard extension used : nameless struct/union -#pragma warning(disable:4511) // warning C4511: copy constructor could not be generated -#pragma warning(disable:4512) // warning C4512: assignment operator could not be generated -#pragma warning(disable:4514) // warning C4514: "unreferenced inline function has been removed" - -#if _MSC_VER>=1100 -#define AM_NOVTABLE __declspec(novtable) -#else -#define AM_NOVTABLE -#endif -#endif // MSC_VER - - -// Because of differences between Visual C++ and older Microsoft SDKs, -// you may have defined _DEBUG without defining DEBUG. This logic -// ensures that both will be set if Visual C++ sets _DEBUG. -#ifdef _DEBUG -#ifndef DEBUG -#define DEBUG -#endif -#endif - - -#include -#include -#include -#include -#include - - -#ifndef NUMELMS -#if _WIN32_WINNT < 0x0600 - #define NUMELMS(aa) (sizeof(aa)/sizeof((aa)[0])) -#else - #define NUMELMS(aa) ARRAYSIZE(aa) -#endif -#endif - -/////////////////////////////////////////////////////////////////////////// -// The following definitions come from the Platform SDK and are required if -// the applicaiton is being compiled with the headers from Visual C++ 6.0. -/////////////////////////////////////////////////// //////////////////////// -#ifndef InterlockedExchangePointer - #define InterlockedExchangePointer(Target, Value) \ - (PVOID)InterlockedExchange((PLONG)(Target), (LONG)(Value)) -#endif - -#ifndef _WAVEFORMATEXTENSIBLE_ -#define _WAVEFORMATEXTENSIBLE_ -typedef struct { - WAVEFORMATEX Format; - union { - WORD wValidBitsPerSample; /* bits of precision */ - WORD wSamplesPerBlock; /* valid if wBitsPerSample==0 */ - WORD wReserved; /* If neither applies, set to zero. */ - } Samples; - DWORD dwChannelMask; /* which channels are */ - /* present in stream */ - GUID SubFormat; -} WAVEFORMATEXTENSIBLE, *PWAVEFORMATEXTENSIBLE; -#endif // !_WAVEFORMATEXTENSIBLE_ - -#if !defined(WAVE_FORMAT_EXTENSIBLE) -#define WAVE_FORMAT_EXTENSIBLE 0xFFFE -#endif // !defined(WAVE_FORMAT_EXTENSIBLE) - -#ifndef GetWindowLongPtr - #define GetWindowLongPtrA GetWindowLongA - #define GetWindowLongPtrW GetWindowLongW - #ifdef UNICODE - #define GetWindowLongPtr GetWindowLongPtrW - #else - #define GetWindowLongPtr GetWindowLongPtrA - #endif // !UNICODE -#endif // !GetWindowLongPtr - -#ifndef SetWindowLongPtr - #define SetWindowLongPtrA SetWindowLongA - #define SetWindowLongPtrW SetWindowLongW - #ifdef UNICODE - #define SetWindowLongPtr SetWindowLongPtrW - #else - #define SetWindowLongPtr SetWindowLongPtrA - #endif // !UNICODE -#endif // !SetWindowLongPtr - -#ifndef GWLP_WNDPROC - #define GWLP_WNDPROC (-4) -#endif -#ifndef GWLP_HINSTANCE - #define GWLP_HINSTANCE (-6) -#endif -#ifndef GWLP_HWNDPARENT - #define GWLP_HWNDPARENT (-8) -#endif -#ifndef GWLP_USERDATA - #define GWLP_USERDATA (-21) -#endif -#ifndef GWLP_ID - #define GWLP_ID (-12) -#endif -#ifndef DWLP_MSGRESULT - #define DWLP_MSGRESULT 0 -#endif -#ifndef DWLP_DLGPROC - #define DWLP_DLGPROC DWLP_MSGRESULT + sizeof(LRESULT) -#endif -#ifndef DWLP_USER - #define DWLP_USER DWLP_DLGPROC + sizeof(DLGPROC) -#endif - - -#pragma warning(push) -#pragma warning(disable: 4312 4244) -// _GetWindowLongPtr -// Templated version of GetWindowLongPtr, to suppress spurious compiler warning. -template -T _GetWindowLongPtr(HWND hwnd, int nIndex) -{ - return (T)GetWindowLongPtr(hwnd, nIndex); -} - -// _SetWindowLongPtr -// Templated version of SetWindowLongPtr, to suppress spurious compiler warning. -template -LONG_PTR _SetWindowLongPtr(HWND hwnd, int nIndex, T p) -{ - return SetWindowLongPtr(hwnd, nIndex, (LONG_PTR)p); -} -#pragma warning(pop) - -/////////////////////////////////////////////////////////////////////////// -// End Platform SDK definitions -/////////////////////////////////////////////////////////////////////////// - - -#include // Generated IDL header file for streams interfaces -#include // required by amvideo.h - -#include // Helper class for REFERENCE_TIME management -#include // Debug support for logging and ASSERTs -#include // ActiveMovie video interfaces and definitions -//include amaudio.h explicitly if you need it. it requires the DX SDK. -//#include // ActiveMovie audio interfaces and definitions -#include // General helper classes for threads etc -#include // Base COM classes to support IUnknown -#include // Filter registration support functions -#include // Performance measurement -#include // Light weight com function prototypes - -#include // Simple cache container class -#include // Non MFC generic list class -#include // CMsgThread -#include // Helper class for managing media types -#include // conversions between FOURCCs and GUIDs -#include // generated from control.odl -#include // control interface utility classes -#include // event code definitions -#include // Main streams architecture class hierachy -#include // Generic transform filter -#include // Generic transform-in-place filter -#include // declaration of type GUIDs and well-known clsids -#include // Generic source filter -#include // Output pin queueing -#include // HRESULT status and error definitions -#include // Base class for writing ActiveX renderers -#include // Helps with filters that manage windows -#include // Implements the IVideoWindow interface -#include // Specifically video related classes -#include // Base clock class -#include // System clock -#include // IPersistStream helper class -#include // Video Transform Filter base class -#include -#include // Base property page class -#include // IAMStreamControl support -#include // External device control interface defines -#include // audio filter device error event codes - - - -#else - #ifdef DEBUG - #pragma message("STREAMS.H included TWICE") - #endif -#endif // __STREAMS__ - diff --git a/UnityWebcam/UnityCamService/includes/strmctl.h b/UnityWebcam/UnityCamService/includes/strmctl.h deleted file mode 100644 index 4077e6c..0000000 --- a/UnityWebcam/UnityCamService/includes/strmctl.h +++ /dev/null @@ -1,157 +0,0 @@ -//------------------------------------------------------------------------------ -// File: StrmCtl.h -// -// Desc: DirectShow base classes. -// -// Copyright (c) 1996-2001 Microsoft Corporation. All rights reserved. -//------------------------------------------------------------------------------ - - -#ifndef __strmctl_h__ -#define __strmctl_h__ - -class CBaseStreamControl : public IAMStreamControl -{ -public: - // Used by the implementation - enum StreamControlState - { STREAM_FLOWING = 0x1000, - STREAM_DISCARDING - }; - -private: - enum StreamControlState m_StreamState; // Current stream state - enum StreamControlState m_StreamStateOnStop; // State after next stop - // (i.e.Blocking or Discarding) - - REFERENCE_TIME m_tStartTime; // MAX_TIME implies none - REFERENCE_TIME m_tStopTime; // MAX_TIME implies none - DWORD m_dwStartCookie; // Cookie for notification to app - DWORD m_dwStopCookie; // Cookie for notification to app - volatile BOOL m_bIsFlushing; // No optimization pls! - volatile BOOL m_bStopSendExtra; // bSendExtra was set - volatile BOOL m_bStopExtraSent; // the extra one was sent - - CCritSec m_CritSec; // CritSec to guard above attributes - - // Event to fire when we can come - // out of blocking, or to come out of waiting - // to discard if we change our minds. - // - CAMEvent m_StreamEvent; - - // All of these methods execute immediately. Helpers for others. - // - void ExecuteStop(); - void ExecuteStart(); - void CancelStop(); - void CancelStart(); - - // Some things we need to be told by our owning filter - // Your pin must also expose IAMStreamControl when QI'd for it! - // - IReferenceClock * m_pRefClock; // Need it to set advises - // Filter must tell us via - // SetSyncSource - IMediaEventSink * m_pSink; // Event sink - // Filter must tell us after it - // creates it in JoinFilterGraph() - FILTER_STATE m_FilterState; // Just need it! - // Filter must tell us via - // NotifyFilterState - REFERENCE_TIME m_tRunStart; // Per the Run call to the filter - - // This guy will return one of the three StreamControlState's. Here's what - // the caller should do for each one: - // - // STREAM_FLOWING: Proceed as usual (render or pass the sample on) - // STREAM_DISCARDING: Calculate the time 'til *pSampleStop and wait - // that long for the event handle - // (GetStreamEventHandle()). If the wait - // expires, throw the sample away. If the event - // fires, call me back - I've changed my mind. - // - enum StreamControlState CheckSampleTimes( __in const REFERENCE_TIME * pSampleStart, - __in const REFERENCE_TIME * pSampleStop ); - -public: - // You don't have to tell us much when we're created, but there are other - // obligations that must be met. See SetSyncSource & NotifyFilterState - // below. - // - CBaseStreamControl(__inout_opt HRESULT *phr = NULL); - ~CBaseStreamControl(); - - // If you want this class to work properly, there are thing you need to - // (keep) telling it. Filters with pins that use this class - // should ensure that they pass through to this method any calls they - // receive on their SetSyncSource. - - // We need a clock to see what time it is. This is for the - // "discard in a timely fashion" logic. If we discard everything as - // quick as possible, a whole 60 minute file could get discarded in the - // first 10 seconds, and if somebody wants to turn streaming on at 30 - // minutes into the file, and they make the call more than a few seconds - // after the graph is run, it may be too late! - // So we hold every sample until it's time has gone, then we discard it. - // The filter should call this when it gets a SetSyncSource - // - void SetSyncSource( IReferenceClock * pRefClock ) - { - CAutoLock lck(&m_CritSec); - if (m_pRefClock) m_pRefClock->Release(); - m_pRefClock = pRefClock; - if (m_pRefClock) m_pRefClock->AddRef(); - } - - // Set event sink for notifications - // The filter should call this in its JoinFilterGraph after it creates the - // IMediaEventSink - // - void SetFilterGraph( IMediaEventSink *pSink ) { - m_pSink = pSink; - } - - // Since we schedule in stream time, we need the tStart and must track the - // state of our owning filter. - // The app should call this ever state change - // - void NotifyFilterState( FILTER_STATE new_state, REFERENCE_TIME tStart = 0 ); - - // Filter should call Flushing(TRUE) in BeginFlush, - // and Flushing(FALSE) in EndFlush. - // - void Flushing( BOOL bInProgress ); - - - // The two main methods of IAMStreamControl - - // Class adds default values suitable for immediate - // muting and unmuting of the stream. - - STDMETHODIMP StopAt( const REFERENCE_TIME * ptStop = NULL, - BOOL bSendExtra = FALSE, - DWORD dwCookie = 0 ); - STDMETHODIMP StartAt( const REFERENCE_TIME * ptStart = NULL, - DWORD dwCookie = 0 ); - STDMETHODIMP GetInfo( __out AM_STREAM_INFO *pInfo); - - // Helper function for pin's receive method. Call this with - // the sample and we'll tell you what to do with it. We'll do a - // WaitForSingleObject within this call if one is required. This is - // a "What should I do with this sample?" kind of call. We'll tell the - // caller to either flow it or discard it. - // If pSample is NULL we evaluate based on the current state - // settings - enum StreamControlState CheckStreamState( IMediaSample * pSample ); - -private: - // These don't require locking, but we are relying on the fact that - // m_StreamState can be retrieved with integrity, and is a snap shot that - // may have just been, or may be just about to be, changed. - HANDLE GetStreamEventHandle() const { return m_StreamEvent; } - enum StreamControlState GetStreamState() const { return m_StreamState; } - BOOL IsStreaming() const { return m_StreamState == STREAM_FLOWING; } -}; - -#endif diff --git a/UnityWebcam/UnityCamService/includes/sysclock.h b/UnityWebcam/UnityCamService/includes/sysclock.h deleted file mode 100644 index bf9192c..0000000 --- a/UnityWebcam/UnityCamService/includes/sysclock.h +++ /dev/null @@ -1,39 +0,0 @@ -//------------------------------------------------------------------------------ -// File: SysClock.h -// -// Desc: DirectShow base classes - defines a system clock implementation of -// IReferenceClock. -// -// Copyright (c) 1992-2001 Microsoft Corporation. All rights reserved. -//------------------------------------------------------------------------------ - - -#ifndef __SYSTEMCLOCK__ -#define __SYSTEMCLOCK__ - -// -// Base clock. Uses timeGetTime ONLY -// Uses most of the code in the base reference clock. -// Provides GetTime -// - -class CSystemClock : public CBaseReferenceClock, public IAMClockAdjust, public IPersist -{ -public: - // We must be able to create an instance of ourselves - static CUnknown * WINAPI CreateInstance(__inout_opt LPUNKNOWN pUnk, __inout HRESULT *phr); - CSystemClock(__in_opt LPCTSTR pName, __inout_opt LPUNKNOWN pUnk, __inout HRESULT *phr); - - DECLARE_IUNKNOWN - - STDMETHODIMP NonDelegatingQueryInterface(REFIID riid, __deref_out void ** ppv); - - // Yield up our class id so that we can be persisted - // Implement required Ipersist method - STDMETHODIMP GetClassID(__out CLSID *pClsID); - - // IAMClockAdjust methods - STDMETHODIMP SetClockDelta(REFERENCE_TIME rtDelta); -}; //CSystemClock - -#endif /* __SYSTEMCLOCK__ */ diff --git a/UnityWebcam/UnityCamService/includes/transfrm.h b/UnityWebcam/UnityCamService/includes/transfrm.h deleted file mode 100644 index 36c2e0d..0000000 --- a/UnityWebcam/UnityCamService/includes/transfrm.h +++ /dev/null @@ -1,304 +0,0 @@ -//------------------------------------------------------------------------------ -// File: Transfrm.h -// -// Desc: DirectShow base classes - defines classes from which simple -// transform codecs may be derived. -// -// Copyright (c) 1992-2001 Microsoft Corporation. All rights reserved. -//------------------------------------------------------------------------------ - - -// It assumes the codec has one input and one output stream, and has no -// interest in memory management, interface negotiation or anything else. -// -// derive your class from this, and supply Transform and the media type/format -// negotiation functions. Implement that class, compile and link and -// you're done. - - -#ifndef __TRANSFRM__ -#define __TRANSFRM__ - -// ====================================================================== -// This is the com object that represents a simple transform filter. It -// supports IBaseFilter, IMediaFilter and two pins through nested interfaces -// ====================================================================== - -class CTransformFilter; - -// ================================================== -// Implements the input pin -// ================================================== - -class CTransformInputPin : public CBaseInputPin -{ - friend class CTransformFilter; - -protected: - CTransformFilter *m_pTransformFilter; - - -public: - - CTransformInputPin( - __in_opt LPCTSTR pObjectName, - __inout CTransformFilter *pTransformFilter, - __inout HRESULT * phr, - __in_opt LPCWSTR pName); -#ifdef UNICODE - CTransformInputPin( - __in_opt LPCSTR pObjectName, - __inout CTransformFilter *pTransformFilter, - __inout HRESULT * phr, - __in_opt LPCWSTR pName); -#endif - - STDMETHODIMP QueryId(__deref_out LPWSTR * Id) - { - return AMGetWideString(L"In", Id); - } - - // Grab and release extra interfaces if required - - HRESULT CheckConnect(IPin *pPin); - HRESULT BreakConnect(); - HRESULT CompleteConnect(IPin *pReceivePin); - - // check that we can support this output type - HRESULT CheckMediaType(const CMediaType* mtIn); - - // set the connection media type - HRESULT SetMediaType(const CMediaType* mt); - - // --- IMemInputPin ----- - - // here's the next block of data from the stream. - // AddRef it yourself if you need to hold it beyond the end - // of this call. - STDMETHODIMP Receive(IMediaSample * pSample); - - // provide EndOfStream that passes straight downstream - // (there is no queued data) - STDMETHODIMP EndOfStream(void); - - // passes it to CTransformFilter::BeginFlush - STDMETHODIMP BeginFlush(void); - - // passes it to CTransformFilter::EndFlush - STDMETHODIMP EndFlush(void); - - STDMETHODIMP NewSegment( - REFERENCE_TIME tStart, - REFERENCE_TIME tStop, - double dRate); - - // Check if it's OK to process samples - virtual HRESULT CheckStreaming(); - - // Media type -public: - CMediaType& CurrentMediaType() { return m_mt; }; - -}; - -// ================================================== -// Implements the output pin -// ================================================== - -class CTransformOutputPin : public CBaseOutputPin -{ - friend class CTransformFilter; - -protected: - CTransformFilter *m_pTransformFilter; - -public: - - // implement IMediaPosition by passing upstream - IUnknown * m_pPosition; - - CTransformOutputPin( - __in_opt LPCTSTR pObjectName, - __inout CTransformFilter *pTransformFilter, - __inout HRESULT * phr, - __in_opt LPCWSTR pName); -#ifdef UNICODE - CTransformOutputPin( - __in_opt LPCSTR pObjectName, - __inout CTransformFilter *pTransformFilter, - __inout HRESULT * phr, - __in_opt LPCWSTR pName); -#endif - ~CTransformOutputPin(); - - // override to expose IMediaPosition - STDMETHODIMP NonDelegatingQueryInterface(REFIID riid, __deref_out void **ppv); - - // --- CBaseOutputPin ------------ - - STDMETHODIMP QueryId(__deref_out LPWSTR * Id) - { - return AMGetWideString(L"Out", Id); - } - - // Grab and release extra interfaces if required - - HRESULT CheckConnect(IPin *pPin); - HRESULT BreakConnect(); - HRESULT CompleteConnect(IPin *pReceivePin); - - // check that we can support this output type - HRESULT CheckMediaType(const CMediaType* mtOut); - - // set the connection media type - HRESULT SetMediaType(const CMediaType *pmt); - - // called from CBaseOutputPin during connection to ask for - // the count and size of buffers we need. - HRESULT DecideBufferSize( - IMemAllocator * pAlloc, - __inout ALLOCATOR_PROPERTIES *pProp); - - // returns the preferred formats for a pin - HRESULT GetMediaType(int iPosition, __inout CMediaType *pMediaType); - - // inherited from IQualityControl via CBasePin - STDMETHODIMP Notify(IBaseFilter * pSender, Quality q); - - // Media type -public: - CMediaType& CurrentMediaType() { return m_mt; }; -}; - - -class AM_NOVTABLE CTransformFilter : public CBaseFilter -{ - -public: - - // map getpin/getpincount for base enum of pins to owner - // override this to return more specialised pin objects - - virtual int GetPinCount(); - virtual CBasePin * GetPin(int n); - STDMETHODIMP FindPin(LPCWSTR Id, __deref_out IPin **ppPin); - - // override state changes to allow derived transform filter - // to control streaming start/stop - STDMETHODIMP Stop(); - STDMETHODIMP Pause(); - -public: - - CTransformFilter(__in_opt LPCTSTR , __inout_opt LPUNKNOWN, REFCLSID clsid); -#ifdef UNICODE - CTransformFilter(__in_opt LPCSTR , __inout_opt LPUNKNOWN, REFCLSID clsid); -#endif - ~CTransformFilter(); - - // ================================================================= - // ----- override these bits --------------------------------------- - // ================================================================= - - // These must be supplied in a derived class - - virtual HRESULT Transform(IMediaSample * pIn, IMediaSample *pOut); - - // check if you can support mtIn - virtual HRESULT CheckInputType(const CMediaType* mtIn) PURE; - - // check if you can support the transform from this input to this output - virtual HRESULT CheckTransform(const CMediaType* mtIn, const CMediaType* mtOut) PURE; - - // this goes in the factory template table to create new instances - // static CCOMObject * CreateInstance(__inout_opt LPUNKNOWN, HRESULT *); - - // call the SetProperties function with appropriate arguments - virtual HRESULT DecideBufferSize( - IMemAllocator * pAllocator, - __inout ALLOCATOR_PROPERTIES *pprop) PURE; - - // override to suggest OUTPUT pin media types - virtual HRESULT GetMediaType(int iPosition, __inout CMediaType *pMediaType) PURE; - - - - // ================================================================= - // ----- Optional Override Methods ----------------------- - // ================================================================= - - // you can also override these if you want to know about streaming - virtual HRESULT StartStreaming(); - virtual HRESULT StopStreaming(); - - // override if you can do anything constructive with quality notifications - virtual HRESULT AlterQuality(Quality q); - - // override this to know when the media type is actually set - virtual HRESULT SetMediaType(PIN_DIRECTION direction,const CMediaType *pmt); - - // chance to grab extra interfaces on connection - virtual HRESULT CheckConnect(PIN_DIRECTION dir,IPin *pPin); - virtual HRESULT BreakConnect(PIN_DIRECTION dir); - virtual HRESULT CompleteConnect(PIN_DIRECTION direction,IPin *pReceivePin); - - // chance to customize the transform process - virtual HRESULT Receive(IMediaSample *pSample); - - // Standard setup for output sample - HRESULT InitializeOutputSample(IMediaSample *pSample, __deref_out IMediaSample **ppOutSample); - - // if you override Receive, you may need to override these three too - virtual HRESULT EndOfStream(void); - virtual HRESULT BeginFlush(void); - virtual HRESULT EndFlush(void); - virtual HRESULT NewSegment( - REFERENCE_TIME tStart, - REFERENCE_TIME tStop, - double dRate); - -#ifdef PERF - // Override to register performance measurement with a less generic string - // You should do this to avoid confusion with other filters - virtual void RegisterPerfId() - {m_idTransform = MSR_REGISTER(TEXT("Transform"));} -#endif // PERF - - -// implementation details - -protected: - -#ifdef PERF - int m_idTransform; // performance measuring id -#endif - BOOL m_bEOSDelivered; // have we sent EndOfStream - BOOL m_bSampleSkipped; // Did we just skip a frame - BOOL m_bQualityChanged; // Have we degraded? - - // critical section protecting filter state. - - CCritSec m_csFilter; - - // critical section stopping state changes (ie Stop) while we're - // processing a sample. - // - // This critical section is held when processing - // events that occur on the receive thread - Receive() and EndOfStream(). - // - // If you want to hold both m_csReceive and m_csFilter then grab - // m_csFilter FIRST - like CTransformFilter::Stop() does. - - CCritSec m_csReceive; - - // these hold our input and output pins - - friend class CTransformInputPin; - friend class CTransformOutputPin; - CTransformInputPin *m_pInput; - CTransformOutputPin *m_pOutput; -}; - -#endif /* __TRANSFRM__ */ - - diff --git a/UnityWebcam/UnityCamService/includes/transip.h b/UnityWebcam/UnityCamService/includes/transip.h deleted file mode 100644 index 45fb4e9..0000000 --- a/UnityWebcam/UnityCamService/includes/transip.h +++ /dev/null @@ -1,250 +0,0 @@ -//------------------------------------------------------------------------------ -// File: TransIP.h -// -// Desc: DirectShow base classes - defines classes from which simple -// Transform-In-Place filters may be derived. -// -// Copyright (c) 1992-2001 Microsoft Corporation. All rights reserved. -//------------------------------------------------------------------------------ - - -// -// The difference between this and Transfrm.h is that Transfrm copies the data. -// -// It assumes the filter has one input and one output stream, and has no -// interest in memory management, interface negotiation or anything else. -// -// Derive your class from this, and supply Transform and the media type/format -// negotiation functions. Implement that class, compile and link and -// you're done. - - -#ifndef __TRANSIP__ -#define __TRANSIP__ - -// ====================================================================== -// This is the com object that represents a simple transform filter. It -// supports IBaseFilter, IMediaFilter and two pins through nested interfaces -// ====================================================================== - -class CTransInPlaceFilter; - -// Several of the pin functions call filter functions to do the work, -// so you can often use the pin classes unaltered, just overriding the -// functions in CTransInPlaceFilter. If that's not enough and you want -// to derive your own pin class, override GetPin in the filter to supply -// your own pin classes to the filter. - -// ================================================== -// Implements the input pin -// ================================================== - -class CTransInPlaceInputPin : public CTransformInputPin -{ - -protected: - CTransInPlaceFilter * const m_pTIPFilter; // our filter - BOOL m_bReadOnly; // incoming stream is read only - -public: - - CTransInPlaceInputPin( - __in_opt LPCTSTR pObjectName, - __inout CTransInPlaceFilter *pFilter, - __inout HRESULT *phr, - __in_opt LPCWSTR pName); - - // --- IMemInputPin ----- - - // Provide an enumerator for media types by getting one from downstream - STDMETHODIMP EnumMediaTypes( __deref_out IEnumMediaTypes **ppEnum ); - - // Say whether media type is acceptable. - HRESULT CheckMediaType(const CMediaType* pmt); - - // Return our upstream allocator - STDMETHODIMP GetAllocator(__deref_out IMemAllocator ** ppAllocator); - - // get told which allocator the upstream output pin is actually - // going to use. - STDMETHODIMP NotifyAllocator(IMemAllocator * pAllocator, - BOOL bReadOnly); - - // Allow the filter to see what allocator we have - // N.B. This does NOT AddRef - __out IMemAllocator * PeekAllocator() const - { return m_pAllocator; } - - // Pass this on downstream if it ever gets called. - STDMETHODIMP GetAllocatorRequirements(__out ALLOCATOR_PROPERTIES *pProps); - - HRESULT CompleteConnect(IPin *pReceivePin); - - inline const BOOL ReadOnly() { return m_bReadOnly ; } - -}; // CTransInPlaceInputPin - -// ================================================== -// Implements the output pin -// ================================================== - -class CTransInPlaceOutputPin : public CTransformOutputPin -{ - -protected: - // m_pFilter points to our CBaseFilter - CTransInPlaceFilter * const m_pTIPFilter; - -public: - - CTransInPlaceOutputPin( - __in_opt LPCTSTR pObjectName, - __inout CTransInPlaceFilter *pFilter, - __inout HRESULT *phr, - __in_opt LPCWSTR pName); - - - // --- CBaseOutputPin ------------ - - // negotiate the allocator and its buffer size/count - // Insists on using our own allocator. (Actually the one upstream of us). - // We don't override this - instead we just agree the default - // then let the upstream filter decide for itself on reconnect - // virtual HRESULT DecideAllocator(IMemInputPin * pPin, IMemAllocator ** pAlloc); - - // Provide a media type enumerator. Get it from upstream. - STDMETHODIMP EnumMediaTypes( __deref_out IEnumMediaTypes **ppEnum ); - - // Say whether media type is acceptable. - HRESULT CheckMediaType(const CMediaType* pmt); - - // This just saves the allocator being used on the output pin - // Also called by input pin's GetAllocator() - void SetAllocator(IMemAllocator * pAllocator); - - __out_opt IMemInputPin * ConnectedIMemInputPin() - { return m_pInputPin; } - - // Allow the filter to see what allocator we have - // N.B. This does NOT AddRef - __out IMemAllocator * PeekAllocator() const - { return m_pAllocator; } - - HRESULT CompleteConnect(IPin *pReceivePin); - -}; // CTransInPlaceOutputPin - - -class AM_NOVTABLE CTransInPlaceFilter : public CTransformFilter -{ - -public: - - // map getpin/getpincount for base enum of pins to owner - // override this to return more specialised pin objects - - virtual CBasePin *GetPin(int n); - -public: - - // Set bModifiesData == false if your derived filter does - // not modify the data samples (for instance it's just copying - // them somewhere else or looking at the timestamps). - - CTransInPlaceFilter(__in_opt LPCTSTR, __inout_opt LPUNKNOWN, REFCLSID clsid, __inout HRESULT *, - bool bModifiesData = true); -#ifdef UNICODE - CTransInPlaceFilter(__in_opt LPCSTR, __inout_opt LPUNKNOWN, REFCLSID clsid, __inout HRESULT *, - bool bModifiesData = true); -#endif - // The following are defined to avoid undefined pure virtuals. - // Even if they are never called, they will give linkage warnings/errors - - // We override EnumMediaTypes to bypass the transform class enumerator - // which would otherwise call this. - HRESULT GetMediaType(int iPosition, __inout CMediaType *pMediaType) - { DbgBreak("CTransInPlaceFilter::GetMediaType should never be called"); - return E_UNEXPECTED; - } - - // This is called when we actually have to provide our own allocator. - HRESULT DecideBufferSize(IMemAllocator*, __inout ALLOCATOR_PROPERTIES *); - - // The functions which call this in CTransform are overridden in this - // class to call CheckInputType with the assumption that the type - // does not change. In Debug builds some calls will be made and - // we just ensure that they do not assert. - HRESULT CheckTransform(const CMediaType *mtIn, const CMediaType *mtOut) - { - return S_OK; - }; - - - // ================================================================= - // ----- You may want to override this ----------------------------- - // ================================================================= - - HRESULT CompleteConnect(PIN_DIRECTION dir,IPin *pReceivePin); - - // chance to customize the transform process - virtual HRESULT Receive(IMediaSample *pSample); - - // ================================================================= - // ----- You MUST override these ----------------------------------- - // ================================================================= - - virtual HRESULT Transform(IMediaSample *pSample) PURE; - - // this goes in the factory template table to create new instances - // static CCOMObject * CreateInstance(LPUNKNOWN, HRESULT *); - - -#ifdef PERF - // Override to register performance measurement with a less generic string - // You should do this to avoid confusion with other filters - virtual void RegisterPerfId() - {m_idTransInPlace = MSR_REGISTER(TEXT("TransInPlace"));} -#endif // PERF - - -// implementation details - -protected: - - __out_opt IMediaSample * CTransInPlaceFilter::Copy(IMediaSample *pSource); - -#ifdef PERF - int m_idTransInPlace; // performance measuring id -#endif // PERF - bool m_bModifiesData; // Does this filter change the data? - - // these hold our input and output pins - - friend class CTransInPlaceInputPin; - friend class CTransInPlaceOutputPin; - - __out CTransInPlaceInputPin *InputPin() const - { - return (CTransInPlaceInputPin *)m_pInput; - }; - __out CTransInPlaceOutputPin *OutputPin() const - { - return (CTransInPlaceOutputPin *)m_pOutput; - }; - - // Helper to see if the input and output types match - BOOL TypesMatch() - { - return InputPin()->CurrentMediaType() == - OutputPin()->CurrentMediaType(); - } - - // Are the input and output allocators different? - BOOL UsingDifferentAllocators() const - { - return InputPin()->PeekAllocator() != OutputPin()->PeekAllocator(); - } -}; // CTransInPlaceFilter - -#endif /* __TRANSIP__ */ - diff --git a/UnityWebcam/UnityCamService/includes/videoctl.h b/UnityWebcam/UnityCamService/includes/videoctl.h deleted file mode 100644 index 440d81a..0000000 --- a/UnityWebcam/UnityCamService/includes/videoctl.h +++ /dev/null @@ -1,168 +0,0 @@ -//------------------------------------------------------------------------------ -// File: VideoCtl.h -// -// Desc: DirectShow base classes. -// -// Copyright (c) 1992-2001 Microsoft Corporation. All rights reserved. -//------------------------------------------------------------------------------ - - -#ifndef __VIDEOCTL__ -#define __VIDEOCTL__ - -// These help with property page implementations. The first can be used to -// load any string from a resource file. The buffer to load into is passed -// as an input parameter. The same buffer is the return value if the string -// was found otherwise it returns TEXT(""). The GetDialogSize is passed the -// resource ID of a dialog box and returns the size of it in screen pixels - -#define STR_MAX_LENGTH 256 -LPTSTR WINAPI StringFromResource(__out_ecount(STR_MAX_LENGTH) LPTSTR pBuffer, int iResourceID); - -#ifdef UNICODE -#define WideStringFromResource StringFromResource -LPSTR WINAPI StringFromResource(__out_ecount(STR_MAX_LENGTH) LPSTR pBuffer, int iResourceID); -#else -LPWSTR WINAPI WideStringFromResource(__out_ecount(STR_MAX_LENGTH) LPWSTR pBuffer, int iResourceID); -#endif - - -BOOL WINAPI GetDialogSize(int iResourceID, // Dialog box resource identifier - DLGPROC pDlgProc, // Pointer to dialog procedure - LPARAM lParam, // Any user data wanted in pDlgProc - __out SIZE *pResult);// Returns the size of dialog box - -// Class that aggregates an IDirectDraw interface - -class CAggDirectDraw : public IDirectDraw, public CUnknown -{ -protected: - - LPDIRECTDRAW m_pDirectDraw; - -public: - - DECLARE_IUNKNOWN - STDMETHODIMP NonDelegatingQueryInterface(REFIID riid,__deref_out void **ppv); - - // Constructor and destructor - - CAggDirectDraw(__in_opt LPCTSTR pName,__inout_opt LPUNKNOWN pUnk) : - CUnknown(pName,pUnk), - m_pDirectDraw(NULL) { }; - - virtual CAggDirectDraw::~CAggDirectDraw() { }; - - // Set the object we should be aggregating - void SetDirectDraw(__inout LPDIRECTDRAW pDirectDraw) { - m_pDirectDraw = pDirectDraw; - } - - // IDirectDraw methods - - STDMETHODIMP Compact(); - STDMETHODIMP CreateClipper(DWORD dwFlags,__deref_out LPDIRECTDRAWCLIPPER *lplpDDClipper,__inout_opt IUnknown *pUnkOuter); - STDMETHODIMP CreatePalette(DWORD dwFlags,__in LPPALETTEENTRY lpColorTable,__deref_out LPDIRECTDRAWPALETTE *lplpDDPalette,__inout_opt IUnknown *pUnkOuter); - STDMETHODIMP CreateSurface(__in LPDDSURFACEDESC lpDDSurfaceDesc,__deref_out LPDIRECTDRAWSURFACE *lplpDDSurface,__inout_opt IUnknown *pUnkOuter); - STDMETHODIMP DuplicateSurface(__in LPDIRECTDRAWSURFACE lpDDSurface,__deref_out LPDIRECTDRAWSURFACE *lplpDupDDSurface); - STDMETHODIMP EnumDisplayModes(DWORD dwSurfaceDescCount,__in LPDDSURFACEDESC lplpDDSurfaceDescList,__in LPVOID lpContext,__in LPDDENUMMODESCALLBACK lpEnumCallback); - STDMETHODIMP EnumSurfaces(DWORD dwFlags,__in LPDDSURFACEDESC lpDDSD,__in LPVOID lpContext,__in LPDDENUMSURFACESCALLBACK lpEnumCallback); - STDMETHODIMP FlipToGDISurface(); - STDMETHODIMP GetCaps(__out LPDDCAPS lpDDDriverCaps,__out LPDDCAPS lpDDHELCaps); - STDMETHODIMP GetDisplayMode(__out LPDDSURFACEDESC lpDDSurfaceDesc); - STDMETHODIMP GetFourCCCodes(__inout LPDWORD lpNumCodes,__out_ecount(*lpNumCodes) LPDWORD lpCodes); - STDMETHODIMP GetGDISurface(__deref_out LPDIRECTDRAWSURFACE *lplpGDIDDSurface); - STDMETHODIMP GetMonitorFrequency(__out LPDWORD lpdwFrequency); - STDMETHODIMP GetScanLine(__out LPDWORD lpdwScanLine); - STDMETHODIMP GetVerticalBlankStatus(__out LPBOOL lpblsInVB); - STDMETHODIMP Initialize(__in GUID *lpGUID); - STDMETHODIMP RestoreDisplayMode(); - STDMETHODIMP SetCooperativeLevel(HWND hWnd,DWORD dwFlags); - STDMETHODIMP SetDisplayMode(DWORD dwWidth,DWORD dwHeight,DWORD dwBpp); - STDMETHODIMP WaitForVerticalBlank(DWORD dwFlags,HANDLE hEvent); -}; - - -// Class that aggregates an IDirectDrawSurface interface - -class CAggDrawSurface : public IDirectDrawSurface, public CUnknown -{ -protected: - - LPDIRECTDRAWSURFACE m_pDirectDrawSurface; - -public: - - DECLARE_IUNKNOWN - STDMETHODIMP NonDelegatingQueryInterface(REFIID riid,__deref_out void **ppv); - - // Constructor and destructor - - CAggDrawSurface(__in_opt LPCTSTR pName,__inout_opt LPUNKNOWN pUnk) : - CUnknown(pName,pUnk), - m_pDirectDrawSurface(NULL) { }; - - virtual ~CAggDrawSurface() { }; - - // Set the object we should be aggregating - void SetDirectDrawSurface(__inout LPDIRECTDRAWSURFACE pDirectDrawSurface) { - m_pDirectDrawSurface = pDirectDrawSurface; - } - - // IDirectDrawSurface methods - - STDMETHODIMP AddAttachedSurface(__in LPDIRECTDRAWSURFACE lpDDSAttachedSurface); - STDMETHODIMP AddOverlayDirtyRect(__in LPRECT lpRect); - STDMETHODIMP Blt(__in LPRECT lpDestRect,__in LPDIRECTDRAWSURFACE lpDDSrcSurface,__in LPRECT lpSrcRect,DWORD dwFlags,__in LPDDBLTFX lpDDBltFx); - STDMETHODIMP BltBatch(__in_ecount(dwCount) LPDDBLTBATCH lpDDBltBatch,DWORD dwCount,DWORD dwFlags); - STDMETHODIMP BltFast(DWORD dwX,DWORD dwY,__in LPDIRECTDRAWSURFACE lpDDSrcSurface,__in LPRECT lpSrcRect,DWORD dwTrans); - STDMETHODIMP DeleteAttachedSurface(DWORD dwFlags,__in LPDIRECTDRAWSURFACE lpDDSAttachedSurface); - STDMETHODIMP EnumAttachedSurfaces(__in LPVOID lpContext,__in LPDDENUMSURFACESCALLBACK lpEnumSurfacesCallback); - STDMETHODIMP EnumOverlayZOrders(DWORD dwFlags,__in LPVOID lpContext,__in LPDDENUMSURFACESCALLBACK lpfnCallback); - STDMETHODIMP Flip(__in LPDIRECTDRAWSURFACE lpDDSurfaceTargetOverride,DWORD dwFlags); - STDMETHODIMP GetAttachedSurface(__in LPDDSCAPS lpDDSCaps,__deref_out LPDIRECTDRAWSURFACE *lplpDDAttachedSurface); - STDMETHODIMP GetBltStatus(DWORD dwFlags); - STDMETHODIMP GetCaps(__out LPDDSCAPS lpDDSCaps); - STDMETHODIMP GetClipper(__deref_out LPDIRECTDRAWCLIPPER *lplpDDClipper); - STDMETHODIMP GetColorKey(DWORD dwFlags,__out LPDDCOLORKEY lpDDColorKey); - STDMETHODIMP GetDC(__out HDC *lphDC); - STDMETHODIMP GetFlipStatus(DWORD dwFlags); - STDMETHODIMP GetOverlayPosition(__out LPLONG lpdwX,__out LPLONG lpdwY); - STDMETHODIMP GetPalette(__deref_out LPDIRECTDRAWPALETTE *lplpDDPalette); - STDMETHODIMP GetPixelFormat(__out LPDDPIXELFORMAT lpDDPixelFormat); - STDMETHODIMP GetSurfaceDesc(__out LPDDSURFACEDESC lpDDSurfaceDesc); - STDMETHODIMP Initialize(__in LPDIRECTDRAW lpDD,__in LPDDSURFACEDESC lpDDSurfaceDesc); - STDMETHODIMP IsLost(); - STDMETHODIMP Lock(__in LPRECT lpDestRect,__inout LPDDSURFACEDESC lpDDSurfaceDesc,DWORD dwFlags,HANDLE hEvent); - STDMETHODIMP ReleaseDC(HDC hDC); - STDMETHODIMP Restore(); - STDMETHODIMP SetClipper(__in LPDIRECTDRAWCLIPPER lpDDClipper); - STDMETHODIMP SetColorKey(DWORD dwFlags,__in LPDDCOLORKEY lpDDColorKey); - STDMETHODIMP SetOverlayPosition(LONG dwX,LONG dwY); - STDMETHODIMP SetPalette(__in LPDIRECTDRAWPALETTE lpDDPalette); - STDMETHODIMP Unlock(__in LPVOID lpSurfaceData); - STDMETHODIMP UpdateOverlay(__in LPRECT lpSrcRect,__in LPDIRECTDRAWSURFACE lpDDDestSurface,__in LPRECT lpDestRect,DWORD dwFlags,__in LPDDOVERLAYFX lpDDOverlayFX); - STDMETHODIMP UpdateOverlayDisplay(DWORD dwFlags); - STDMETHODIMP UpdateOverlayZOrder(DWORD dwFlags,__in LPDIRECTDRAWSURFACE lpDDSReference); -}; - - -class CLoadDirectDraw -{ - LPDIRECTDRAW m_pDirectDraw; // The DirectDraw driver instance - HINSTANCE m_hDirectDraw; // Handle to the loaded library - -public: - - CLoadDirectDraw(); - ~CLoadDirectDraw(); - - HRESULT LoadDirectDraw(__in LPSTR szDevice); - void ReleaseDirectDraw(); - HRESULT IsDirectDrawLoaded(); - LPDIRECTDRAW GetDirectDraw(); - BOOL IsDirectDrawVersion1(); -}; - -#endif // __VIDEOCTL__ - diff --git a/UnityWebcam/UnityCamService/includes/vtrans.h b/UnityWebcam/UnityCamService/includes/vtrans.h deleted file mode 100644 index 7122392..0000000 --- a/UnityWebcam/UnityCamService/includes/vtrans.h +++ /dev/null @@ -1,143 +0,0 @@ -//------------------------------------------------------------------------------ -// File: VTrans.h -// -// Desc: DirectShow base classes - defines a video transform class. -// -// Copyright (c) 1992-2001 Microsoft Corporation. All rights reserved. -//------------------------------------------------------------------------------ - - -// This class is derived from CTransformFilter, but is specialised to handle -// the requirements of video quality control by frame dropping. -// This is a non-in-place transform, (i.e. it copies the data) such as a decoder. - -class CVideoTransformFilter : public CTransformFilter -{ - public: - - CVideoTransformFilter(__in_opt LPCTSTR, __inout_opt LPUNKNOWN, REFCLSID clsid); - ~CVideoTransformFilter(); - HRESULT EndFlush(); - - // ================================================================= - // ----- override these bits --------------------------------------- - // ================================================================= - // The following methods are in CTransformFilter which is inherited. - // They are mentioned here for completeness - // - // These MUST be supplied in a derived class - // - // NOTE: - // virtual HRESULT Transform(IMediaSample * pIn, IMediaSample *pOut); - // virtual HRESULT CheckInputType(const CMediaType* mtIn) PURE; - // virtual HRESULT CheckTransform - // (const CMediaType* mtIn, const CMediaType* mtOut) PURE; - // static CCOMObject * CreateInstance(LPUNKNOWN, HRESULT *); - // virtual HRESULT DecideBufferSize - // (IMemAllocator * pAllocator, ALLOCATOR_PROPERTIES *pprop) PURE; - // virtual HRESULT GetMediaType(int iPosition, CMediaType *pMediaType) PURE; - // - // These MAY also be overridden - // - // virtual HRESULT StopStreaming(); - // virtual HRESULT SetMediaType(PIN_DIRECTION direction,const CMediaType *pmt); - // virtual HRESULT CheckConnect(PIN_DIRECTION dir,IPin *pPin); - // virtual HRESULT BreakConnect(PIN_DIRECTION dir); - // virtual HRESULT CompleteConnect(PIN_DIRECTION direction,IPin *pReceivePin); - // virtual HRESULT EndOfStream(void); - // virtual HRESULT BeginFlush(void); - // virtual HRESULT EndFlush(void); - // virtual HRESULT NewSegment - // (REFERENCE_TIME tStart,REFERENCE_TIME tStop,double dRate); -#ifdef PERF - - // If you override this - ensure that you register all these ids - // as well as any of your own, - virtual void RegisterPerfId() { - m_idSkip = MSR_REGISTER(TEXT("Video Transform Skip frame")); - m_idFrameType = MSR_REGISTER(TEXT("Video transform frame type")); - m_idLate = MSR_REGISTER(TEXT("Video Transform Lateness")); - m_idTimeTillKey = MSR_REGISTER(TEXT("Video Transform Estd. time to next key")); - CTransformFilter::RegisterPerfId(); - } -#endif - - protected: - - // =========== QUALITY MANAGEMENT IMPLEMENTATION ======================== - // Frames are assumed to come in three types: - // Type 1: an AVI key frame or an MPEG I frame. - // This frame can be decoded with no history. - // Dropping this frame means that no further frame can be decoded - // until the next type 1 frame. - // Type 1 frames are sync points. - // Type 2: an AVI non-key frame or an MPEG P frame. - // This frame cannot be decoded unless the previous type 1 frame was - // decoded and all type 2 frames since have been decoded. - // Dropping this frame means that no further frame can be decoded - // until the next type 1 frame. - // Type 3: An MPEG B frame. - // This frame cannot be decoded unless the previous type 1 or 2 frame - // has been decoded AND the subsequent type 1 or 2 frame has also - // been decoded. (This requires decoding the frames out of sequence). - // Dropping this frame affects no other frames. This implementation - // does not allow for these. All non-sync-point frames are treated - // as being type 2. - // - // The spacing of frames of type 1 in a file is not guaranteed. There MUST - // be a type 1 frame at (well, near) the start of the file in order to start - // decoding at all. After that there could be one every half second or so, - // there could be one at the start of each scene (aka "cut", "shot") or - // there could be no more at all. - // If there is only a single type 1 frame then NO FRAMES CAN BE DROPPED - // without losing all the rest of the movie. There is no way to tell whether - // this is the case, so we find that we are in the gambling business. - // To try to improve the odds, we record the greatest interval between type 1s - // that we have seen and we bet on things being no worse than this in the - // future. - - // You can tell if it's a type 1 frame by calling IsSyncPoint(). - // there is no architected way to test for a type 3, so you should override - // the quality management here if you have B-frames. - - int m_nKeyFramePeriod; // the largest observed interval between type 1 frames - // 1 means every frame is type 1, 2 means every other. - - int m_nFramesSinceKeyFrame; // Used to count frames since the last type 1. - // becomes the new m_nKeyFramePeriod if greater. - - BOOL m_bSkipping; // we are skipping to the next type 1 frame - -#ifdef PERF - int m_idFrameType; // MSR id Frame type. 1=Key, 2="non-key" - int m_idSkip; // MSR id skipping - int m_idLate; // MSR id lateness - int m_idTimeTillKey; // MSR id for guessed time till next key frame. -#endif - - virtual HRESULT StartStreaming(); - - HRESULT AbortPlayback(HRESULT hr); // if something bad happens - - HRESULT Receive(IMediaSample *pSample); - - HRESULT AlterQuality(Quality q); - - BOOL ShouldSkipFrame(IMediaSample * pIn); - - int m_itrLate; // lateness from last Quality message - // (this overflows at 214 secs late). - int m_tDecodeStart; // timeGetTime when decode started. - int m_itrAvgDecode; // Average decode time in reference units. - - BOOL m_bNoSkip; // debug - no skipping. - - // We send an EC_QUALITY_CHANGE notification to the app if we have to degrade. - // We send one when we start degrading, not one for every frame, this means - // we track whether we've sent one yet. - BOOL m_bQualityChanged; - - // When non-zero, don't pass anything to renderer until next keyframe - // If there are few keys, give up and eventually draw something - int m_nWaitForKey; -}; diff --git a/UnityWebcam/UnityCamService/includes/winctrl.h b/UnityWebcam/UnityCamService/includes/winctrl.h deleted file mode 100644 index f18ba82..0000000 --- a/UnityWebcam/UnityCamService/includes/winctrl.h +++ /dev/null @@ -1,224 +0,0 @@ -//------------------------------------------------------------------------------ -// File: WinCtrl.h -// -// Desc: DirectShow base classes - defines classes for video control -// interfaces. -// -// Copyright (c) 1992-2001 Microsoft Corporation. All rights reserved. -//------------------------------------------------------------------------------ - - -#ifndef __WINCTRL__ -#define __WINCTRL__ - -#define ABSOL(x) (x < 0 ? -x : x) -#define NEGAT(x) (x > 0 ? -x : x) - -// Helper -BOOL WINAPI PossiblyEatMessage(HWND hwnd, UINT uMsg, WPARAM wParam, LPARAM lParam); - -class CBaseControlWindow : public CBaseVideoWindow, public CBaseWindow -{ -protected: - - CBaseFilter *m_pFilter; // Pointer to owning media filter - CBasePin *m_pPin; // Controls media types for connection - CCritSec *m_pInterfaceLock; // Externally defined critical section - COLORREF m_BorderColour; // Current window border colour - BOOL m_bAutoShow; // What happens when the state changes - HWND m_hwndOwner; // Owner window that we optionally have - HWND m_hwndDrain; // HWND to post any messages received - BOOL m_bCursorHidden; // Should we hide the window cursor - -public: - - // Internal methods for other objects to get information out - - HRESULT DoSetWindowStyle(long Style,long WindowLong); - HRESULT DoGetWindowStyle(__out long *pStyle,long WindowLong); - BOOL IsAutoShowEnabled() { return m_bAutoShow; }; - COLORREF GetBorderColour() { return m_BorderColour; }; - HWND GetOwnerWindow() { return m_hwndOwner; }; - BOOL IsCursorHidden() { return m_bCursorHidden; }; - - inline BOOL PossiblyEatMessage(UINT uMsg, WPARAM wParam, LPARAM lParam) - { - return ::PossiblyEatMessage(m_hwndDrain, uMsg, wParam, lParam); - } - - // Derived classes must call this to set the pin the filter is using - // We don't have the pin passed in to the constructor (as we do with - // the CBaseFilter object) because filters typically create the - // pins dynamically when requested in CBaseFilter::GetPin. This can - // not be called from our constructor because is is a virtual method - - void SetControlWindowPin(CBasePin *pPin) { - m_pPin = pPin; - } - -public: - - CBaseControlWindow(__inout CBaseFilter *pFilter, // Owning media filter - __in CCritSec *pInterfaceLock, // Locking object - __in_opt LPCTSTR pName, // Object description - __inout_opt LPUNKNOWN pUnk, // Normal COM ownership - __inout HRESULT *phr); // OLE return code - - // These are the properties we support - - STDMETHODIMP put_Caption(__in BSTR strCaption); - STDMETHODIMP get_Caption(__out BSTR *pstrCaption); - STDMETHODIMP put_AutoShow(long AutoShow); - STDMETHODIMP get_AutoShow(__out long *AutoShow); - STDMETHODIMP put_WindowStyle(long WindowStyle); - STDMETHODIMP get_WindowStyle(__out long *pWindowStyle); - STDMETHODIMP put_WindowStyleEx(long WindowStyleEx); - STDMETHODIMP get_WindowStyleEx(__out long *pWindowStyleEx); - STDMETHODIMP put_WindowState(long WindowState); - STDMETHODIMP get_WindowState(__out long *pWindowState); - STDMETHODIMP put_BackgroundPalette(long BackgroundPalette); - STDMETHODIMP get_BackgroundPalette(__out long *pBackgroundPalette); - STDMETHODIMP put_Visible(long Visible); - STDMETHODIMP get_Visible(__out long *pVisible); - STDMETHODIMP put_Left(long Left); - STDMETHODIMP get_Left(__out long *pLeft); - STDMETHODIMP put_Width(long Width); - STDMETHODIMP get_Width(__out long *pWidth); - STDMETHODIMP put_Top(long Top); - STDMETHODIMP get_Top(__out long *pTop); - STDMETHODIMP put_Height(long Height); - STDMETHODIMP get_Height(__out long *pHeight); - STDMETHODIMP put_Owner(OAHWND Owner); - STDMETHODIMP get_Owner(__out OAHWND *Owner); - STDMETHODIMP put_MessageDrain(OAHWND Drain); - STDMETHODIMP get_MessageDrain(__out OAHWND *Drain); - STDMETHODIMP get_BorderColor(__out long *Color); - STDMETHODIMP put_BorderColor(long Color); - STDMETHODIMP get_FullScreenMode(__out long *FullScreenMode); - STDMETHODIMP put_FullScreenMode(long FullScreenMode); - - // And these are the methods - - STDMETHODIMP SetWindowForeground(long Focus); - STDMETHODIMP NotifyOwnerMessage(OAHWND hwnd,long uMsg,LONG_PTR wParam,LONG_PTR lParam); - STDMETHODIMP GetMinIdealImageSize(__out long *pWidth,__out long *pHeight); - STDMETHODIMP GetMaxIdealImageSize(__out long *pWidth,__out long *pHeight); - STDMETHODIMP SetWindowPosition(long Left,long Top,long Width,long Height); - STDMETHODIMP GetWindowPosition(__out long *pLeft,__out long *pTop,__out long *pWidth,__out long *pHeight); - STDMETHODIMP GetRestorePosition(__out long *pLeft,__out long *pTop,__out long *pWidth,__out long *pHeight); - STDMETHODIMP HideCursor(long HideCursor); - STDMETHODIMP IsCursorHidden(__out long *CursorHidden); -}; - -// This class implements the IBasicVideo interface - -class CBaseControlVideo : public CBaseBasicVideo -{ -protected: - - CBaseFilter *m_pFilter; // Pointer to owning media filter - CBasePin *m_pPin; // Controls media types for connection - CCritSec *m_pInterfaceLock; // Externally defined critical section - -public: - - // Derived classes must provide these for the implementation - - virtual HRESULT IsDefaultTargetRect() PURE; - virtual HRESULT SetDefaultTargetRect() PURE; - virtual HRESULT SetTargetRect(RECT *pTargetRect) PURE; - virtual HRESULT GetTargetRect(RECT *pTargetRect) PURE; - virtual HRESULT IsDefaultSourceRect() PURE; - virtual HRESULT SetDefaultSourceRect() PURE; - virtual HRESULT SetSourceRect(RECT *pSourceRect) PURE; - virtual HRESULT GetSourceRect(RECT *pSourceRect) PURE; - virtual HRESULT GetStaticImage(__inout long *pBufferSize,__out_bcount_part(*pBufferSize, *pBufferSize) long *pDIBImage) PURE; - - // Derived classes must override this to return a VIDEOINFO representing - // the video format. We cannot call IPin ConnectionMediaType to get this - // format because various filters dynamically change the type when using - // DirectDraw such that the format shows the position of the logical - // bitmap in a frame buffer surface, so the size might be returned as - // 1024x768 pixels instead of 320x240 which is the real video dimensions - - __out virtual VIDEOINFOHEADER *GetVideoFormat() PURE; - - // Helper functions for creating memory renderings of a DIB image - - HRESULT GetImageSize(__in VIDEOINFOHEADER *pVideoInfo, - __out LONG *pBufferSize, - __in RECT *pSourceRect); - - HRESULT CopyImage(IMediaSample *pMediaSample, - __in VIDEOINFOHEADER *pVideoInfo, - __inout LONG *pBufferSize, - __out_bcount_part(*pBufferSize, *pBufferSize) BYTE *pVideoImage, - __in RECT *pSourceRect); - - // Override this if you want notifying when the rectangles change - virtual HRESULT OnUpdateRectangles() { return NOERROR; }; - virtual HRESULT OnVideoSizeChange(); - - // Derived classes must call this to set the pin the filter is using - // We don't have the pin passed in to the constructor (as we do with - // the CBaseFilter object) because filters typically create the - // pins dynamically when requested in CBaseFilter::GetPin. This can - // not be called from our constructor because is is a virtual method - - void SetControlVideoPin(__inout CBasePin *pPin) { - m_pPin = pPin; - } - - // Helper methods for checking rectangles - virtual HRESULT CheckSourceRect(__in RECT *pSourceRect); - virtual HRESULT CheckTargetRect(__in RECT *pTargetRect); - -public: - - CBaseControlVideo(__inout CBaseFilter *pFilter, // Owning media filter - __in CCritSec *pInterfaceLock, // Serialise interface - __in_opt LPCTSTR pName, // Object description - __inout_opt LPUNKNOWN pUnk, // Normal COM ownership - __inout HRESULT *phr); // OLE return code - - // These are the properties we support - - STDMETHODIMP get_AvgTimePerFrame(__out REFTIME *pAvgTimePerFrame); - STDMETHODIMP get_BitRate(__out long *pBitRate); - STDMETHODIMP get_BitErrorRate(__out long *pBitErrorRate); - STDMETHODIMP get_VideoWidth(__out long *pVideoWidth); - STDMETHODIMP get_VideoHeight(__out long *pVideoHeight); - STDMETHODIMP put_SourceLeft(long SourceLeft); - STDMETHODIMP get_SourceLeft(__out long *pSourceLeft); - STDMETHODIMP put_SourceWidth(long SourceWidth); - STDMETHODIMP get_SourceWidth(__out long *pSourceWidth); - STDMETHODIMP put_SourceTop(long SourceTop); - STDMETHODIMP get_SourceTop(__out long *pSourceTop); - STDMETHODIMP put_SourceHeight(long SourceHeight); - STDMETHODIMP get_SourceHeight(__out long *pSourceHeight); - STDMETHODIMP put_DestinationLeft(long DestinationLeft); - STDMETHODIMP get_DestinationLeft(__out long *pDestinationLeft); - STDMETHODIMP put_DestinationWidth(long DestinationWidth); - STDMETHODIMP get_DestinationWidth(__out long *pDestinationWidth); - STDMETHODIMP put_DestinationTop(long DestinationTop); - STDMETHODIMP get_DestinationTop(__out long *pDestinationTop); - STDMETHODIMP put_DestinationHeight(long DestinationHeight); - STDMETHODIMP get_DestinationHeight(__out long *pDestinationHeight); - - // And these are the methods - - STDMETHODIMP GetVideoSize(__out long *pWidth,__out long *pHeight); - STDMETHODIMP SetSourcePosition(long Left,long Top,long Width,long Height); - STDMETHODIMP GetSourcePosition(__out long *pLeft,__out long *pTop,__out long *pWidth,__out long *pHeight); - STDMETHODIMP GetVideoPaletteEntries(long StartIndex,long Entries,__out long *pRetrieved,__out_ecount_part(Entries, *pRetrieved) long *pPalette); - STDMETHODIMP SetDefaultSourcePosition(); - STDMETHODIMP IsUsingDefaultSource(); - STDMETHODIMP SetDestinationPosition(long Left,long Top,long Width,long Height); - STDMETHODIMP GetDestinationPosition(__out long *pLeft,__out long *pTop,__out long *pWidth,__out long *pHeight); - STDMETHODIMP SetDefaultDestinationPosition(); - STDMETHODIMP IsUsingDefaultDestination(); - STDMETHODIMP GetCurrentImage(__inout long *pBufferSize,__out_bcount_part(*pBufferSize, *pBufferSize) long *pVideoImage); -}; - -#endif // __WINCTRL__ - diff --git a/UnityWebcam/UnityCamService/includes/winutil.h b/UnityWebcam/UnityCamService/includes/winutil.h deleted file mode 100644 index 641b53a..0000000 --- a/UnityWebcam/UnityCamService/includes/winutil.h +++ /dev/null @@ -1,419 +0,0 @@ -//------------------------------------------------------------------------------ -// File: WinUtil.h -// -// Desc: DirectShow base classes - defines generic handler classes. -// -// Copyright (c) 1992-2001 Microsoft Corporation. All rights reserved. -//------------------------------------------------------------------------------ - - -// Make sure that you call PrepareWindow to initialise the window after -// the object has been constructed. It is a separate method so that -// derived classes can override useful methods like MessageLoop. Also -// any derived class must call DoneWithWindow in its destructor. If it -// doesn't a message may be retrieved and call a derived class member -// function while a thread is executing the base class destructor code - -#ifndef __WINUTIL__ -#define __WINUTIL__ - -const int DEFWIDTH = 320; // Initial window width -const int DEFHEIGHT = 240; // Initial window height -const int CAPTION = 256; // Maximum length of caption -const int TIMELENGTH = 50; // Maximum length of times -const int PROFILESTR = 128; // Normal profile string -const WORD PALVERSION = 0x300; // GDI palette version -const LONG PALETTE_VERSION = (LONG) 1; // Initial palette version -const COLORREF VIDEO_COLOUR = 0; // Defaults to black background -const HANDLE hMEMORY = (HANDLE) (-1); // Says to open as memory file - -#define WIDTH(x) ((*(x)).right - (*(x)).left) -#define HEIGHT(x) ((*(x)).bottom - (*(x)).top) -#define SHOWSTAGE TEXT("WM_SHOWSTAGE") -#define SHOWSTAGETOP TEXT("WM_SHOWSTAGETOP") -#define REALIZEPALETTE TEXT("WM_REALIZEPALETTE") - -class AM_NOVTABLE CBaseWindow -{ -protected: - - HINSTANCE m_hInstance; // Global module instance handle - HWND m_hwnd; // Handle for our window - HDC m_hdc; // Device context for the window - LONG m_Width; // Client window width - LONG m_Height; // Client window height - BOOL m_bActivated; // Has the window been activated - LPTSTR m_pClassName; // Static string holding class name - DWORD m_ClassStyles; // Passed in to our constructor - DWORD m_WindowStyles; // Likewise the initial window styles - DWORD m_WindowStylesEx; // And the extended window styles - UINT m_ShowStageMessage; // Have the window shown with focus - UINT m_ShowStageTop; // Makes the window WS_EX_TOPMOST - UINT m_RealizePalette; // Makes us realize our new palette - HDC m_MemoryDC; // Used for fast BitBlt operations - HPALETTE m_hPalette; // Handle to any palette we may have - BYTE m_bNoRealize; // Don't realize palette now - BYTE m_bBackground; // Should we realise in background - BYTE m_bRealizing; // already realizing the palette - CCritSec m_WindowLock; // Serialise window object access - BOOL m_bDoGetDC; // Should this window get a DC - bool m_bDoPostToDestroy; // Use PostMessage to destroy - CCritSec m_PaletteLock; // This lock protects m_hPalette. - // It should be held anytime the - // program use the value of m_hPalette. - - // Maps windows message procedure into C++ methods - friend LRESULT CALLBACK WndProc(HWND hwnd, // Window handle - UINT uMsg, // Message ID - WPARAM wParam, // First parameter - LPARAM lParam); // Other parameter - - virtual LRESULT OnPaletteChange(HWND hwnd, UINT Message); - -public: - - CBaseWindow(BOOL bDoGetDC = TRUE, bool bPostToDestroy = false); - -#ifdef DEBUG - virtual ~CBaseWindow(); -#endif - - virtual HRESULT DoneWithWindow(); - virtual HRESULT PrepareWindow(); - virtual HRESULT InactivateWindow(); - virtual HRESULT ActivateWindow(); - virtual BOOL OnSize(LONG Width, LONG Height); - virtual BOOL OnClose(); - virtual RECT GetDefaultRect(); - virtual HRESULT UninitialiseWindow(); - virtual HRESULT InitialiseWindow(HWND hwnd); - - HRESULT CompleteConnect(); - HRESULT DoCreateWindow(); - - HRESULT PerformanceAlignWindow(); - HRESULT DoShowWindow(LONG ShowCmd); - void PaintWindow(BOOL bErase); - void DoSetWindowForeground(BOOL bFocus); - virtual HRESULT SetPalette(HPALETTE hPalette); - void SetRealize(BOOL bRealize) - { - m_bNoRealize = !bRealize; - } - - // Jump over to the window thread to set the current palette - HRESULT SetPalette(); - void UnsetPalette(void); - virtual HRESULT DoRealisePalette(BOOL bForceBackground = FALSE); - - void LockPaletteLock(); - void UnlockPaletteLock(); - - virtual BOOL PossiblyEatMessage(UINT uMsg, WPARAM wParam, LPARAM lParam) - { return FALSE; }; - - // Access our window information - - bool WindowExists(); - LONG GetWindowWidth(); - LONG GetWindowHeight(); - HWND GetWindowHWND(); - HDC GetMemoryHDC(); - HDC GetWindowHDC(); - - #ifdef DEBUG - HPALETTE GetPalette(); - #endif // DEBUG - - // This is the window procedure the derived object should override - - virtual LRESULT OnReceiveMessage(HWND hwnd, // Window handle - UINT uMsg, // Message ID - WPARAM wParam, // First parameter - LPARAM lParam); // Other parameter - - // Must be overriden to return class and window styles - - virtual LPTSTR GetClassWindowStyles( - __out DWORD *pClassStyles, // Class styles - __out DWORD *pWindowStyles, // Window styles - __out DWORD *pWindowStylesEx) PURE; // Extended styles -}; - - -// This helper class is entirely subservient to the owning CBaseWindow object -// All this object does is to split out the actual drawing operation from the -// main object (because it was becoming too large). We have a number of entry -// points to set things like the draw device contexts, to implement the actual -// drawing and to set the destination rectangle in the client window. We have -// no critical section locking in this class because we are used exclusively -// by the owning window object which looks after serialising calls into us - -// If you want to use this class make sure you call NotifyAllocator once the -// allocate has been agreed, also call NotifyMediaType with a pointer to a -// NON stack based CMediaType once that has been set (we keep a pointer to -// the original rather than taking a copy). When the palette changes call -// IncrementPaletteVersion (easiest thing to do is to also call this method -// in the SetMediaType method most filters implement). Finally before you -// start rendering anything call SetDrawContext so that we can get the HDCs -// for drawing from the CBaseWindow object we are given during construction - -class CDrawImage -{ -protected: - - CBaseWindow *m_pBaseWindow; // Owning video window object - CRefTime m_StartSample; // Start time for the current sample - CRefTime m_EndSample; // And likewise it's end sample time - HDC m_hdc; // Main window device context - HDC m_MemoryDC; // Offscreen draw device context - RECT m_TargetRect; // Target destination rectangle - RECT m_SourceRect; // Source image rectangle - BOOL m_bStretch; // Do we have to stretch the images - BOOL m_bUsingImageAllocator; // Are the samples shared DIBSECTIONs - CMediaType *m_pMediaType; // Pointer to the current format - int m_perfidRenderTime; // Time taken to render an image - LONG m_PaletteVersion; // Current palette version cookie - - // Draw the video images in the window - - void SlowRender(IMediaSample *pMediaSample); - void FastRender(IMediaSample *pMediaSample); - void DisplaySampleTimes(IMediaSample *pSample); - void UpdateColourTable(HDC hdc,__in BITMAPINFOHEADER *pbmi); - void SetStretchMode(); - -public: - - // Used to control the image drawing - - CDrawImage(__inout CBaseWindow *pBaseWindow); - BOOL DrawImage(IMediaSample *pMediaSample); - BOOL DrawVideoImageHere(HDC hdc, IMediaSample *pMediaSample, - __in LPRECT lprcSrc, __in LPRECT lprcDst); - void SetDrawContext(); - void SetTargetRect(__in RECT *pTargetRect); - void SetSourceRect(__in RECT *pSourceRect); - void GetTargetRect(__out RECT *pTargetRect); - void GetSourceRect(__out RECT *pSourceRect); - virtual RECT ScaleSourceRect(const RECT *pSource); - - // Handle updating palettes as they change - - LONG GetPaletteVersion(); - void ResetPaletteVersion(); - void IncrementPaletteVersion(); - - // Tell us media types and allocator assignments - - void NotifyAllocator(BOOL bUsingImageAllocator); - void NotifyMediaType(__in CMediaType *pMediaType); - BOOL UsingImageAllocator(); - - // Called when we are about to draw an image - - void NotifyStartDraw() { - MSR_START(m_perfidRenderTime); - }; - - // Called when we complete an image rendering - - void NotifyEndDraw() { - MSR_STOP(m_perfidRenderTime); - }; -}; - - -// This is the structure used to keep information about each GDI DIB. All the -// samples we create from our allocator will have a DIBSECTION allocated to -// them. When we receive the sample we know we can BitBlt straight to an HDC - -typedef struct tagDIBDATA { - - LONG PaletteVersion; // Current palette version in use - DIBSECTION DibSection; // Details of DIB section allocated - HBITMAP hBitmap; // Handle to bitmap for drawing - HANDLE hMapping; // Handle to shared memory block - BYTE *pBase; // Pointer to base memory address - -} DIBDATA; - - -// This class inherits from CMediaSample and uses all of it's methods but it -// overrides the constructor to initialise itself with the DIBDATA structure -// When we come to render an IMediaSample we will know if we are using our own -// allocator, and if we are, we can cast the IMediaSample to a pointer to one -// of these are retrieve the DIB section information and hence the HBITMAP - -class CImageSample : public CMediaSample -{ -protected: - - DIBDATA m_DibData; // Information about the DIBSECTION - BOOL m_bInit; // Is the DIB information setup - -public: - - // Constructor - - CImageSample(__inout CBaseAllocator *pAllocator, - __in_opt LPCTSTR pName, - __inout HRESULT *phr, - __in_bcount(length) LPBYTE pBuffer, - LONG length); - - // Maintain the DIB/DirectDraw state - - void SetDIBData(__in DIBDATA *pDibData); - __out DIBDATA *GetDIBData(); -}; - - -// This is an allocator based on the abstract CBaseAllocator base class that -// allocates sample buffers in shared memory. The number and size of these -// are determined when the output pin calls Prepare on us. The shared memory -// blocks are used in subsequent calls to GDI CreateDIBSection, once that -// has been done the output pin can fill the buffers with data which will -// then be handed to GDI through BitBlt calls and thereby remove one copy - -class CImageAllocator : public CBaseAllocator -{ -protected: - - CBaseFilter *m_pFilter; // Delegate reference counts to - CMediaType *m_pMediaType; // Pointer to the current format - - // Used to create and delete samples - - HRESULT Alloc(); - void Free(); - - // Manage the shared DIBSECTION and DCI/DirectDraw buffers - - HRESULT CreateDIB(LONG InSize,DIBDATA &DibData); - STDMETHODIMP CheckSizes(__in ALLOCATOR_PROPERTIES *pRequest); - virtual CImageSample *CreateImageSample(__in_bcount(Length) LPBYTE pData,LONG Length); - -public: - - // Constructor and destructor - - CImageAllocator(__inout CBaseFilter *pFilter,__in_opt LPCTSTR pName,__inout HRESULT *phr); -#ifdef DEBUG - ~CImageAllocator(); -#endif - - STDMETHODIMP_(ULONG) NonDelegatingAddRef(); - STDMETHODIMP_(ULONG) NonDelegatingRelease(); - void NotifyMediaType(__in CMediaType *pMediaType); - - // Agree the number of buffers to be used and their size - - STDMETHODIMP SetProperties( - __in ALLOCATOR_PROPERTIES *pRequest, - __out ALLOCATOR_PROPERTIES *pActual); -}; - - -// This class is a fairly specialised helper class for image renderers that -// have to create and manage palettes. The CBaseWindow class looks after -// realising palettes once they have been installed. This class can be used -// to create the palette handles from a media format (which must contain a -// VIDEOINFO structure in the format block). We try to make the palette an -// identity palette to maximise performance and also only change palettes -// if actually required to (we compare palette colours before updating). -// All the methods are virtual so that they can be overriden if so required - -class CImagePalette -{ -protected: - - CBaseWindow *m_pBaseWindow; // Window to realise palette in - CBaseFilter *m_pFilter; // Media filter to send events - CDrawImage *m_pDrawImage; // Object who will be drawing - HPALETTE m_hPalette; // The palette handle we own - -public: - - CImagePalette(__inout CBaseFilter *pBaseFilter, - __inout CBaseWindow *pBaseWindow, - __inout CDrawImage *pDrawImage); - -#ifdef DEBUG - virtual ~CImagePalette(); -#endif - - static HPALETTE MakePalette(const VIDEOINFOHEADER *pVideoInfo, __in LPSTR szDevice); - HRESULT RemovePalette(); - static HRESULT MakeIdentityPalette(__inout_ecount_full(iColours) PALETTEENTRY *pEntry,INT iColours, __in LPSTR szDevice); - HRESULT CopyPalette(const CMediaType *pSrc,__out CMediaType *pDest); - BOOL ShouldUpdate(const VIDEOINFOHEADER *pNewInfo,const VIDEOINFOHEADER *pOldInfo); - HRESULT PreparePalette(const CMediaType *pmtNew,const CMediaType *pmtOld,__in LPSTR szDevice); - - BOOL DrawVideoImageHere(HDC hdc, IMediaSample *pMediaSample, __in LPRECT lprcSrc, __in LPRECT lprcDst) - { - return m_pDrawImage->DrawVideoImageHere(hdc, pMediaSample, lprcSrc,lprcDst); - } -}; - - -// Another helper class really for video based renderers. Most such renderers -// need to know what the display format is to some degree or another. This -// class initialises itself with the display format. The format can be asked -// for through GetDisplayFormat and various other accessor functions. If a -// filter detects a display format change (perhaps it gets a WM_DEVMODECHANGE -// message then it can call RefreshDisplayType to reset that format). Also -// many video renderers will want to check formats as they are proposed by -// source filters. This class provides methods to check formats and only -// accept those video formats that can be efficiently drawn using GDI calls - -class CImageDisplay : public CCritSec -{ -protected: - - // This holds the display format; biSize should not be too big, so we can - // safely use the VIDEOINFO structure - VIDEOINFO m_Display; - - static DWORD CountSetBits(const DWORD Field); - static DWORD CountPrefixBits(const DWORD Field); - static BOOL CheckBitFields(const VIDEOINFO *pInput); - -public: - - // Constructor and destructor - - CImageDisplay(); - - // Used to manage BITMAPINFOHEADERs and the display format - - const VIDEOINFO *GetDisplayFormat(); - HRESULT RefreshDisplayType(__in_opt LPSTR szDeviceName); - static BOOL CheckHeaderValidity(const VIDEOINFO *pInput); - static BOOL CheckPaletteHeader(const VIDEOINFO *pInput); - BOOL IsPalettised(); - WORD GetDisplayDepth(); - - // Provide simple video format type checking - - HRESULT CheckMediaType(const CMediaType *pmtIn); - HRESULT CheckVideoType(const VIDEOINFO *pInput); - HRESULT UpdateFormat(__inout VIDEOINFO *pVideoInfo); - const DWORD *GetBitMasks(const VIDEOINFO *pVideoInfo); - - BOOL GetColourMask(__out DWORD *pMaskRed, - __out DWORD *pMaskGreen, - __out DWORD *pMaskBlue); -}; - -// Convert a FORMAT_VideoInfo to FORMAT_VideoInfo2 -STDAPI ConvertVideoInfoToVideoInfo2(__inout AM_MEDIA_TYPE *pmt); - -// Check a media type containing VIDEOINFOHEADER -STDAPI CheckVideoInfoType(const AM_MEDIA_TYPE *pmt); - -// Check a media type containing VIDEOINFOHEADER -STDAPI CheckVideoInfo2Type(const AM_MEDIA_TYPE *pmt); - -#endif // __WINUTIL__ - diff --git a/UnityWebcam/UnityCamService/includes/wxdebug.h b/UnityWebcam/UnityCamService/includes/wxdebug.h deleted file mode 100644 index 62efffb..0000000 --- a/UnityWebcam/UnityCamService/includes/wxdebug.h +++ /dev/null @@ -1,359 +0,0 @@ -//------------------------------------------------------------------------------ -// File: WXDebug.h -// -// Desc: DirectShow base classes - provides debugging facilities. -// -// Copyright (c) 1992-2001 Microsoft Corporation. All rights reserved. -//------------------------------------------------------------------------------ - - -#ifndef __WXDEBUG__ -#define __WXDEBUG__ - -// This library provides fairly straight forward debugging functionality, this -// is split into two main sections. The first is assertion handling, there are -// three types of assertions provided here. The most commonly used one is the -// ASSERT(condition) macro which will pop up a message box including the file -// and line number if the condition evaluates to FALSE. Then there is the -// EXECUTE_ASSERT macro which is the same as ASSERT except the condition will -// still be executed in NON debug builds. The final type of assertion is the -// KASSERT macro which is more suitable for pure (perhaps kernel) filters as -// the condition is printed onto the debugger rather than in a message box. -// -// The other part of the debug module facilties is general purpose logging. -// This is accessed by calling DbgLog(). The function takes a type and level -// field which define the type of informational string you are presenting and -// it's relative importance. The type field can be a combination (one or more) -// of LOG_TIMING, LOG_TRACE, LOG_MEMORY, LOG_LOCKING and LOG_ERROR. The level -// is a DWORD value where zero defines highest important. Use of zero as the -// debug logging level is to be encouraged ONLY for major errors or events as -// they will ALWAYS be displayed on the debugger. Other debug output has it's -// level matched against the current debug output level stored in the registry -// for this module and if less than the current setting it will be displayed. -// -// Each module or executable has it's own debug output level for each of the -// five types. These are read in when the DbgInitialise function is called -// for DLLs linking to STRMBASE.LIB this is done automatically when the DLL -// is loaded, executables must call it explicitely with the module instance -// handle given to them through the WINMAIN entry point. An executable must -// also call DbgTerminate when they have finished to clean up the resources -// the debug library uses, once again this is done automatically for DLLs - -// These are the five different categories of logging information - -enum { LOG_TIMING = 0x01, // Timing and performance measurements - LOG_TRACE = 0x02, // General step point call tracing - LOG_MEMORY = 0x04, // Memory and object allocation/destruction - LOG_LOCKING = 0x08, // Locking/unlocking of critical sections - LOG_ERROR = 0x10, // Debug error notification - LOG_CUSTOM1 = 0x20, - LOG_CUSTOM2 = 0x40, - LOG_CUSTOM3 = 0x80, - LOG_CUSTOM4 = 0x100, - LOG_CUSTOM5 = 0x200, -}; - -#define LOG_FORCIBLY_SET 0x80000000 - -enum { CDISP_HEX = 0x01, - CDISP_DEC = 0x02}; - -// For each object created derived from CBaseObject (in debug builds) we -// create a descriptor that holds it's name (statically allocated memory) -// and a cookie we assign it. We keep a list of all the active objects -// we have registered so that we can dump a list of remaining objects - -typedef struct tag_ObjectDesc { - LPCSTR m_szName; - LPCWSTR m_wszName; - DWORD m_dwCookie; - tag_ObjectDesc *m_pNext; -} ObjectDesc; - -#define DLLIMPORT __declspec(dllimport) -#define DLLEXPORT __declspec(dllexport) - -#ifdef DEBUG - - #define NAME(x) TEXT(x) - - // These are used internally by the debug library (PRIVATE) - - void WINAPI DbgInitKeyLevels(HKEY hKey, bool fTakeMax); - void WINAPI DbgInitGlobalSettings(bool fTakeMax); - void WINAPI DbgInitModuleSettings(bool fTakeMax); - void WINAPI DbgInitModuleName(); - DWORD WINAPI DbgRegisterObjectCreation( - LPCSTR szObjectName, LPCWSTR wszObjectName); - - BOOL WINAPI DbgRegisterObjectDestruction(DWORD dwCookie); - - // These are the PUBLIC entry points - - BOOL WINAPI DbgCheckModuleLevel(DWORD Type,DWORD Level); - void WINAPI DbgSetModuleLevel(DWORD Type,DWORD Level); - void WINAPI DbgSetAutoRefreshLevels(bool fAuto); - - // Initialise the library with the module handle - - void WINAPI DbgInitialise(HINSTANCE hInst); - void WINAPI DbgTerminate(); - - void WINAPI DbgDumpObjectRegister(); - - // Display error and logging to the user - - void WINAPI DbgAssert(LPCTSTR pCondition,LPCTSTR pFileName,INT iLine); - void WINAPI DbgBreakPoint(LPCTSTR pCondition,LPCTSTR pFileName,INT iLine); - void WINAPI DbgBreakPoint(LPCTSTR pFileName,INT iLine,__format_string LPCTSTR szFormatString,...); - - void WINAPI DbgKernelAssert(LPCTSTR pCondition,LPCTSTR pFileName,INT iLine); - void WINAPI DbgLogInfo(DWORD Type,DWORD Level,__format_string LPCTSTR pFormat,...); -#ifdef UNICODE - void WINAPI DbgLogInfo(DWORD Type,DWORD Level,__format_string LPCSTR pFormat,...); - void WINAPI DbgAssert(LPCSTR pCondition,LPCSTR pFileName,INT iLine); - void WINAPI DbgBreakPoint(LPCSTR pCondition,LPCSTR pFileName,INT iLine); - void WINAPI DbgKernelAssert(LPCSTR pCondition,LPCSTR pFileName,INT iLine); -#endif - void WINAPI DbgOutString(LPCTSTR psz); - - // Debug infinite wait stuff - DWORD WINAPI DbgWaitForSingleObject(HANDLE h); - DWORD WINAPI DbgWaitForMultipleObjects(DWORD nCount, - __in_ecount(nCount) CONST HANDLE *lpHandles, - BOOL bWaitAll); - void WINAPI DbgSetWaitTimeout(DWORD dwTimeout); - -#ifdef __strmif_h__ - // Display a media type: Terse at level 2, verbose at level 5 - void WINAPI DisplayType(LPCTSTR label, const AM_MEDIA_TYPE *pmtIn); - - // Dump lots of information about a filter graph - void WINAPI DumpGraph(IFilterGraph *pGraph, DWORD dwLevel); -#endif - - #define KASSERT(_x_) if (!(_x_)) \ - DbgKernelAssert(TEXT(#_x_),TEXT(__FILE__),__LINE__) - - // Break on the debugger without putting up a message box - // message goes to debugger instead - - #define KDbgBreak(_x_) \ - DbgKernelAssert(TEXT(#_x_),TEXT(__FILE__),__LINE__) - - // We chose a common name for our ASSERT macro, MFC also uses this name - // So long as the implementation evaluates the condition and handles it - // then we will be ok. Rather than override the behaviour expected we - // will leave whatever first defines ASSERT as the handler (i.e. MFC) - #ifndef ASSERT - #define ASSERT(_x_) if (!(_x_)) \ - DbgAssert(TEXT(#_x_),TEXT(__FILE__),__LINE__) - #endif - - #define DbgAssertAligned( _ptr_, _alignment_ ) ASSERT( ((DWORD_PTR) (_ptr_)) % (_alignment_) == 0) - - // Put up a message box informing the user of a halt - // condition in the program - - #define DbgBreak(_x_) \ - DbgBreakPoint(TEXT(#_x_),TEXT(__FILE__),__LINE__) - - #define EXECUTE_ASSERT(_x_) ASSERT(_x_) - #define DbgLog(_x_) DbgLogInfo _x_ - // MFC style trace macros - - #define NOTE(_x_) DbgLog((LOG_TRACE,5,TEXT(_x_))) - #define NOTE1(_x_,a) DbgLog((LOG_TRACE,5,TEXT(_x_),a)) - #define NOTE2(_x_,a,b) DbgLog((LOG_TRACE,5,TEXT(_x_),a,b)) - #define NOTE3(_x_,a,b,c) DbgLog((LOG_TRACE,5,TEXT(_x_),a,b,c)) - #define NOTE4(_x_,a,b,c,d) DbgLog((LOG_TRACE,5,TEXT(_x_),a,b,c,d)) - #define NOTE5(_x_,a,b,c,d,e) DbgLog((LOG_TRACE,5,TEXT(_x_),a,b,c,d,e)) - -#else - - // Retail builds make public debug functions inert - WARNING the source - // files do not define or build any of the entry points in debug builds - // (public entry points compile to nothing) so if you go trying to call - // any of the private entry points in your source they won't compile - - #define NAME(_x_) ((LPTSTR) NULL) - - #define DbgInitialise(hInst) - #define DbgTerminate() - #define DbgLog(_x_) 0 - #define DbgOutString(psz) - #define DbgAssertAligned( _ptr_, _alignment_ ) 0 - - #define DbgRegisterObjectCreation(pObjectName) - #define DbgRegisterObjectDestruction(dwCookie) - #define DbgDumpObjectRegister() - - #define DbgCheckModuleLevel(Type,Level) - #define DbgSetModuleLevel(Type,Level) - #define DbgSetAutoRefreshLevels(fAuto) - - #define DbgWaitForSingleObject(h) WaitForSingleObject(h, INFINITE) - #define DbgWaitForMultipleObjects(nCount, lpHandles, bWaitAll) \ - WaitForMultipleObjects(nCount, lpHandles, bWaitAll, INFINITE) - #define DbgSetWaitTimeout(dwTimeout) - - #define KDbgBreak(_x_) - #define DbgBreak(_x_) - - #define KASSERT(_x_) ((void)0) - #ifndef ASSERT - #define ASSERT(_x_) ((void)0) - #endif - #define EXECUTE_ASSERT(_x_) ((void)(_x_)) - - // MFC style trace macros - - #define NOTE(_x_) ((void)0) - #define NOTE1(_x_,a) ((void)0) - #define NOTE2(_x_,a,b) ((void)0) - #define NOTE3(_x_,a,b,c) ((void)0) - #define NOTE4(_x_,a,b,c,d) ((void)0) - #define NOTE5(_x_,a,b,c,d,e) ((void)0) - - #define DisplayType(label, pmtIn) ((void)0) - #define DumpGraph(pGraph, label) ((void)0) -#endif - - -// Checks a pointer which should be non NULL - can be used as follows. - -#define CheckPointer(p,ret) {if((p)==NULL) return (ret);} - -// HRESULT Foo(VOID *pBar) -// { -// CheckPointer(pBar,E_INVALIDARG) -// } -// -// Or if the function returns a boolean -// -// BOOL Foo(VOID *pBar) -// { -// CheckPointer(pBar,FALSE) -// } - -#define ValidateReadPtr(p,cb) 0 -#define ValidateWritePtr(p,cb) 0 -#define ValidateReadWritePtr(p,cb) 0 -#define ValidateStringPtr(p) 0 -#define ValidateStringPtrA(p) 0 -#define ValidateStringPtrW(p) 0 - - -#ifdef _OBJBASE_H_ - - // Outputting GUID names. If you want to include the name - // associated with a GUID (eg CLSID_...) then - // - // GuidNames[yourGUID] - // - // Returns the name defined in uuids.h as a string - - typedef struct { - CHAR *szName; - GUID guid; - } GUID_STRING_ENTRY; - - class CGuidNameList { - public: - CHAR *operator [] (const GUID& guid); - }; - - extern CGuidNameList GuidNames; - -#endif - -#ifndef REMIND - // REMIND macro - generates warning as reminder to complete coding - // (eg) usage: - // - // #pragma message (REMIND("Add automation support")) - - - #define QUOTE(x) #x - #define QQUOTE(y) QUOTE(y) - #define REMIND(str) __FILE__ "(" QQUOTE(__LINE__) ") : " str -#endif - -// Method to display objects in a useful format -// -// eg If you want to display a LONGLONG ll in a debug string do (eg) -// -// DbgLog((LOG_TRACE, n, TEXT("Value is %s"), (LPCTSTR)CDisp(ll, CDISP_HEX))); - - -class CDispBasic -{ -public: - CDispBasic() { m_pString = m_String; }; - ~CDispBasic(); -protected: - PTCHAR m_pString; // normally points to m_String... unless too much data - TCHAR m_String[50]; -}; -class CDisp : public CDispBasic -{ -public: - CDisp(LONGLONG ll, int Format = CDISP_HEX); // Display a LONGLONG in CDISP_HEX or CDISP_DEC form - CDisp(REFCLSID clsid); // Display a GUID - CDisp(double d); // Display a floating point number -#ifdef __strmif_h__ -#ifdef __STREAMS__ - CDisp(CRefTime t); // Display a Reference Time -#endif - CDisp(IPin *pPin); // Display a pin as {filter clsid}(pin name) - CDisp(IUnknown *pUnk); // Display a filter or pin -#endif // __strmif_h__ - ~CDisp(); - - // Implement cast to (LPCTSTR) as parameter to logger - operator LPCTSTR() - { - return (LPCTSTR)m_pString; - }; -}; - - -#if defined(DEBUG) -class CAutoTrace -{ -private: - LPCTSTR _szBlkName; - const int _level; - static const TCHAR _szEntering[]; - static const TCHAR _szLeaving[]; -public: - CAutoTrace(LPCTSTR szBlkName, const int level = 15) - : _szBlkName(szBlkName), _level(level) - {DbgLog((LOG_TRACE, _level, _szEntering, _szBlkName));} - - ~CAutoTrace() - {DbgLog((LOG_TRACE, _level, _szLeaving, _szBlkName));} -}; - -#if defined (__FUNCTION__) - -#define AMTRACEFN() CAutoTrace __trace(TEXT(__FUNCTION__)) -#define AMTRACE(_x_) CAutoTrace __trace(TEXT(__FUNCTION__)) - -#else - -#define AMTRACE(_x_) CAutoTrace __trace _x_ -#define AMTRACEFN() - -#endif - -#else - -#define AMTRACE(_x_) -#define AMTRACEFN() - -#endif - -#endif // __WXDEBUG__ - - diff --git a/UnityWebcam/UnityCamService/includes/wxlist.h b/UnityWebcam/UnityCamService/includes/wxlist.h deleted file mode 100644 index 931893d..0000000 --- a/UnityWebcam/UnityCamService/includes/wxlist.h +++ /dev/null @@ -1,553 +0,0 @@ -//------------------------------------------------------------------------------ -// File: WXList.h -// -// Desc: DirectShow base classes - defines a non-MFC generic template list -// class. -// -// Copyright (c) 1992-2001 Microsoft Corporation. All rights reserved. -//------------------------------------------------------------------------------ - - -/* A generic list of pointers to objects. - No storage management or copying is done on the objects pointed to. - Objectives: avoid using MFC libraries in ndm kernel mode and - provide a really useful list type. - - The class is thread safe in that separate threads may add and - delete items in the list concurrently although the application - must ensure that constructor and destructor access is suitably - synchronised. An application can cause deadlock with operations - which use two lists by simultaneously calling - list1->Operation(list2) and list2->Operation(list1). So don't! - - The names must not conflict with MFC classes as an application - may use both. - */ - -#ifndef __WXLIST__ -#define __WXLIST__ - - /* A POSITION represents (in some fashion that's opaque) a cursor - on the list that can be set to identify any element. NULL is - a valid value and several operations regard NULL as the position - "one step off the end of the list". (In an n element list there - are n+1 places to insert and NULL is that "n+1-th" value). - The POSITION of an element in the list is only invalidated if - that element is deleted. Move operations may mean that what - was a valid POSITION in one list is now a valid POSITION in - a different list. - - Some operations which at first sight are illegal are allowed as - harmless no-ops. For instance RemoveHead is legal on an empty - list and it returns NULL. This allows an atomic way to test if - there is an element there, and if so, get it. The two operations - AddTail and RemoveHead thus implement a MONITOR (See Hoare's paper). - - Single element operations return POSITIONs, non-NULL means it worked. - whole list operations return a BOOL. TRUE means it all worked. - - This definition is the same as the POSITION type for MFCs, so we must - avoid defining it twice. - */ -#ifndef __AFX_H__ -struct __POSITION { int unused; }; -typedef __POSITION* POSITION; -#endif - -const int DEFAULTCACHE = 10; /* Default node object cache size */ - -/* A class representing one node in a list. - Each node knows a pointer to it's adjacent nodes and also a pointer - to the object that it looks after. - All of these pointers can be retrieved or set through member functions. -*/ -class CBaseList -#ifdef DEBUG - : public CBaseObject -#endif -{ - /* Making these classes inherit from CBaseObject does nothing - functionally but it allows us to check there are no memory - leaks in debug builds. - */ - -public: - -#ifdef DEBUG - class CNode : public CBaseObject { -#else - class CNode { -#endif - - CNode *m_pPrev; /* Previous node in the list */ - CNode *m_pNext; /* Next node in the list */ - void *m_pObject; /* Pointer to the object */ - - public: - - /* Constructor - initialise the object's pointers */ - CNode() -#ifdef DEBUG - : CBaseObject(NAME("List node")) -#endif - { - }; - - - /* Return the previous node before this one */ - __out CNode *Prev() const { return m_pPrev; }; - - - /* Return the next node after this one */ - __out CNode *Next() const { return m_pNext; }; - - - /* Set the previous node before this one */ - void SetPrev(__in_opt CNode *p) { m_pPrev = p; }; - - - /* Set the next node after this one */ - void SetNext(__in_opt CNode *p) { m_pNext = p; }; - - - /* Get the pointer to the object for this node */ - __out void *GetData() const { return m_pObject; }; - - - /* Set the pointer to the object for this node */ - void SetData(__in void *p) { m_pObject = p; }; - }; - - class CNodeCache - { - public: - CNodeCache(INT iCacheSize) : m_iCacheSize(iCacheSize), - m_pHead(NULL), - m_iUsed(0) - {}; - ~CNodeCache() { - CNode *pNode = m_pHead; - while (pNode) { - CNode *pCurrent = pNode; - pNode = pNode->Next(); - delete pCurrent; - } - }; - void AddToCache(__inout CNode *pNode) - { - if (m_iUsed < m_iCacheSize) { - pNode->SetNext(m_pHead); - m_pHead = pNode; - m_iUsed++; - } else { - delete pNode; - } - }; - CNode *RemoveFromCache() - { - CNode *pNode = m_pHead; - if (pNode != NULL) { - m_pHead = pNode->Next(); - m_iUsed--; - ASSERT(m_iUsed >= 0); - } else { - ASSERT(m_iUsed == 0); - } - return pNode; - }; - private: - INT m_iCacheSize; - INT m_iUsed; - CNode *m_pHead; - }; - -protected: - - CNode* m_pFirst; /* Pointer to first node in the list */ - CNode* m_pLast; /* Pointer to the last node in the list */ - LONG m_Count; /* Number of nodes currently in the list */ - -private: - - CNodeCache m_Cache; /* Cache of unused node pointers */ - -private: - - /* These override the default copy constructor and assignment - operator for all list classes. They are in the private class - declaration section so that anybody trying to pass a list - object by value will generate a compile time error of - "cannot access the private member function". If these were - not here then the compiler will create default constructors - and assignment operators which when executed first take a - copy of all member variables and then during destruction - delete them all. This must not be done for any heap - allocated data. - */ - CBaseList(const CBaseList &refList); - CBaseList &operator=(const CBaseList &refList); - -public: - - CBaseList(__in_opt LPCTSTR pName, - INT iItems); - - CBaseList(__in_opt LPCTSTR pName); -#ifdef UNICODE - CBaseList(__in_opt LPCSTR pName, - INT iItems); - - CBaseList(__in_opt LPCSTR pName); -#endif - ~CBaseList(); - - /* Remove all the nodes from *this i.e. make the list empty */ - void RemoveAll(); - - - /* Return a cursor which identifies the first element of *this */ - __out_opt POSITION GetHeadPositionI() const; - - - /* Return a cursor which identifies the last element of *this */ - __out_opt POSITION GetTailPositionI() const; - - - /* Return the number of objects in *this */ - int GetCountI() const; - -protected: - /* Return the pointer to the object at rp, - Update rp to the next node in *this - but make it NULL if it was at the end of *this. - This is a wart retained for backwards compatibility. - GetPrev is not implemented. - Use Next, Prev and Get separately. - */ - __out void *GetNextI(__inout POSITION& rp) const; - - - /* Return a pointer to the object at p - Asking for the object at NULL will return NULL harmlessly. - */ - __out_opt void *GetI(__in_opt POSITION p) const; - __out void *GetValidI(__in POSITION p) const; - -public: - /* return the next / prev position in *this - return NULL when going past the end/start. - Next(NULL) is same as GetHeadPosition() - Prev(NULL) is same as GetTailPosition() - An n element list therefore behaves like a n+1 element - cycle with NULL at the start/end. - - !!WARNING!! - This handling of NULL is DIFFERENT from GetNext. - - Some reasons are: - 1. For a list of n items there are n+1 positions to insert - These are conveniently encoded as the n POSITIONs and NULL. - 2. If you are keeping a list sorted (fairly common) and you - search forward for an element to insert before and don't - find it you finish up with NULL as the element before which - to insert. You then want that NULL to be a valid POSITION - so that you can insert before it and you want that insertion - point to mean the (n+1)-th one that doesn't have a POSITION. - (symmetrically if you are working backwards through the list). - 3. It simplifies the algebra which the methods generate. - e.g. AddBefore(p,x) is identical to AddAfter(Prev(p),x) - in ALL cases. All the other arguments probably are reflections - of the algebraic point. - */ - __out_opt POSITION Next(__in_opt POSITION pos) const - { - if (pos == NULL) { - return (POSITION) m_pFirst; - } - CNode *pn = (CNode *) pos; - return (POSITION) pn->Next(); - } //Next - - // See Next - __out_opt POSITION Prev(__in_opt POSITION pos) const - { - if (pos == NULL) { - return (POSITION) m_pLast; - } - CNode *pn = (CNode *) pos; - return (POSITION) pn->Prev(); - } //Prev - - - /* Return the first position in *this which holds the given - pointer. Return NULL if the pointer was not not found. - */ -protected: - __out_opt POSITION FindI( __in void * pObj) const; - - // ??? Should there be (or even should there be only) - // ??? POSITION FindNextAfter(void * pObj, POSITION p) - // ??? And of course FindPrevBefore too. - // ??? List.Find(&Obj) then becomes List.FindNextAfter(&Obj, NULL) - - - /* Remove the first node in *this (deletes the pointer to its - object from the list, does not free the object itself). - Return the pointer to its object. - If *this was already empty it will harmlessly return NULL. - */ - __out_opt void *RemoveHeadI(); - - - /* Remove the last node in *this (deletes the pointer to its - object from the list, does not free the object itself). - Return the pointer to its object. - If *this was already empty it will harmlessly return NULL. - */ - __out_opt void *RemoveTailI(); - - - /* Remove the node identified by p from the list (deletes the pointer - to its object from the list, does not free the object itself). - Asking to Remove the object at NULL will harmlessly return NULL. - Return the pointer to the object removed. - */ - __out_opt void *RemoveI(__in_opt POSITION p); - - /* Add single object *pObj to become a new last element of the list. - Return the new tail position, NULL if it fails. - If you are adding a COM objects, you might want AddRef it first. - Other existing POSITIONs in *this are still valid - */ - __out_opt POSITION AddTailI(__in void * pObj); -public: - - - /* Add all the elements in *pList to the tail of *this. - This duplicates all the nodes in *pList (i.e. duplicates - all its pointers to objects). It does not duplicate the objects. - If you are adding a list of pointers to a COM object into the list - it's a good idea to AddRef them all it when you AddTail it. - Return TRUE if it all worked, FALSE if it didn't. - If it fails some elements may have been added. - Existing POSITIONs in *this are still valid - - If you actually want to MOVE the elements, use MoveToTail instead. - */ - BOOL AddTail(__in CBaseList *pList); - - - /* Mirror images of AddHead: */ - - /* Add single object to become a new first element of the list. - Return the new head position, NULL if it fails. - Existing POSITIONs in *this are still valid - */ -protected: - __out_opt POSITION AddHeadI(__in void * pObj); -public: - - /* Add all the elements in *pList to the head of *this. - Same warnings apply as for AddTail. - Return TRUE if it all worked, FALSE if it didn't. - If it fails some of the objects may have been added. - - If you actually want to MOVE the elements, use MoveToHead instead. - */ - BOOL AddHead(__in CBaseList *pList); - - - /* Add the object *pObj to *this after position p in *this. - AddAfter(NULL,x) adds x to the start - equivalent to AddHead - Return the position of the object added, NULL if it failed. - Existing POSITIONs in *this are undisturbed, including p. - */ -protected: - __out_opt POSITION AddAfterI(__in_opt POSITION p, __in void * pObj); -public: - - /* Add the list *pList to *this after position p in *this - AddAfter(NULL,x) adds x to the start - equivalent to AddHead - Return TRUE if it all worked, FALSE if it didn't. - If it fails, some of the objects may be added - Existing POSITIONs in *this are undisturbed, including p. - */ - BOOL AddAfter(__in_opt POSITION p, __in CBaseList *pList); - - - /* Mirror images: - Add the object *pObj to this-List after position p in *this. - AddBefore(NULL,x) adds x to the end - equivalent to AddTail - Return the position of the new object, NULL if it fails - Existing POSITIONs in *this are undisturbed, including p. - */ - protected: - __out_opt POSITION AddBeforeI(__in_opt POSITION p, __in void * pObj); - public: - - /* Add the list *pList to *this before position p in *this - AddAfter(NULL,x) adds x to the start - equivalent to AddHead - Return TRUE if it all worked, FALSE if it didn't. - If it fails, some of the objects may be added - Existing POSITIONs in *this are undisturbed, including p. - */ - BOOL AddBefore(__in_opt POSITION p, __in CBaseList *pList); - - - /* Note that AddAfter(p,x) is equivalent to AddBefore(Next(p),x) - even in cases where p is NULL or Next(p) is NULL. - Similarly for mirror images etc. - This may make it easier to argue about programs. - */ - - - - /* The following operations do not copy any elements. - They move existing blocks of elements around by switching pointers. - They are fairly efficient for long lists as for short lists. - (Alas, the Count slows things down). - - They split the list into two parts. - One part remains as the original list, the other part - is appended to the second list. There are eight possible - variations: - Split the list {after/before} a given element - keep the {head/tail} portion in the original list - append the rest to the {head/tail} of the new list. - - Since After is strictly equivalent to Before Next - we are not in serious need of the Before/After variants. - That leaves only four. - - If you are processing a list left to right and dumping - the bits that you have processed into another list as - you go, the Tail/Tail variant gives the most natural result. - If you are processing in reverse order, Head/Head is best. - - By using NULL positions and empty lists judiciously either - of the other two can be built up in two operations. - - The definition of NULL (see Next/Prev etc) means that - degenerate cases include - "move all elements to new list" - "Split a list into two lists" - "Concatenate two lists" - (and quite a few no-ops) - - !!WARNING!! The type checking won't buy you much if you get list - positions muddled up - e.g. use a POSITION that's in a different - list and see what a mess you get! - */ - - /* Split *this after position p in *this - Retain as *this the tail portion of the original *this - Add the head portion to the tail end of *pList - Return TRUE if it all worked, FALSE if it didn't. - - e.g. - foo->MoveToTail(foo->GetHeadPosition(), bar); - moves one element from the head of foo to the tail of bar - foo->MoveToTail(NULL, bar); - is a no-op, returns NULL - foo->MoveToTail(foo->GetTailPosition, bar); - concatenates foo onto the end of bar and empties foo. - - A better, except excessively long name might be - MoveElementsFromHeadThroughPositionToOtherTail - */ - BOOL MoveToTail(__in_opt POSITION pos, __in CBaseList *pList); - - - /* Mirror image: - Split *this before position p in *this. - Retain in *this the head portion of the original *this - Add the tail portion to the start (i.e. head) of *pList - - e.g. - foo->MoveToHead(foo->GetTailPosition(), bar); - moves one element from the tail of foo to the head of bar - foo->MoveToHead(NULL, bar); - is a no-op, returns NULL - foo->MoveToHead(foo->GetHeadPosition, bar); - concatenates foo onto the start of bar and empties foo. - */ - BOOL MoveToHead(__in_opt POSITION pos, __in CBaseList *pList); - - - /* Reverse the order of the [pointers to] objects in *this - */ - void Reverse(); - - - /* set cursor to the position of each element of list in turn */ - #define TRAVERSELIST(list, cursor) \ - for ( cursor = (list).GetHeadPosition() \ - ; cursor!=NULL \ - ; cursor = (list).Next(cursor) \ - ) - - - /* set cursor to the position of each element of list in turn - in reverse order - */ - #define REVERSETRAVERSELIST(list, cursor) \ - for ( cursor = (list).GetTailPosition() \ - ; cursor!=NULL \ - ; cursor = (list).Prev(cursor) \ - ) - -}; // end of class declaration - -template class CGenericList : public CBaseList -{ -public: - CGenericList(__in_opt LPCTSTR pName, - INT iItems, - BOOL bLock = TRUE, - BOOL bAlert = FALSE) : - CBaseList(pName, iItems) { - UNREFERENCED_PARAMETER(bAlert); - UNREFERENCED_PARAMETER(bLock); - }; - CGenericList(__in_opt LPCTSTR pName) : - CBaseList(pName) { - }; - - __out_opt POSITION GetHeadPosition() const { return (POSITION)m_pFirst; } - __out_opt POSITION GetTailPosition() const { return (POSITION)m_pLast; } - int GetCount() const { return m_Count; } - - __out OBJECT *GetNext(__inout POSITION& rp) const { return (OBJECT *) GetNextI(rp); } - - __out_opt OBJECT *Get(__in_opt POSITION p) const { return (OBJECT *) GetI(p); } - __out OBJECT *GetValid(__in POSITION p) const { return (OBJECT *) GetValidI(p); } - __out_opt OBJECT *GetHead() const { return Get(GetHeadPosition()); } - - __out_opt OBJECT *RemoveHead() { return (OBJECT *) RemoveHeadI(); } - - __out_opt OBJECT *RemoveTail() { return (OBJECT *) RemoveTailI(); } - - __out_opt OBJECT *Remove(__in_opt POSITION p) { return (OBJECT *) RemoveI(p); } - __out_opt POSITION AddBefore(__in_opt POSITION p, __in OBJECT * pObj) { return AddBeforeI(p, pObj); } - __out_opt POSITION AddAfter(__in_opt POSITION p, __in OBJECT * pObj) { return AddAfterI(p, pObj); } - __out_opt POSITION AddHead(__in OBJECT * pObj) { return AddHeadI(pObj); } - __out_opt POSITION AddTail(__in OBJECT * pObj) { return AddTailI(pObj); } - BOOL AddTail(__in CGenericList *pList) - { return CBaseList::AddTail((CBaseList *) pList); } - BOOL AddHead(__in CGenericList *pList) - { return CBaseList::AddHead((CBaseList *) pList); } - BOOL AddAfter(__in_opt POSITION p, __in CGenericList *pList) - { return CBaseList::AddAfter(p, (CBaseList *) pList); }; - BOOL AddBefore(__in_opt POSITION p, __in CGenericList *pList) - { return CBaseList::AddBefore(p, (CBaseList *) pList); }; - __out_opt POSITION Find( __in OBJECT * pObj) const { return FindI(pObj); } -}; // end of class declaration - - - -/* These define the standard list types */ - -typedef CGenericList CBaseObjectList; -typedef CGenericList CBaseInterfaceList; - -#endif /* __WXLIST__ */ - diff --git a/UnityWebcam/UnityCamService/includes/wxutil.h b/UnityWebcam/UnityCamService/includes/wxutil.h deleted file mode 100644 index 3bfc2d2..0000000 --- a/UnityWebcam/UnityCamService/includes/wxutil.h +++ /dev/null @@ -1,532 +0,0 @@ -//------------------------------------------------------------------------------ -// File: WXUtil.h -// -// Desc: DirectShow base classes - defines helper classes and functions for -// building multimedia filters. -// -// Copyright (c) 1992-2001 Microsoft Corporation. All rights reserved. -//------------------------------------------------------------------------------ - - -#ifndef __WXUTIL__ -#define __WXUTIL__ - -// eliminate spurious "statement has no effect" warnings. -#pragma warning(disable: 4705) - -// wrapper for whatever critical section we have -class CCritSec { - - // make copy constructor and assignment operator inaccessible - - CCritSec(const CCritSec &refCritSec); - CCritSec &operator=(const CCritSec &refCritSec); - - CRITICAL_SECTION m_CritSec; - -#ifdef DEBUG -public: - DWORD m_currentOwner; - DWORD m_lockCount; - BOOL m_fTrace; // Trace this one -public: - CCritSec(); - ~CCritSec(); - void Lock(); - void Unlock(); -#else - -public: - CCritSec() { - InitializeCriticalSection(&m_CritSec); - }; - - ~CCritSec() { - DeleteCriticalSection(&m_CritSec); - }; - - void Lock() { - EnterCriticalSection(&m_CritSec); - }; - - void Unlock() { - LeaveCriticalSection(&m_CritSec); - }; -#endif -}; - -// -// To make deadlocks easier to track it is useful to insert in the -// code an assertion that says whether we own a critical section or -// not. We make the routines that do the checking globals to avoid -// having different numbers of member functions in the debug and -// retail class implementations of CCritSec. In addition we provide -// a routine that allows usage of specific critical sections to be -// traced. This is NOT on by default - there are far too many. -// - -#ifdef DEBUG - BOOL WINAPI CritCheckIn(CCritSec * pcCrit); - BOOL WINAPI CritCheckIn(const CCritSec * pcCrit); - BOOL WINAPI CritCheckOut(CCritSec * pcCrit); - BOOL WINAPI CritCheckOut(const CCritSec * pcCrit); - void WINAPI DbgLockTrace(CCritSec * pcCrit, BOOL fTrace); -#else - #define CritCheckIn(x) TRUE - #define CritCheckOut(x) TRUE - #define DbgLockTrace(pc, fT) -#endif - - -// locks a critical section, and unlocks it automatically -// when the lock goes out of scope -class CAutoLock { - - // make copy constructor and assignment operator inaccessible - - CAutoLock(const CAutoLock &refAutoLock); - CAutoLock &operator=(const CAutoLock &refAutoLock); - -protected: - CCritSec * m_pLock; - -public: - CAutoLock(CCritSec * plock) - { - m_pLock = plock; - m_pLock->Lock(); - }; - - ~CAutoLock() { - m_pLock->Unlock(); - }; -}; - - - -// wrapper for event objects -class CAMEvent -{ - - // make copy constructor and assignment operator inaccessible - - CAMEvent(const CAMEvent &refEvent); - CAMEvent &operator=(const CAMEvent &refEvent); - -protected: - HANDLE m_hEvent; -public: - CAMEvent(BOOL fManualReset = FALSE, __inout_opt HRESULT *phr = NULL); - CAMEvent(__inout_opt HRESULT *phr); - ~CAMEvent(); - - // Cast to HANDLE - we don't support this as an lvalue - operator HANDLE () const { return m_hEvent; }; - - void Set() {EXECUTE_ASSERT(SetEvent(m_hEvent));}; - BOOL Wait(DWORD dwTimeout = INFINITE) { - return (WaitForSingleObject(m_hEvent, dwTimeout) == WAIT_OBJECT_0); - }; - void Reset() { ResetEvent(m_hEvent); }; - BOOL Check() { return Wait(0); }; -}; - - -// wrapper for event objects that do message processing -// This adds ONE method to the CAMEvent object to allow sent -// messages to be processed while waiting - -class CAMMsgEvent : public CAMEvent -{ - -public: - - CAMMsgEvent(__inout_opt HRESULT *phr = NULL); - - // Allow SEND messages to be processed while waiting - BOOL WaitMsg(DWORD dwTimeout = INFINITE); -}; - -// old name supported for the time being -#define CTimeoutEvent CAMEvent - -// support for a worker thread - -#ifdef AM_NOVTABLE -// simple thread class supports creation of worker thread, synchronization -// and communication. Can be derived to simplify parameter passing -class AM_NOVTABLE CAMThread { - - // make copy constructor and assignment operator inaccessible - - CAMThread(const CAMThread &refThread); - CAMThread &operator=(const CAMThread &refThread); - - CAMEvent m_EventSend; - CAMEvent m_EventComplete; - - DWORD m_dwParam; - DWORD m_dwReturnVal; - -protected: - HANDLE m_hThread; - - // thread will run this function on startup - // must be supplied by derived class - virtual DWORD ThreadProc() = 0; - -public: - CAMThread(__inout_opt HRESULT *phr = NULL); - virtual ~CAMThread(); - - CCritSec m_AccessLock; // locks access by client threads - CCritSec m_WorkerLock; // locks access to shared objects - - // thread initially runs this. param is actually 'this'. function - // just gets this and calls ThreadProc - static DWORD WINAPI InitialThreadProc(__inout LPVOID pv); - - // start thread running - error if already running - BOOL Create(); - - // signal the thread, and block for a response - // - DWORD CallWorker(DWORD); - - // accessor thread calls this when done with thread (having told thread - // to exit) - void Close() { - - // Disable warning: Conversion from LONG to PVOID of greater size -#pragma warning(push) -#pragma warning(disable: 4312) - HANDLE hThread = (HANDLE)InterlockedExchangePointer(&m_hThread, 0); -#pragma warning(pop) - - if (hThread) { - WaitForSingleObject(hThread, INFINITE); - CloseHandle(hThread); - } - }; - - // ThreadExists - // Return TRUE if the thread exists. FALSE otherwise - BOOL ThreadExists(void) const - { - if (m_hThread == 0) { - return FALSE; - } else { - return TRUE; - } - } - - // wait for the next request - DWORD GetRequest(); - - // is there a request? - BOOL CheckRequest(__out_opt DWORD * pParam); - - // reply to the request - void Reply(DWORD); - - // If you want to do WaitForMultipleObjects you'll need to include - // this handle in your wait list or you won't be responsive - HANDLE GetRequestHandle() const { return m_EventSend; }; - - // Find out what the request was - DWORD GetRequestParam() const { return m_dwParam; }; - - // call CoInitializeEx (COINIT_DISABLE_OLE1DDE) if - // available. S_FALSE means it's not available. - static HRESULT CoInitializeHelper(); -}; -#endif // AM_NOVTABLE - - -// CQueue -// -// Implements a simple Queue ADT. The queue contains a finite number of -// objects, access to which is controlled by a semaphore. The semaphore -// is created with an initial count (N). Each time an object is added -// a call to WaitForSingleObject is made on the semaphore's handle. When -// this function returns a slot has been reserved in the queue for the new -// object. If no slots are available the function blocks until one becomes -// available. Each time an object is removed from the queue ReleaseSemaphore -// is called on the semaphore's handle, thus freeing a slot in the queue. -// If no objects are present in the queue the function blocks until an -// object has been added. - -#define DEFAULT_QUEUESIZE 2 - -template class CQueue { -private: - HANDLE hSemPut; // Semaphore controlling queue "putting" - HANDLE hSemGet; // Semaphore controlling queue "getting" - CRITICAL_SECTION CritSect; // Thread seriallization - int nMax; // Max objects allowed in queue - int iNextPut; // Array index of next "PutMsg" - int iNextGet; // Array index of next "GetMsg" - T *QueueObjects; // Array of objects (ptr's to void) - - void Initialize(int n) { - iNextPut = iNextGet = 0; - nMax = n; - InitializeCriticalSection(&CritSect); - hSemPut = CreateSemaphore(NULL, n, n, NULL); - hSemGet = CreateSemaphore(NULL, 0, n, NULL); - QueueObjects = new T[n]; - } - - -public: - CQueue(int n) { - Initialize(n); - } - - CQueue() { - Initialize(DEFAULT_QUEUESIZE); - } - - ~CQueue() { - delete [] QueueObjects; - DeleteCriticalSection(&CritSect); - CloseHandle(hSemPut); - CloseHandle(hSemGet); - } - - T GetQueueObject() { - int iSlot; - T Object; - LONG lPrevious; - - // Wait for someone to put something on our queue, returns straight - // away is there is already an object on the queue. - // - WaitForSingleObject(hSemGet, INFINITE); - - EnterCriticalSection(&CritSect); - iSlot = iNextGet++ % nMax; - Object = QueueObjects[iSlot]; - LeaveCriticalSection(&CritSect); - - // Release anyone waiting to put an object onto our queue as there - // is now space available in the queue. - // - ReleaseSemaphore(hSemPut, 1L, &lPrevious); - return Object; - } - - void PutQueueObject(T Object) { - int iSlot; - LONG lPrevious; - - // Wait for someone to get something from our queue, returns straight - // away is there is already an empty slot on the queue. - // - WaitForSingleObject(hSemPut, INFINITE); - - EnterCriticalSection(&CritSect); - iSlot = iNextPut++ % nMax; - QueueObjects[iSlot] = Object; - LeaveCriticalSection(&CritSect); - - // Release anyone waiting to remove an object from our queue as there - // is now an object available to be removed. - // - ReleaseSemaphore(hSemGet, 1L, &lPrevious); - } -}; - -// Ensures that memory is not read past the length source buffer -// and that memory is not written past the length of the dst buffer -// dst - buffer to copy to -// dst_size - total size of destination buffer -// cb_dst_offset - offset, first byte copied to dst+cb_dst_offset -// src - buffer to copy from -// src_size - total size of source buffer -// cb_src_offset - offset, first byte copied from src+cb_src_offset -// count - number of bytes to copy -// -// Returns: -// S_OK - no error -// E_INVALIDARG - values passed would lead to overrun -HRESULT AMSafeMemMoveOffset( - __in_bcount(dst_size) void * dst, - __in size_t dst_size, - __in DWORD cb_dst_offset, - __in_bcount(src_size) const void * src, - __in size_t src_size, - __in DWORD cb_src_offset, - __in size_t count); - -extern "C" -void * __stdcall memmoveInternal(void *, const void *, size_t); - -inline void * __cdecl memchrInternal(const void *buf, int chr, size_t cnt) -{ -#ifdef _X86_ - void *pRet = NULL; - - _asm { - cld // make sure we get the direction right - mov ecx, cnt // num of bytes to scan - mov edi, buf // pointer byte stream - mov eax, chr // byte to scan for - repne scasb // look for the byte in the byte stream - jnz exit_memchr // Z flag set if byte found - dec edi // scasb always increments edi even when it - // finds the required byte - mov pRet, edi -exit_memchr: - } - return pRet; - -#else - while ( cnt && (*(unsigned char *)buf != (unsigned char)chr) ) { - buf = (unsigned char *)buf + 1; - cnt--; - } - - return(cnt ? (void *)buf : NULL); -#endif -} - -void WINAPI IntToWstr(int i, __out_ecount(12) LPWSTR wstr); - -#define WstrToInt(sz) _wtoi(sz) -#define atoiW(sz) _wtoi(sz) -#define atoiA(sz) atoi(sz) - -// These are available to help managing bitmap VIDEOINFOHEADER media structures - -extern const DWORD bits555[3]; -extern const DWORD bits565[3]; -extern const DWORD bits888[3]; - -// These help convert between VIDEOINFOHEADER and BITMAPINFO structures - -STDAPI_(const GUID) GetTrueColorType(const BITMAPINFOHEADER *pbmiHeader); -STDAPI_(const GUID) GetBitmapSubtype(const BITMAPINFOHEADER *pbmiHeader); -STDAPI_(WORD) GetBitCount(const GUID *pSubtype); - -// strmbase.lib implements this for compatibility with people who -// managed to link to this directly. we don't want to advertise it. -// -// STDAPI_(/* T */ CHAR *) GetSubtypeName(const GUID *pSubtype); - -STDAPI_(CHAR *) GetSubtypeNameA(const GUID *pSubtype); -STDAPI_(WCHAR *) GetSubtypeNameW(const GUID *pSubtype); - -#ifdef UNICODE -#define GetSubtypeName GetSubtypeNameW -#else -#define GetSubtypeName GetSubtypeNameA -#endif - -STDAPI_(LONG) GetBitmapFormatSize(const BITMAPINFOHEADER *pHeader); -STDAPI_(DWORD) GetBitmapSize(const BITMAPINFOHEADER *pHeader); - -#ifdef __AMVIDEO__ -STDAPI_(BOOL) ContainsPalette(const VIDEOINFOHEADER *pVideoInfo); -STDAPI_(const RGBQUAD *) GetBitmapPalette(const VIDEOINFOHEADER *pVideoInfo); -#endif // __AMVIDEO__ - - -// Compares two interfaces and returns TRUE if they are on the same object -BOOL WINAPI IsEqualObject(IUnknown *pFirst, IUnknown *pSecond); - -// This is for comparing pins -#define EqualPins(pPin1, pPin2) IsEqualObject(pPin1, pPin2) - - -// Arithmetic helper functions - -// Compute (a * b + rnd) / c -LONGLONG WINAPI llMulDiv(LONGLONG a, LONGLONG b, LONGLONG c, LONGLONG rnd); -LONGLONG WINAPI Int64x32Div32(LONGLONG a, LONG b, LONG c, LONG rnd); - - -// Avoids us dyna-linking to SysAllocString to copy BSTR strings -STDAPI WriteBSTR(__deref_out BSTR * pstrDest, LPCWSTR szSrc); -STDAPI FreeBSTR(__deref_in BSTR* pstr); - -// Return a wide string - allocating memory for it -// Returns: -// S_OK - no error -// E_POINTER - ppszReturn == NULL -// E_OUTOFMEMORY - can't allocate memory for returned string -STDAPI AMGetWideString(LPCWSTR pszString, __deref_out LPWSTR *ppszReturn); - -// Special wait for objects owning windows -DWORD WINAPI WaitDispatchingMessages( - HANDLE hObject, - DWORD dwWait, - HWND hwnd = NULL, - UINT uMsg = 0, - HANDLE hEvent = NULL); - -// HRESULT_FROM_WIN32 converts ERROR_SUCCESS to a success code, but in -// our use of HRESULT_FROM_WIN32, it typically means a function failed -// to call SetLastError(), and we still want a failure code. -// -#define AmHresultFromWin32(x) (MAKE_HRESULT(SEVERITY_ERROR, FACILITY_WIN32, x)) - -// call GetLastError and return an HRESULT value that will fail the -// SUCCEEDED() macro. -HRESULT AmGetLastErrorToHResult(void); - -// duplicate of ATL's CComPtr to avoid linker conflicts. - -IUnknown* QzAtlComPtrAssign(__deref_inout_opt IUnknown** pp, __in_opt IUnknown* lp); - -template -class QzCComPtr -{ -public: - typedef T _PtrClass; - QzCComPtr() {p=NULL;} - QzCComPtr(T* lp) - { - if ((p = lp) != NULL) - p->AddRef(); - } - QzCComPtr(const QzCComPtr& lp) - { - if ((p = lp.p) != NULL) - p->AddRef(); - } - ~QzCComPtr() {if (p) p->Release();} - void Release() {if (p) p->Release(); p=NULL;} - operator T*() {return (T*)p;} - T& operator*() {ASSERT(p!=NULL); return *p; } - //The assert on operator& usually indicates a bug. If this is really - //what is needed, however, take the address of the p member explicitly. - T** operator&() { ASSERT(p==NULL); return &p; } - T* operator->() { ASSERT(p!=NULL); return p; } - T* operator=(T* lp){return (T*)QzAtlComPtrAssign((IUnknown**)&p, lp);} - T* operator=(const QzCComPtr& lp) - { - return (T*)QzAtlComPtrAssign((IUnknown**)&p, lp.p); - } -#if _MSC_VER>1020 - bool operator!(){return (p == NULL);} -#else - BOOL operator!(){return (p == NULL) ? TRUE : FALSE;} -#endif - T* p; -}; - -MMRESULT CompatibleTimeSetEvent( UINT uDelay, UINT uResolution, __in LPTIMECALLBACK lpTimeProc, DWORD_PTR dwUser, UINT fuEvent ); -bool TimeKillSynchronousFlagAvailable( void ); - -// Helper to replace lstrcpmi -__inline int lstrcmpiLocaleIndependentW(LPCWSTR lpsz1, LPCWSTR lpsz2) -{ - return CompareStringW(LOCALE_INVARIANT, NORM_IGNORECASE, lpsz1, -1, lpsz2, -1) - CSTR_EQUAL; -} -__inline int lstrcmpiLocaleIndependentA(LPCSTR lpsz1, LPCSTR lpsz2) -{ - return CompareStringA(LOCALE_INVARIANT, NORM_IGNORECASE, lpsz1, -1, lpsz2, -1) - CSTR_EQUAL; -} - -#endif /* __WXUTIL__ */ diff --git a/UnityWebcam/UnityCamService/libs/x64/strmbasd.lib b/UnityWebcam/UnityCamService/libs/x64/strmbasd.lib deleted file mode 100644 index 4df2448..0000000 Binary files a/UnityWebcam/UnityCamService/libs/x64/strmbasd.lib and /dev/null differ diff --git a/UnityWebcam/UnityCamService/libs/x64/strmbase.lib b/UnityWebcam/UnityCamService/libs/x64/strmbase.lib deleted file mode 100644 index d29f67f..0000000 Binary files a/UnityWebcam/UnityCamService/libs/x64/strmbase.lib and /dev/null differ diff --git a/UnityWebcam/UnityCamService/libs/x86/strmbasd.lib b/UnityWebcam/UnityCamService/libs/x86/strmbasd.lib deleted file mode 100644 index c1f1e01..0000000 Binary files a/UnityWebcam/UnityCamService/libs/x86/strmbasd.lib and /dev/null differ diff --git a/UnityWebcam/UnityCamService/libs/x86/strmbase.lib b/UnityWebcam/UnityCamService/libs/x86/strmbase.lib deleted file mode 100644 index 467ed9f..0000000 Binary files a/UnityWebcam/UnityCamService/libs/x86/strmbase.lib and /dev/null differ diff --git a/UnityWebcam/UnityCamService/stdafx.cpp b/UnityWebcam/UnityCamService/stdafx.cpp deleted file mode 100644 index 1647228..0000000 --- a/UnityWebcam/UnityCamService/stdafx.cpp +++ /dev/null @@ -1,2 +0,0 @@ - -#include "stdafx.h" \ No newline at end of file diff --git a/UnityWebcam/UnityCamService/stdafx.h b/UnityWebcam/UnityCamService/stdafx.h deleted file mode 100644 index 33ed0eb..0000000 --- a/UnityWebcam/UnityCamService/stdafx.h +++ /dev/null @@ -1,8 +0,0 @@ - -#pragma once - -#include "targetver.h" - -#define WIN32_LEAN_AND_MEAN -#include -#include diff --git a/UnityWebcam/UnityCamService/targetver.h b/UnityWebcam/UnityCamService/targetver.h deleted file mode 100644 index 87c0086..0000000 --- a/UnityWebcam/UnityCamService/targetver.h +++ /dev/null @@ -1,8 +0,0 @@ -#pragma once - -// Including SDKDDKVer.h defines the highest available Windows platform. - -// If you wish to build your application for a previous Windows platform, include WinSDKVer.h and -// set the _WIN32_WINNT macro to the platform you wish to support before including SDKDDKVer.h. - -#include diff --git a/UnityWebcam/UnityWebcam.sln b/UnityWebcam/UnityWebcam.sln deleted file mode 100644 index 01f371c..0000000 --- a/UnityWebcam/UnityWebcam.sln +++ /dev/null @@ -1,35 +0,0 @@ - -Microsoft Visual Studio Solution File, Format Version 12.00 -# Visual Studio 2013 -VisualStudioVersion = 12.0.21005.1 -MinimumVisualStudioVersion = 10.0.40219.1 -Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "UnityWebcam", "UnityWebcam\UnityWebcam.vcxproj", "{727D3AC5-27B5-4288-A475-7A471ECD71B7}" -EndProject -Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "UnityCamService", "UnityCamService\UnityCamService.vcxproj", "{3D0A9889-9EC1-4012-9382-4FE1EB610D17}" -EndProject -Global - GlobalSection(SolutionConfigurationPlatforms) = preSolution - Debug|Win32 = Debug|Win32 - Debug|x64 = Debug|x64 - Release|Win32 = Release|Win32 - Release|x64 = Release|x64 - EndGlobalSection - GlobalSection(ProjectConfigurationPlatforms) = postSolution - {727D3AC5-27B5-4288-A475-7A471ECD71B7}.Debug|Win32.ActiveCfg = Debug|x64 - {727D3AC5-27B5-4288-A475-7A471ECD71B7}.Debug|x64.ActiveCfg = Debug|x64 - {727D3AC5-27B5-4288-A475-7A471ECD71B7}.Release|Win32.ActiveCfg = Release|Win32 - {727D3AC5-27B5-4288-A475-7A471ECD71B7}.Release|Win32.Build.0 = Release|Win32 - {727D3AC5-27B5-4288-A475-7A471ECD71B7}.Release|x64.ActiveCfg = Release|x64 - {3D0A9889-9EC1-4012-9382-4FE1EB610D17}.Debug|Win32.ActiveCfg = Debug|Win32 - {3D0A9889-9EC1-4012-9382-4FE1EB610D17}.Debug|Win32.Build.0 = Debug|Win32 - {3D0A9889-9EC1-4012-9382-4FE1EB610D17}.Debug|x64.ActiveCfg = Debug|x64 - {3D0A9889-9EC1-4012-9382-4FE1EB610D17}.Debug|x64.Build.0 = Debug|x64 - {3D0A9889-9EC1-4012-9382-4FE1EB610D17}.Release|Win32.ActiveCfg = Release|Win32 - {3D0A9889-9EC1-4012-9382-4FE1EB610D17}.Release|Win32.Build.0 = Release|Win32 - {3D0A9889-9EC1-4012-9382-4FE1EB610D17}.Release|x64.ActiveCfg = Release|x64 - {3D0A9889-9EC1-4012-9382-4FE1EB610D17}.Release|x64.Build.0 = Release|x64 - EndGlobalSection - GlobalSection(SolutionProperties) = preSolution - HideSolutionNode = FALSE - EndGlobalSection -EndGlobal diff --git a/UnityWebcam/UnityWebcam/FilterRegister.cpp b/UnityWebcam/UnityWebcam/FilterRegister.cpp deleted file mode 100644 index 5a9b56d..0000000 --- a/UnityWebcam/UnityWebcam/FilterRegister.cpp +++ /dev/null @@ -1,64 +0,0 @@ - - -#include "stdafx.h" -#include "FilterRegister.h" -#include - -FilterRegister* FilterRegister::_instance = 0; - - -FilterRegister::FilterRegister() -{ - _refCount = 0; - _registered = false; -} -FilterRegister::~FilterRegister() -{ -} - -void FilterRegister::AddRef() -{ - _refCount++; - if (_refCount > 0) - { - _Register(); - } - -} -void FilterRegister::SubRef() -{ - _refCount--; - if (_refCount <= 0) - { - _refCount = 0; - _UnRegister(); - } - -} - -//http://www.gdcl.co.uk/2011/June/UnregisteredFilters.htm -typedef HRESULT(STDAPICALLTYPE* FN_DLLGETCLASSOBJECT)(REFCLSID clsid, REFIID iid, void** ppv); - -void FilterRegister::_Register() -{ - if (_registered) - return; - - _registered = true; -} -void FilterRegister::_UnRegister() -{ - if (!_registered) - return; - - _registered = false; -} - -FilterRegister* FilterRegister::Instance() -{ - if (_instance == NULL) - _instance = new FilterRegister(); - return _instance; -} - - diff --git a/UnityWebcam/UnityWebcam/FilterRegister.h b/UnityWebcam/UnityWebcam/FilterRegister.h deleted file mode 100644 index 71ce461..0000000 --- a/UnityWebcam/UnityWebcam/FilterRegister.h +++ /dev/null @@ -1,31 +0,0 @@ - - -#ifndef __FILTERREGISTER__ -#define __FILTERREGISTER__ - - -class FilterRegister -{ -protected: - - int _refCount; - bool _registered; - static FilterRegister* _instance; - - void _Register(); - void _UnRegister(); -public: - - FilterRegister(); - virtual ~FilterRegister(); - - void AddRef(); - void SubRef(); - - - static FilterRegister* Instance(); -}; - - - -#endif diff --git a/UnityWebcam/UnityWebcam/GraphicsInclude.h b/UnityWebcam/UnityWebcam/GraphicsInclude.h deleted file mode 100644 index e69de29..0000000 diff --git a/UnityWebcam/UnityWebcam/PluginInterface.cpp b/UnityWebcam/UnityWebcam/PluginInterface.cpp deleted file mode 100644 index 80745a0..0000000 --- a/UnityWebcam/UnityWebcam/PluginInterface.cpp +++ /dev/null @@ -1,57 +0,0 @@ -// -// Funnel - Syphon server plugin for Unity -// -// Copyright (C) 2013-2016 Keijiro Takahashi -// -// 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. -// - -#include "stdafx.h" -#include "IUnityInterface.h" -#include "IUnityGraphics.h" - -namespace -{ - IUnityInterfaces* s_interfaces; - IUnityGraphics* s_graphics; -} - -extern "C" -{ - void UNITY_INTERFACE_API OnGraphicsDeviceEvent(UnityGfxDeviceEventType eventType) - {} - // Plugin load event - void UNITY_INTERFACE_EXPORT UNITY_INTERFACE_API UnityPluginLoad(IUnityInterfaces* interfaces) - { - s_interfaces = interfaces; - s_graphics = s_interfaces->Get(); - - s_graphics->RegisterDeviceEventCallback(OnGraphicsDeviceEvent); - - // Run OnGraphicsDeviceEvent(initialize) manually on plugin load. - OnGraphicsDeviceEvent(kUnityGfxDeviceEventInitialize); - } - - // Plugin unload event - void UNITY_INTERFACE_EXPORT UNITY_INTERFACE_API UnityPluginUnload() - { - s_graphics->UnregisterDeviceEventCallback(OnGraphicsDeviceEvent); - } - -} diff --git a/UnityWebcam/UnityWebcam/ReadMe.txt b/UnityWebcam/UnityWebcam/ReadMe.txt deleted file mode 100644 index 612076b..0000000 --- a/UnityWebcam/UnityWebcam/ReadMe.txt +++ /dev/null @@ -1,48 +0,0 @@ -======================================================================== - DYNAMIC LINK LIBRARY : UnityWebcam Project Overview -======================================================================== - -AppWizard has created this UnityWebcam DLL for you. - -This file contains a summary of what you will find in each of the files that -make up your UnityWebcam application. - - -UnityWebcam.vcxproj - This is the main project file for VC++ projects generated using an Application Wizard. - It contains information about the version of Visual C++ that generated the file, and - information about the platforms, configurations, and project features selected with the - Application Wizard. - -UnityWebcam.vcxproj.filters - This is the filters file for VC++ projects generated using an Application Wizard. - It contains information about the association between the files in your project - and the filters. This association is used in the IDE to show grouping of files with - similar extensions under a specific node (for e.g. ".cpp" files are associated with the - "Source Files" filter). - -UnityWebcam.cpp - This is the main DLL source file. - - When created, this DLL does not export any symbols. As a result, it - will not produce a .lib file when it is built. If you wish this project - to be a project dependency of some other project, you will either need to - add code to export some symbols from the DLL so that an export library - will be produced, or you can set the Ignore Input Library property to Yes - on the General propert page of the Linker folder in the project's Property - Pages dialog box. - -///////////////////////////////////////////////////////////////////////////// -Other standard files: - -StdAfx.h, StdAfx.cpp - These files are used to build a precompiled header (PCH) file - named UnityWebcam.pch and a precompiled types file named StdAfx.obj. - -///////////////////////////////////////////////////////////////////////////// -Other notes: - -AppWizard uses "TODO:" comments to indicate parts of the source code you -should add to or customize. - -///////////////////////////////////////////////////////////////////////////// diff --git a/UnityWebcam/UnityWebcam/SharedImageMemory.cpp b/UnityWebcam/UnityWebcam/SharedImageMemory.cpp deleted file mode 100644 index 59984a5..0000000 --- a/UnityWebcam/UnityWebcam/SharedImageMemory.cpp +++ /dev/null @@ -1,116 +0,0 @@ -#include "StdAfx.h" -#include "SharedImageMemory.h" -#include -#include - -namespace mray -{ - -SharedImageMemory::SharedImageMemory(const wchar_t* memName, const wchar_t* writeEventName, const wchar_t* readEventName) -{ - m_pMutex = NULL; - m_hSharedFile = NULL; - m_hWriteEvent = NULL; - m_pSharedBuf = NULL; - m_memName = memName; - m_writeEventName = writeEventName; - m_readEventName = readEventName; -} - -SharedImageMemory::~SharedImageMemory(void) -{ - if(m_pMutex != NULL) { - delete m_pMutex; - m_pMutex = NULL; - } - if(m_hWriteEvent != NULL) { - CloseHandle(m_hWriteEvent); - m_hWriteEvent = NULL; - } - if(m_hSharedFile != NULL) { - CloseHandle(m_hSharedFile); - m_hSharedFile = NULL; - } - m_pSharedBuf = NULL; -} - -HRESULT SharedImageMemory::Send(LONGLONG time, int width, int height, const unsigned char* buffer) -{ - if(buffer == NULL) - return E_POINTER; - - HRESULT hr = Open(); - if (hr != S_OK) - return hr; - - { - CriticalSection cs(m_pMutex); - int32_t imageSize = width * height*3 ; - int32_t bufSize = imageSize + sizeof(BufferHeader); - if(m_pSharedBuf->maxSize < bufSize) { - return E_UNEXPECTED; - } - m_pSharedBuf->size = bufSize; - BufferHeader* pDesc = (BufferHeader*) m_pSharedBuf->bufferPtr; - pDesc->timestamp = time; - pDesc->width = width; - pDesc->height = height; - unsigned char* pSharedData = m_pSharedBuf->bufferPtr + sizeof(BufferHeader); - memcpy(pSharedData, buffer, imageSize); - } - SetEvent(m_hWriteEvent); - return S_OK; -} -std::string GetLastErrorAsString() -{ - //Get the error message, if any. - DWORD errorMessageID = ::GetLastError(); - if (errorMessageID == 0) - return std::string(); //No error message has been recorded - - LPSTR messageBuffer = nullptr; - int32_t size = FormatMessageA(FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_IGNORE_INSERTS, - NULL, errorMessageID, MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT), (LPSTR)&messageBuffer, 0, NULL); - - std::string message(messageBuffer, size); - - //Free the buffer. - LocalFree(messageBuffer); - - return message; -} - -HRESULT SharedImageMemory::Open() -{ - DWORD err=0; - if(m_hWriteEvent == NULL) { - m_hWriteEvent = OpenEvent(EVENT_MODIFY_STATE, FALSE, m_writeEventName.c_str()); - if(m_hWriteEvent == NULL) { - return S_FALSE; - } - } - if(m_hSharedFile == NULL) { - m_hSharedFile = OpenFileMapping(FILE_MAP_WRITE, FALSE, m_memName.c_str()); - if (m_hSharedFile == NULL) { - return S_FALSE; - } - - m_pSharedBuf = (SharedMemHeader*)MapViewOfFile(m_hSharedFile, FILE_MAP_WRITE, 0, 0, 0); - - if(m_pSharedBuf == NULL) { - return E_UNEXPECTED; - } - } - if(m_pMutex == NULL) { - HRESULT hr = S_OK; - m_pMutex = new SharedMutex(m_readEventName.c_str(), false, & hr); - if (FAILED(hr)) { - delete m_pMutex; - m_pMutex = NULL; - return S_FALSE; - } - } - return S_OK; -} - -} \ No newline at end of file diff --git a/UnityWebcam/UnityWebcam/SharedImageMemory.h b/UnityWebcam/UnityWebcam/SharedImageMemory.h deleted file mode 100644 index e6e7c7a..0000000 --- a/UnityWebcam/UnityWebcam/SharedImageMemory.h +++ /dev/null @@ -1,37 +0,0 @@ -#ifndef __SHAREDIMAGEMEMORY__ -#define __SHAREDIMAGEMEMORY__ - -#include -class SharedMutex; - - -namespace mray -{ - -class SharedImageMemory -{ -public: - - SharedImageMemory(const wchar_t* memName, const wchar_t* writeEventName, const wchar_t* readEventName); - - virtual ~SharedImageMemory(void); - - virtual HRESULT Send(LONGLONG time, int width, int height, const unsigned char* buffer); - -private: - - HRESULT Open(); - std::wstring m_memName; - std::wstring m_writeEventName; - std::wstring m_readEventName; - HANDLE m_hWriteEvent; - SharedMutex* m_pMutex; - HANDLE m_hSharedFile; - SharedMemHeader* m_pSharedBuf; - -}; - -} - - -#endif diff --git a/UnityWebcam/UnityWebcam/SharedImageWrapper.cpp b/UnityWebcam/UnityWebcam/SharedImageWrapper.cpp deleted file mode 100644 index cc14051..0000000 --- a/UnityWebcam/UnityWebcam/SharedImageWrapper.cpp +++ /dev/null @@ -1,46 +0,0 @@ -#include "stdafx.h" -#include "SharedImageWrapper.h" - -#include - -using namespace std; - -namespace mray -{ - -SharedImageWrapper::SharedImageWrapper() { - totalTime = 0; - m_sender = new SharedImageMemory(CS_SHARED_Base_PATH, CS_EVENT_Base_WRITE, CS_EVENT_Base_READ); - _start = std::chrono::system_clock::now(); -} - -SharedImageWrapper::~SharedImageWrapper() -{ - delete m_sender; -} -bool SharedImageWrapper::Ready() -{ - auto now = std::chrono::system_clock::now(); - auto diff = now - _prev; - long long diffInt = std::chrono::duration_cast(diff).count(); - if (diffInt < 1000 / 30) - return false; - return true; -} - - -bool SharedImageWrapper::SendImage(const unsigned char* data, int width, int height) { - - if (!Ready()) - return false; - auto now = std::chrono::system_clock::now(); - _prev = now; - long long diffInt = std::chrono::duration_cast(now - _start).count(); - - //push the captured data to directshow filter - HRESULT hr = m_sender->Send(diffInt, width, height, data); - - return true; -} - -} \ No newline at end of file diff --git a/UnityWebcam/UnityWebcam/SharedImageWrapper.h b/UnityWebcam/UnityWebcam/SharedImageWrapper.h deleted file mode 100644 index 5e36844..0000000 --- a/UnityWebcam/UnityWebcam/SharedImageWrapper.h +++ /dev/null @@ -1,24 +0,0 @@ -#ifndef HELLOLIB_H__ -#define HELLOLIB_H__ - -#include "SharedImageMemory.h" -#include - -namespace mray -{ - -class SharedImageWrapper { -private: - long long totalTime; - std::chrono::system_clock::time_point _prev, _start; - SharedImageMemory* m_sender; -public: - SharedImageWrapper(); - virtual ~SharedImageWrapper(); - bool SendImage(const unsigned char* data, int width, int height); - bool Ready(); -}; -} - - -#endif \ No newline at end of file diff --git a/UnityWebcam/UnityWebcam/UnityAPI.cpp b/UnityWebcam/UnityWebcam/UnityAPI.cpp deleted file mode 100644 index d2dcdf7..0000000 --- a/UnityWebcam/UnityWebcam/UnityAPI.cpp +++ /dev/null @@ -1,30 +0,0 @@ - - -#include "stdafx.h" -#include "UnityAPI.h" -#include "UnityTextureWrapper.h" - -using namespace mray; - - -extern "C" UNITY_INTERFACE_EXPORT void* CreateTextureWrapper() -{ - UnityTextureWrapper* w = new UnityTextureWrapper(); - return w; -} -extern "C" UNITY_INTERFACE_EXPORT void DeleteTextureWrapper(void* wrapper) -{ - UnityTextureWrapper* w = static_cast(wrapper); - if (!w) - return; - delete w; -} -extern "C" UNITY_INTERFACE_EXPORT bool SendTexture(void* wrapper, void* TextureID) -{ - UnityTextureWrapper* w = static_cast(wrapper); - if (!w) - return false; - - return w->SendImage(TextureID); - -} diff --git a/UnityWebcam/UnityWebcam/UnityAPI.h b/UnityWebcam/UnityWebcam/UnityAPI.h deleted file mode 100644 index 745920a..0000000 --- a/UnityWebcam/UnityWebcam/UnityAPI.h +++ /dev/null @@ -1,12 +0,0 @@ - -#ifndef __UNITYAPI__ -#define __UNITYAPI__ - -#include "IUnityInterface.h" - -extern "C" UNITY_INTERFACE_EXPORT void* CreateTextureWrapper(); -extern "C" UNITY_INTERFACE_EXPORT void DeleteTextureWrapper(void* wrapper); -extern "C" UNITY_INTERFACE_EXPORT bool SendTexture(void* wrapper,void* TextureID); - - -#endif diff --git a/UnityWebcam/UnityWebcam/UnityGraphicsDevice.cpp b/UnityWebcam/UnityWebcam/UnityGraphicsDevice.cpp deleted file mode 100644 index 4ba3408..0000000 --- a/UnityWebcam/UnityWebcam/UnityGraphicsDevice.cpp +++ /dev/null @@ -1,91 +0,0 @@ -// Check out http://docs.unity3d.com/Documentation/Manual/NativePluginInterface.html -// for additional documentation about this process. - -#include "stdafx.h" -#include "IUnityGraphics.h" -#include "IUnityInterface.h" - -void* g_GraphicsDevice = 0; -int g_GraphicsDeviceType = -1; -#if SUPPORT_D3D9 -IDirect3DDevice9* g_D3D9GraphicsDevice = 0; -#endif -#if SUPPORT_D3D11 -ID3D11Device* g_D3D11GraphicsDevice = 0; -#endif - -static void DebugLog (const char* str) -{ -#if UNITY_WIN - OutputDebugStringA (str); -#else - printf ("%s", str); -#endif -} - -// If exported by a plugin, this function will be called when graphics device is created, destroyed, -// and before and after it is reset (ie, resolution changed). -extern "C" void UNITY_INTERFACE_EXPORT UnitySetGraphicsDevice( void* device, int deviceType, int eventType ) -{ - // Assign default values. - g_GraphicsDevice = 0; - g_GraphicsDeviceType = -1; - - switch (eventType) - { - case kUnityGfxDeviceEventInitialize: - case kUnityGfxDeviceEventAfterReset: - { - g_GraphicsDevice = device; - g_GraphicsDeviceType = deviceType; - - switch (g_GraphicsDeviceType) - { -#if SUPPORT_D3D9 - case kGfxRendererD3D9: - { - DebugLog ("Set D3D9 graphics device\n"); - g_D3D9GraphicsDevice = (IDirect3DDevice9*)g_GraphicsDevice; - break; - } -#endif - case kUnityGfxRendererD3D11: - { - DebugLog ("Set D3D11 graphics device\n"); - g_D3D11GraphicsDevice = (ID3D11Device*)g_GraphicsDevice; - break; - } - case kUnityGfxRendererOpenGL: - { - DebugLog ("Set OpenGL graphics device\n"); - break; - } - } - break; - } - case kUnityGfxDeviceEventBeforeReset: - { - break; - } - case kUnityGfxDeviceEventShutdown: - { - break; - } - } -} - -// If exported by a plugin, this function will be called for GL.IssuePluginEvent script calls. -// The function will be called on a rendering thread; note that when multithreaded rendering is used, -// the rendering thread WILL BE DIFFERENT from the thread that all scripts & other game logic happens! -// You have to ensure any synchronization with other plugin script calls is properly done by you. -extern "C" void UNITY_INTERFACE_EXPORT UnityRenderEvent ( int eventID ) -{ - -} - - -void* GetBufferPtrFromNativePtr( void* _NativePtr ) -{ - - return 0; -} \ No newline at end of file diff --git a/UnityWebcam/UnityWebcam/UnityHelpers.cpp b/UnityWebcam/UnityWebcam/UnityHelpers.cpp deleted file mode 100644 index d90c518..0000000 --- a/UnityWebcam/UnityWebcam/UnityHelpers.cpp +++ /dev/null @@ -1,164 +0,0 @@ - - -#include "stdafx.h" -#include "UnityHelpers.h" - -#include -#include "IUnityGraphics.h" - -using namespace mray; - -FuncPtr Debug; -FuncFloatRetPtr GetEngineTimePtr; - -void LogMessage(const std::string& msg, ELogLevel level) -{ - std::string m; - if (level == ELL_INFO) - m = "Info: "; - if (level == ELL_WARNING) - m = "Warning: "; - if (level == ELL_SUCCESS) - m = "Success: "; - if (level == ELL_ERROR) - m = "Error: "; - - m += msg; -#if UNITY_WIN - OutputDebugStringA(m.c_str()); -#else - printf("%s", m.c_str()); -#endif - LogManager::Instance()->LogMessage(m); -// if (Debug) -// Debug(m.c_str()); -} -float GetEngineTime() -{ - if (GetEngineTimePtr) - { - return GetEngineTimePtr(); - } - return 0; -} -extern "C" UNITY_INTERFACE_EXPORT void mray_SetDebugFunction(FuncPtr f) -{ - Debug = f; -} -extern "C" UNITY_INTERFACE_EXPORT void mray_SetGetEngineTime(FuncFloatRetPtr f) -{ - GetEngineTimePtr = f; -} - -LogManager* LogManager::s_instance=0; -LogManager* LogManager::Instance() -{ - if (!s_instance) - { - s_instance = new LogManager(); - } - return s_instance; -} - -LogManager::LogManager() -{ - fileName = "UnityWebcameraLog.txt"; - m_logFile = fopen(fileName.c_str(), "w"); - fclose(m_logFile); - m_logFile = 0; -} -LogManager::~LogManager() -{ - fclose(m_logFile); -} -void LogManager::LogMessage(const std::string& msg) -{ - m_logFile = fopen(fileName.c_str(), "a"); - fprintf(m_logFile, "%s\n", msg.c_str()); - fclose(m_logFile); - m_logFile = 0; -} - -void ReadImage(int TexID) -{ -} - - -void BlitImage( void* _TextureNativePtr, int _UnityTextureWidth, int _UnityTextureHeight) -{ - - if ( !_TextureNativePtr) - return; - - - -#if SUPPORT_D3D9 - // D3D9 case - if (g_GraphicsDeviceType == kGfxRendererD3D9) - { - // Update native texture from code - if (_TextureNativePtr) - { - IDirect3DTexture9* d3dtex = (IDirect3DTexture9*)_TextureNativePtr; - D3DSURFACE_DESC desc; - d3dtex->GetLevelDesc(0, &desc); - D3DLOCKED_RECT lr; - d3dtex->LockRect(0, &lr, nullptr, 0); - - //uchar* data = new uchar[desc.Width*desc.Height * 4]; - - //memcpy((unsigned char*)lr.pBits, ifo->imageData, desc.Width*desc.Height * 3); - CopyToTexture(ifo, (uchar*)lr.pBits,ifo->format); - - d3dtex->UnlockRect(0); - //delete [] data; - } - } -#endif - -#if SUPPORT_D3D11 - // D3D11 case - if (g_GraphicsDeviceType == kUnityGfxRendererD3D11) - { - ID3D11DeviceContext* ctx = nullptr; - g_D3D11GraphicsDevice->GetImmediateContext(&ctx); - - // update native texture from code - if (_TextureNativePtr) - { - ID3D11Texture2D* d3dtex = (ID3D11Texture2D*)_TextureNativePtr; - D3D11_TEXTURE2D_DESC desc; - d3dtex->GetDesc(&desc); - //ctx->UpdateSubresource(d3dtex, 0, nullptr, ifo->imageData, desc.Width * 3, 0); - - uchar* data = 0; - int pitch = 0; - - ctx->UpdateSubresource(d3dtex, 0, nullptr, data, pitch, 0); - //delete[] data; - - } - - ctx->Release(); - } -#endif - - -#if SUPPORT_OPENGL - // OpenGL case - if (g_GraphicsDeviceType == kUnityGfxRendererOpenGL) - { - // update native texture from code - if (_TextureNativePtr) - { - GLuint gltex = (GLuint)(int32_t)(_TextureNativePtr); - glBindTexture(GL_TEXTURE_2D, gltex); - int texWidth, texHeight; - glGetTexLevelParameteriv(GL_TEXTURE_2D, 0, GL_TEXTURE_WIDTH, &texWidth); - glGetTexLevelParameteriv(GL_TEXTURE_2D, 0, GL_TEXTURE_HEIGHT, &texHeight); - glTexSubImage2D(GL_TEXTURE_2D, 0, 0, 0, texWidth, texHeight, GL_RGB, GL_UNSIGNED_BYTE, 0); - - } - } -#endif -} \ No newline at end of file diff --git a/UnityWebcam/UnityWebcam/UnityHelpers.h b/UnityWebcam/UnityWebcam/UnityHelpers.h deleted file mode 100644 index 90e4df2..0000000 --- a/UnityWebcam/UnityWebcam/UnityHelpers.h +++ /dev/null @@ -1,41 +0,0 @@ - - -#ifndef __UNITYHELPERS__ -#define __UNITYHELPERS__ - -#include -#include -#include "mTypes.h" -#include "IUnityInterface.h" - -enum ELogLevel{ - ELL_INFO, - ELL_SUCCESS, - ELL_WARNING, - ELL_ERROR -}; - -extern void LogMessage(const std::string& msg, ELogLevel level); -extern float GetEngineTime(); -extern void BlitImage( void* _TextureNativePtr, int _UnityTextureWidth, int _UnityTextureHeight); - - -typedef void(*FuncPtr)(const char*); -typedef float(*FuncFloatRetPtr)(); - - -extern "C" class UNITY_INTERFACE_EXPORT LogManager -{ - static LogManager* s_instance;; - FILE* m_logFile; - std::string fileName; -public: - LogManager(); - ~LogManager(); - void LogMessage(const std::string& msg); - - static LogManager* Instance(); -}; - - -#endif diff --git a/UnityWebcam/UnityWebcam/UnityTextureWrapper.cpp b/UnityWebcam/UnityWebcam/UnityTextureWrapper.cpp deleted file mode 100644 index ed5ea97..0000000 --- a/UnityWebcam/UnityWebcam/UnityTextureWrapper.cpp +++ /dev/null @@ -1,154 +0,0 @@ - -#include "stdafx.h" -#include "UnityTextureWrapper.h" - -#include "UnityHelpers.h" - -namespace mray -{ -UnityTextureWrapper::UnityTextureWrapper() -{ - _data = 0; - _width = 0; - _height = 0; -#if SUPPORT_D3D11 - textureBuf = 0; -#endif -} -UnityTextureWrapper::~UnityTextureWrapper() -{ -#if SUPPORT_D3D11 - if (textureBuf) - textureBuf->Release(); -#endif - if (_data) - delete[] _data; - _data = 0; -} - -bool UnityTextureWrapper::SendImage(void* _TextureNativePtr) -{ - if (!_TextureNativePtr) - return false; - - if (!Ready()) - return false; - -#if SUPPORT_D3D9 - // D3D9 case - if (g_GraphicsDeviceType == kUnityGfxRendererD3D9) - { - } -#endif - -#if SUPPORT_D3D11 - // D3D11 case - if (g_GraphicsDeviceType == kUnityGfxRendererD3D11) - { - ID3D11DeviceContext* ctx = nullptr; - g_D3D11GraphicsDevice->GetImmediateContext(&ctx); - - // update native texture from code - if (_TextureNativePtr) - { - ID3D11Texture2D* d3dtex = (ID3D11Texture2D*)_TextureNativePtr; - - D3D11_TEXTURE2D_DESC desc; - d3dtex->GetDesc(&desc); - - if (_width != desc.Width || _height != desc.Height) - { - if (textureBuf) - { - textureBuf->Release(); - textureBuf = 0; - } - D3D11_TEXTURE2D_DESC textureDesc; - ZeroMemory(&textureDesc, sizeof(textureDesc)); - textureDesc.Width = desc.Width; - textureDesc.Height = desc.Height; - textureDesc.MipLevels = 1; - textureDesc.ArraySize = 1; - textureDesc.Format = desc.Format; - textureDesc.SampleDesc.Count = 1; - textureDesc.SampleDesc.Quality = 0; - textureDesc.Usage = D3D11_USAGE_STAGING; - textureDesc.CPUAccessFlags = D3D11_CPU_ACCESS_READ; - textureDesc.MiscFlags = 0; - g_D3D11GraphicsDevice->CreateTexture2D(&textureDesc, NULL, &textureBuf); - _width = desc.Width; - _height = desc.Height; - - if (_data) - delete[] _data; - _data = new uchar[_width*_height * 3]; - - } - ctx->CopyResource(textureBuf, d3dtex); - D3D11_MAPPED_SUBRESOURCE mapResource; - HRESULT hr = ctx->Map(textureBuf, 0, D3D11_MAP_READ, NULL, &mapResource); - if (SUCCEEDED(hr)) - { - if (desc.Format == DXGI_FORMAT_R8G8B8A8_UNORM|| - desc.Format == DXGI_FORMAT_R8G8B8A8_UNORM_SRGB) - { - uchar*src = (uchar*)mapResource.pData; - uchar*ptr = (uchar*)_data; - int count= _width*_height * 4; - - while (count>0) - { - for (int i = 0; i < _width; ++i){ - ptr[0] = src[i * 4 + 0]; - ptr[1] = src[i * 4 + 1]; - ptr[2] = src[i * 4 + 2]; - ptr += 3; - count -= 4; - } - src += mapResource.RowPitch; - } - ctx->Unmap(textureBuf, 0); - } - else{ - } - SharedImageWrapper::SendImage((const uchar*)_data, _width, _height); - } - - - } - - } -#endif - -#if SUPPORT_OPENGL - // OpenGL case - if (g_GraphicsDeviceType == kUnityGfxRendererOpenGL) - { - // update native texture from code - if (_TextureNativePtr) - { - GLuint gltex = (GLuint)(int32_t)(_TextureNativePtr); - glBindTexture(GL_TEXTURE_2D, gltex); - int width, height; - glGetTexLevelParameteriv(GL_TEXTURE_2D, 0, GL_TEXTURE_WIDTH, &width); - glGetTexLevelParameteriv(GL_TEXTURE_2D, 0, GL_TEXTURE_HEIGHT, &height); - - if (width != _width || height != _height) - { - delete[] _data; - _data = new uchar[width*height*3]; - _width = width; - _height = height; - } - - glReadPixels(0, 0, width, height, GL_RGB, GL_UNSIGNED_BYTE, _data); - - return SharedImageWrapper::SendImage((const uchar*)_data, width, height); - } - } -#endif - return false; -} - -} - diff --git a/UnityWebcam/UnityWebcam/UnityTextureWrapper.h b/UnityWebcam/UnityWebcam/UnityTextureWrapper.h deleted file mode 100644 index ca0cd72..0000000 --- a/UnityWebcam/UnityWebcam/UnityTextureWrapper.h +++ /dev/null @@ -1,32 +0,0 @@ - - -#ifndef __UNITYTEXTUREWRAPPER__ -#define __UNITYTEXTUREWRAPPER__ - -#include "SharedImageWrapper.h" -#include "IUnityGraphics.h" - -namespace mray -{ -class UNITY_INTERFACE_EXPORT UnityTextureWrapper :public SharedImageWrapper -{ -protected: - void* _data; - int _width; - int _height; - -#if SUPPORT_D3D11 - ID3D11Texture2D* textureBuf; -#endif -public: - UnityTextureWrapper(); - ~UnityTextureWrapper(); - - bool SendImage(void* _TextureNativePtr); - -}; - -} - - -#endif diff --git a/UnityWebcam/UnityWebcam/UnityWebcam.cpp b/UnityWebcam/UnityWebcam/UnityWebcam.cpp deleted file mode 100644 index 15f611f..0000000 --- a/UnityWebcam/UnityWebcam/UnityWebcam.cpp +++ /dev/null @@ -1,6 +0,0 @@ -// UnityWebcam.cpp : Defines the exported functions for the DLL application. -// - -#include "stdafx.h" - - diff --git a/UnityWebcam/UnityWebcam/UnityWebcam.vcxproj b/UnityWebcam/UnityWebcam/UnityWebcam.vcxproj deleted file mode 100644 index f0d6e7d..0000000 --- a/UnityWebcam/UnityWebcam/UnityWebcam.vcxproj +++ /dev/null @@ -1,207 +0,0 @@ - - - - - Debug - Win32 - - - Debug - x64 - - - Release - Win32 - - - Release - x64 - - - - {727D3AC5-27B5-4288-A475-7A471ECD71B7} - Win32Proj - UnityWebcam - - - - DynamicLibrary - true - v120 - Unicode - - - DynamicLibrary - true - v120 - Unicode - - - DynamicLibrary - false - v120 - true - Unicode - - - DynamicLibrary - false - v120 - true - Unicode - - - - - - - - - - - - - - - - - - - true - ..\$(Platform)\$(Configuration)\ - - - true - ..\$(Platform)\$(Configuration)\ - ..\$(Platform)\$(Configuration)\ - - - false - ..\$(Platform)\$(Configuration)\ - ..\$(Platform)\$(Configuration)\ - - - false - ..\$(Platform)\$(Configuration)\ - ..\$(Platform)\$(Configuration)\ - - - - Use - Level3 - Disabled - Win32;_DEBUG;_WINDOWS;_USRDLL;UNITYWEBCAM_EXPORTS;%(PreprocessorDefinitions) - ..\UnityCamService\;%(AdditionalIncludeDirectories) - - - Windows - true - ..\UnityCapturePlugin\$(Platform)\$(Configuration)\ - opengl32.lib;%(AdditionalDependencies) - - - - - Use - Level3 - Disabled - Win32;_DEBUG;_WINDOWS;_USRDLL;UNITYWEBCAM_EXPORTS;%(PreprocessorDefinitions) - ..\UnityCamService\;%(AdditionalIncludeDirectories) - - - Windows - true - ..\UnityCapturePlugin\$(Platform)\$(Configuration)\ - opengl32.lib;%(AdditionalDependencies) - - - - - Level3 - Use - MaxSpeed - true - true - Win32;NDEBUG;_WINDOWS;_USRDLL;UNITYWEBCAM_EXPORTS;%(PreprocessorDefinitions) - ..\UnityCamService\;%(AdditionalIncludeDirectories) - - - Windows - true - true - true - opengl32.lib;%(AdditionalDependencies) - ..\UnityCapturePlugin\$(Platform)\$(Configuration)\ - - - - - Level3 - Use - MaxSpeed - true - true - Win32;NDEBUG;_WINDOWS;_USRDLL;UNITYWEBCAM_EXPORTS;%(PreprocessorDefinitions) - ..\UnityCamService\;%(AdditionalIncludeDirectories) - - - Windows - true - true - true - opengl32.lib;%(AdditionalDependencies) - ..\UnityCapturePlugin\$(Platform)\$(Configuration)\ - - - - - - - - - - - - - - - - - - - - - - false - false - - - - - false - false - - - - - - - - - - - Create - Create - Create - Create - - - - - - - - - - - \ No newline at end of file diff --git a/UnityWebcam/UnityWebcam/UnityWebcam.vcxproj.filters b/UnityWebcam/UnityWebcam/UnityWebcam.vcxproj.filters deleted file mode 100644 index d002c28..0000000 --- a/UnityWebcam/UnityWebcam/UnityWebcam.vcxproj.filters +++ /dev/null @@ -1,93 +0,0 @@ - - - - - {4FC737F1-C7A5-4376-A066-2A32D752A2FF} - cpp;c;cc;cxx;def;odl;idl;hpj;bat;asm;asmx - - - {93995380-89BD-4b04-88EB-625FBE52EBFB} - h;hh;hpp;hxx;hm;inl;inc;xsd - - - {67DA6AB6-F800-4c08-8B7A-83BB121AAD01} - rc;ico;cur;bmp;dlg;rc2;rct;bin;rgs;gif;jpg;jpeg;jpe;resx;tiff;tif;png;wav;mfcribbon-ms - - - - - - - - Header Files - - - Header Files - - - Source Files - - - Source Files - - - Source Files - - - Source Files - - - Source Files - - - Source Files - - - Source Files - - - Source Files - - - Source Files - - - Source Files - - - - - Source Files - - - Source Files - - - Source Files - - - Source Files - - - Source Files - - - Source Files - - - Source Files - - - Source Files - - - Header Files - - - Source Files - - - Source Files - - - \ No newline at end of file diff --git a/UnityWebcam/UnityWebcam/dllmain.cpp b/UnityWebcam/UnityWebcam/dllmain.cpp deleted file mode 100644 index 69b5891..0000000 --- a/UnityWebcam/UnityWebcam/dllmain.cpp +++ /dev/null @@ -1,19 +0,0 @@ -// dllmain.cpp : Defines the entry point for the DLL application. -#include "stdafx.h" - -BOOL APIENTRY DllMain( HMODULE hModule, - DWORD ul_reason_for_call, - LPVOID lpReserved - ) -{ - switch (ul_reason_for_call) - { - case DLL_PROCESS_ATTACH: - case DLL_THREAD_ATTACH: - case DLL_THREAD_DETACH: - case DLL_PROCESS_DETACH: - break; - } - return TRUE; -} - diff --git a/UnityWebcam/UnityWebcam/mTypes.h b/UnityWebcam/UnityWebcam/mTypes.h deleted file mode 100644 index 2dd3525..0000000 --- a/UnityWebcam/UnityWebcam/mTypes.h +++ /dev/null @@ -1,41 +0,0 @@ - - -#ifndef ___m_typeS___ -#define ___m_typeS___ - -namespace mray{ - -typedef unsigned char uchar; -typedef signed char schar; - -typedef unsigned int uint; -typedef signed int sint; - -typedef unsigned short ushort; -typedef signed short sshort; - -typedef unsigned long ulong; -typedef unsigned long long ullong; -typedef signed long slong; - -typedef uchar utf8; -typedef uint utf32; - - -#define mT(X) (X) - -#ifdef UNICODE - -typedef wchar_t mchar; - -#else - -typedef char mchar; - -#endif - -};//mray - - - -#endif \ No newline at end of file diff --git a/UnityWebcam/UnityWebcam/stdafx.cpp b/UnityWebcam/UnityWebcam/stdafx.cpp deleted file mode 100644 index 3a1c688..0000000 --- a/UnityWebcam/UnityWebcam/stdafx.cpp +++ /dev/null @@ -1,8 +0,0 @@ -// stdafx.cpp : source file that includes just the standard includes -// UnityWebcam.pch will be the pre-compiled header -// stdafx.obj will contain the pre-compiled type information - -#include "stdafx.h" - -// TODO: reference any additional headers you need in STDAFX.H -// and not in this file diff --git a/UnityWebcam/UnityWebcam/stdafx.h b/UnityWebcam/UnityWebcam/stdafx.h deleted file mode 100644 index a2d80b2..0000000 --- a/UnityWebcam/UnityWebcam/stdafx.h +++ /dev/null @@ -1,26 +0,0 @@ -// stdafx.h : include file for standard system include files, -// or project specific include files that are used frequently, but -// are changed infrequently -// - -#pragma once - -#include "targetver.h" - -#define WIN32_LEAN_AND_MEAN // Exclude rarely-used stuff from Windows headers -// Windows Header Files: -#include - - - -// TODO: reference additional headers your program requires here - -#include -#include -#include -#include -#include -#include -#include -#include -#include \ No newline at end of file diff --git a/UnityWebcam/UnityWebcam/targetver.h b/UnityWebcam/UnityWebcam/targetver.h deleted file mode 100644 index 87c0086..0000000 --- a/UnityWebcam/UnityWebcam/targetver.h +++ /dev/null @@ -1,8 +0,0 @@ -#pragma once - -// Including SDKDDKVer.h defines the highest available Windows platform. - -// If you wish to build your application for a previous Windows platform, include WinSDKVer.h and -// set the _WIN32_WINNT macro to the platform you wish to support before including SDKDDKVer.h. - -#include diff --git a/UnityWebcam/Win32/Debug/UnityCamService.dll b/UnityWebcam/Win32/Debug/UnityCamService.dll deleted file mode 100644 index 31ba266..0000000 Binary files a/UnityWebcam/Win32/Debug/UnityCamService.dll and /dev/null differ diff --git a/UnityWebcam/Win32/Debug/UnityCamService.exp b/UnityWebcam/Win32/Debug/UnityCamService.exp deleted file mode 100644 index 6a9281f..0000000 Binary files a/UnityWebcam/Win32/Debug/UnityCamService.exp and /dev/null differ diff --git a/UnityWebcam/Win32/Debug/UnityCamService.lib b/UnityWebcam/Win32/Debug/UnityCamService.lib deleted file mode 100644 index a507a2a..0000000 Binary files a/UnityWebcam/Win32/Debug/UnityCamService.lib and /dev/null differ diff --git a/UnityWebcam/Win32/Debug/UnityCamService.tlog/CL.read.1.tlog b/UnityWebcam/Win32/Debug/UnityCamService.tlog/CL.read.1.tlog deleted file mode 100644 index 4689d25..0000000 Binary files a/UnityWebcam/Win32/Debug/UnityCamService.tlog/CL.read.1.tlog and /dev/null differ diff --git a/UnityWebcam/Win32/Debug/UnityCamService.tlog/CL.write.1.tlog b/UnityWebcam/Win32/Debug/UnityCamService.tlog/CL.write.1.tlog deleted file mode 100644 index ed5ad2c..0000000 Binary files a/UnityWebcam/Win32/Debug/UnityCamService.tlog/CL.write.1.tlog and /dev/null differ diff --git a/UnityWebcam/Win32/Debug/UnityCamService.tlog/UnityCamService.lastbuildstate b/UnityWebcam/Win32/Debug/UnityCamService.tlog/UnityCamService.lastbuildstate deleted file mode 100644 index ca78862..0000000 --- a/UnityWebcam/Win32/Debug/UnityCamService.tlog/UnityCamService.lastbuildstate +++ /dev/null @@ -1,2 +0,0 @@ -#TargetFrameworkVersion=v4.0:PlatformToolSet=v120:EnableManagedIncrementalBuild=false:VCToolArchitecture=Native32Bit -Debug|Win32|D:\Development\GitRepos\UnityCam\UnityWebcam\| diff --git a/UnityWebcam/Win32/Debug/UnityCamService.tlog/UnityCamService.write.1u.tlog b/UnityWebcam/Win32/Debug/UnityCamService.tlog/UnityCamService.write.1u.tlog deleted file mode 100644 index ee5340e..0000000 Binary files a/UnityWebcam/Win32/Debug/UnityCamService.tlog/UnityCamService.write.1u.tlog and /dev/null differ diff --git a/UnityWebcam/Win32/Debug/UnityCamService.tlog/cl.command.1.tlog b/UnityWebcam/Win32/Debug/UnityCamService.tlog/cl.command.1.tlog deleted file mode 100644 index ec137bf..0000000 Binary files a/UnityWebcam/Win32/Debug/UnityCamService.tlog/cl.command.1.tlog and /dev/null differ diff --git a/UnityWebcam/Win32/Debug/UnityCamService.tlog/link.command.1.tlog b/UnityWebcam/Win32/Debug/UnityCamService.tlog/link.command.1.tlog deleted file mode 100644 index 85528d6..0000000 Binary files a/UnityWebcam/Win32/Debug/UnityCamService.tlog/link.command.1.tlog and /dev/null differ diff --git a/UnityWebcam/Win32/Debug/UnityCamService.tlog/link.read.1.tlog b/UnityWebcam/Win32/Debug/UnityCamService.tlog/link.read.1.tlog deleted file mode 100644 index 6bb70f3..0000000 Binary files a/UnityWebcam/Win32/Debug/UnityCamService.tlog/link.read.1.tlog and /dev/null differ diff --git a/UnityWebcam/Win32/Debug/UnityCamService.tlog/link.write.1.tlog b/UnityWebcam/Win32/Debug/UnityCamService.tlog/link.write.1.tlog deleted file mode 100644 index fb59b6d..0000000 Binary files a/UnityWebcam/Win32/Debug/UnityCamService.tlog/link.write.1.tlog and /dev/null differ diff --git a/UnityWebcam/Win32/Debug/vc120.idb b/UnityWebcam/Win32/Debug/vc120.idb deleted file mode 100644 index 8f0133d..0000000 Binary files a/UnityWebcam/Win32/Debug/vc120.idb and /dev/null differ diff --git a/UnityWebcam/Win32/Release/UnityCamService.dll b/UnityWebcam/Win32/Release/UnityCamService.dll deleted file mode 100644 index 830a34d..0000000 Binary files a/UnityWebcam/Win32/Release/UnityCamService.dll and /dev/null differ diff --git a/UnityWebcam/Win32/Release/UnityCamService.exp b/UnityWebcam/Win32/Release/UnityCamService.exp deleted file mode 100644 index 6a56d81..0000000 Binary files a/UnityWebcam/Win32/Release/UnityCamService.exp and /dev/null differ diff --git a/UnityWebcam/Win32/Release/UnityCamService.lib b/UnityWebcam/Win32/Release/UnityCamService.lib deleted file mode 100644 index 5ffb6ef..0000000 Binary files a/UnityWebcam/Win32/Release/UnityCamService.lib and /dev/null differ diff --git a/UnityWebcam/Win32/Release/UnityCamService.tlog/CL.read.1.tlog b/UnityWebcam/Win32/Release/UnityCamService.tlog/CL.read.1.tlog deleted file mode 100644 index 811a541..0000000 Binary files a/UnityWebcam/Win32/Release/UnityCamService.tlog/CL.read.1.tlog and /dev/null differ diff --git a/UnityWebcam/Win32/Release/UnityCamService.tlog/CL.write.1.tlog b/UnityWebcam/Win32/Release/UnityCamService.tlog/CL.write.1.tlog deleted file mode 100644 index 6843357..0000000 Binary files a/UnityWebcam/Win32/Release/UnityCamService.tlog/CL.write.1.tlog and /dev/null differ diff --git a/UnityWebcam/Win32/Release/UnityCamService.tlog/UnityCamService.lastbuildstate b/UnityWebcam/Win32/Release/UnityCamService.tlog/UnityCamService.lastbuildstate deleted file mode 100644 index 9e7d7fe..0000000 --- a/UnityWebcam/Win32/Release/UnityCamService.tlog/UnityCamService.lastbuildstate +++ /dev/null @@ -1,2 +0,0 @@ -#TargetFrameworkVersion=v4.0:PlatformToolSet=v120:EnableManagedIncrementalBuild=false:VCToolArchitecture=Native32Bit -Release|Win32|D:\Development\GitRepos\UnityCam\UnityWebcam\| diff --git a/UnityWebcam/Win32/Release/UnityCamService.tlog/UnityCamService.write.1u.tlog b/UnityWebcam/Win32/Release/UnityCamService.tlog/UnityCamService.write.1u.tlog deleted file mode 100644 index d71fc04..0000000 Binary files a/UnityWebcam/Win32/Release/UnityCamService.tlog/UnityCamService.write.1u.tlog and /dev/null differ diff --git a/UnityWebcam/Win32/Release/UnityCamService.tlog/cl.command.1.tlog b/UnityWebcam/Win32/Release/UnityCamService.tlog/cl.command.1.tlog deleted file mode 100644 index 32ae45a..0000000 Binary files a/UnityWebcam/Win32/Release/UnityCamService.tlog/cl.command.1.tlog and /dev/null differ diff --git a/UnityWebcam/Win32/Release/UnityCamService.tlog/link.command.1.tlog b/UnityWebcam/Win32/Release/UnityCamService.tlog/link.command.1.tlog deleted file mode 100644 index b9ab8c2..0000000 Binary files a/UnityWebcam/Win32/Release/UnityCamService.tlog/link.command.1.tlog and /dev/null differ diff --git a/UnityWebcam/Win32/Release/UnityCamService.tlog/link.read.1.tlog b/UnityWebcam/Win32/Release/UnityCamService.tlog/link.read.1.tlog deleted file mode 100644 index c840ee5..0000000 Binary files a/UnityWebcam/Win32/Release/UnityCamService.tlog/link.read.1.tlog and /dev/null differ diff --git a/UnityWebcam/Win32/Release/UnityCamService.tlog/link.write.1.tlog b/UnityWebcam/Win32/Release/UnityCamService.tlog/link.write.1.tlog deleted file mode 100644 index ab090e5..0000000 Binary files a/UnityWebcam/Win32/Release/UnityCamService.tlog/link.write.1.tlog and /dev/null differ diff --git a/UnityWebcam/Win32/Release/UnityWebcam.dll b/UnityWebcam/Win32/Release/UnityWebcam.dll deleted file mode 100644 index 107412e..0000000 Binary files a/UnityWebcam/Win32/Release/UnityWebcam.dll and /dev/null differ diff --git a/UnityWebcam/Win32/Release/UnityWebcam.lib b/UnityWebcam/Win32/Release/UnityWebcam.lib deleted file mode 100644 index c4e5ee4..0000000 Binary files a/UnityWebcam/Win32/Release/UnityWebcam.lib and /dev/null differ diff --git a/UnityWebcam/Win32/Release/UnityWebcam.tlog/CL.read.1.tlog b/UnityWebcam/Win32/Release/UnityWebcam.tlog/CL.read.1.tlog deleted file mode 100644 index aa8da80..0000000 Binary files a/UnityWebcam/Win32/Release/UnityWebcam.tlog/CL.read.1.tlog and /dev/null differ diff --git a/UnityWebcam/Win32/Release/UnityWebcam.tlog/CL.write.1.tlog b/UnityWebcam/Win32/Release/UnityWebcam.tlog/CL.write.1.tlog deleted file mode 100644 index 09d58ff..0000000 Binary files a/UnityWebcam/Win32/Release/UnityWebcam.tlog/CL.write.1.tlog and /dev/null differ diff --git a/UnityWebcam/Win32/Release/UnityWebcam.tlog/UnityWebcam.lastbuildstate b/UnityWebcam/Win32/Release/UnityWebcam.tlog/UnityWebcam.lastbuildstate deleted file mode 100644 index e2bb1c5..0000000 --- a/UnityWebcam/Win32/Release/UnityWebcam.tlog/UnityWebcam.lastbuildstate +++ /dev/null @@ -1,2 +0,0 @@ -#TargetFrameworkVersion=v4.0:PlatformToolSet=v120:EnableManagedIncrementalBuild=false:VCToolArchitecture=Native32Bit -Release|Win32|C:\Users\Torso\Documents\Development\GITRepos\UnityCam\UnityWebcam\| diff --git a/UnityWebcam/Win32/Release/UnityWebcam.tlog/UnityWebcam.write.1u.tlog b/UnityWebcam/Win32/Release/UnityWebcam.tlog/UnityWebcam.write.1u.tlog deleted file mode 100644 index 3efae50..0000000 Binary files a/UnityWebcam/Win32/Release/UnityWebcam.tlog/UnityWebcam.write.1u.tlog and /dev/null differ diff --git a/UnityWebcam/Win32/Release/UnityWebcam.tlog/cl.command.1.tlog b/UnityWebcam/Win32/Release/UnityWebcam.tlog/cl.command.1.tlog deleted file mode 100644 index 4a8e07a..0000000 Binary files a/UnityWebcam/Win32/Release/UnityWebcam.tlog/cl.command.1.tlog and /dev/null differ diff --git a/UnityWebcam/Win32/Release/UnityWebcam.tlog/link.command.1.tlog b/UnityWebcam/Win32/Release/UnityWebcam.tlog/link.command.1.tlog deleted file mode 100644 index 94b10e7..0000000 Binary files a/UnityWebcam/Win32/Release/UnityWebcam.tlog/link.command.1.tlog and /dev/null differ diff --git a/UnityWebcam/Win32/Release/UnityWebcam.tlog/link.read.1.tlog b/UnityWebcam/Win32/Release/UnityWebcam.tlog/link.read.1.tlog deleted file mode 100644 index 0775c3e..0000000 Binary files a/UnityWebcam/Win32/Release/UnityWebcam.tlog/link.read.1.tlog and /dev/null differ diff --git a/UnityWebcam/Win32/Release/UnityWebcam.tlog/link.write.1.tlog b/UnityWebcam/Win32/Release/UnityWebcam.tlog/link.write.1.tlog deleted file mode 100644 index 2893c37..0000000 Binary files a/UnityWebcam/Win32/Release/UnityWebcam.tlog/link.write.1.tlog and /dev/null differ diff --git a/UnityWebcam/x64/Debug/UnityCamService.exp b/UnityWebcam/x64/Debug/UnityCamService.exp deleted file mode 100644 index c3bc755..0000000 Binary files a/UnityWebcam/x64/Debug/UnityCamService.exp and /dev/null differ diff --git a/UnityWebcam/x64/Debug/UnityCamService.tlog/CL.read.1.tlog b/UnityWebcam/x64/Debug/UnityCamService.tlog/CL.read.1.tlog deleted file mode 100644 index 144a51e..0000000 Binary files a/UnityWebcam/x64/Debug/UnityCamService.tlog/CL.read.1.tlog and /dev/null differ diff --git a/UnityWebcam/x64/Debug/UnityCamService.tlog/CL.write.1.tlog b/UnityWebcam/x64/Debug/UnityCamService.tlog/CL.write.1.tlog deleted file mode 100644 index 9a7c517..0000000 Binary files a/UnityWebcam/x64/Debug/UnityCamService.tlog/CL.write.1.tlog and /dev/null differ diff --git a/UnityWebcam/x64/Debug/UnityCamService.tlog/UnityCamService.lastbuildstate b/UnityWebcam/x64/Debug/UnityCamService.tlog/UnityCamService.lastbuildstate deleted file mode 100644 index 7f3936a..0000000 --- a/UnityWebcam/x64/Debug/UnityCamService.tlog/UnityCamService.lastbuildstate +++ /dev/null @@ -1,2 +0,0 @@ -#TargetFrameworkVersion=v4.0:PlatformToolSet=v120:EnableManagedIncrementalBuild=false:VCToolArchitecture=Native32Bit -Debug|x64|D:\Development\GitRepos\UnityCam\UnityWebcam\| diff --git a/UnityWebcam/x64/Debug/UnityCamService.tlog/UnityCamService.write.1u.tlog b/UnityWebcam/x64/Debug/UnityCamService.tlog/UnityCamService.write.1u.tlog deleted file mode 100644 index 8df4599..0000000 Binary files a/UnityWebcam/x64/Debug/UnityCamService.tlog/UnityCamService.write.1u.tlog and /dev/null differ diff --git a/UnityWebcam/x64/Debug/UnityCamService.tlog/cl.command.1.tlog b/UnityWebcam/x64/Debug/UnityCamService.tlog/cl.command.1.tlog deleted file mode 100644 index dffd2ad..0000000 Binary files a/UnityWebcam/x64/Debug/UnityCamService.tlog/cl.command.1.tlog and /dev/null differ diff --git a/UnityWebcam/x64/Debug/UnityCamService.tlog/link.command.1.tlog b/UnityWebcam/x64/Debug/UnityCamService.tlog/link.command.1.tlog deleted file mode 100644 index a691414..0000000 Binary files a/UnityWebcam/x64/Debug/UnityCamService.tlog/link.command.1.tlog and /dev/null differ diff --git a/UnityWebcam/x64/Debug/UnityCamService.tlog/link.read.1.tlog b/UnityWebcam/x64/Debug/UnityCamService.tlog/link.read.1.tlog deleted file mode 100644 index 83d1385..0000000 Binary files a/UnityWebcam/x64/Debug/UnityCamService.tlog/link.read.1.tlog and /dev/null differ diff --git a/UnityWebcam/x64/Debug/UnityCamService.tlog/link.write.1.tlog b/UnityWebcam/x64/Debug/UnityCamService.tlog/link.write.1.tlog deleted file mode 100644 index 50e2869..0000000 Binary files a/UnityWebcam/x64/Debug/UnityCamService.tlog/link.write.1.tlog and /dev/null differ diff --git a/UnityWebcam/x64/Debug/UnityWebcam.dll b/UnityWebcam/x64/Debug/UnityWebcam.dll deleted file mode 100644 index 520c4e5..0000000 Binary files a/UnityWebcam/x64/Debug/UnityWebcam.dll and /dev/null differ diff --git a/UnityWebcam/x64/Debug/UnityWebcam.exp b/UnityWebcam/x64/Debug/UnityWebcam.exp deleted file mode 100644 index 4a69b30..0000000 Binary files a/UnityWebcam/x64/Debug/UnityWebcam.exp and /dev/null differ diff --git a/UnityWebcam/x64/Debug/UnityWebcam.lib b/UnityWebcam/x64/Debug/UnityWebcam.lib deleted file mode 100644 index 94f0958..0000000 Binary files a/UnityWebcam/x64/Debug/UnityWebcam.lib and /dev/null differ diff --git a/UnityWebcam/x64/Debug/UnityWebcam.tlog/CL.read.1.tlog b/UnityWebcam/x64/Debug/UnityWebcam.tlog/CL.read.1.tlog deleted file mode 100644 index 6e062f8..0000000 Binary files a/UnityWebcam/x64/Debug/UnityWebcam.tlog/CL.read.1.tlog and /dev/null differ diff --git a/UnityWebcam/x64/Debug/UnityWebcam.tlog/CL.write.1.tlog b/UnityWebcam/x64/Debug/UnityWebcam.tlog/CL.write.1.tlog deleted file mode 100644 index e0ae7e2..0000000 Binary files a/UnityWebcam/x64/Debug/UnityWebcam.tlog/CL.write.1.tlog and /dev/null differ diff --git a/UnityWebcam/x64/Debug/UnityWebcam.tlog/UnityWebcam.lastbuildstate b/UnityWebcam/x64/Debug/UnityWebcam.tlog/UnityWebcam.lastbuildstate deleted file mode 100644 index 7f3936a..0000000 --- a/UnityWebcam/x64/Debug/UnityWebcam.tlog/UnityWebcam.lastbuildstate +++ /dev/null @@ -1,2 +0,0 @@ -#TargetFrameworkVersion=v4.0:PlatformToolSet=v120:EnableManagedIncrementalBuild=false:VCToolArchitecture=Native32Bit -Debug|x64|D:\Development\GitRepos\UnityCam\UnityWebcam\| diff --git a/UnityWebcam/x64/Debug/UnityWebcam.tlog/UnityWebcam.write.1u.tlog b/UnityWebcam/x64/Debug/UnityWebcam.tlog/UnityWebcam.write.1u.tlog deleted file mode 100644 index af03bc3..0000000 Binary files a/UnityWebcam/x64/Debug/UnityWebcam.tlog/UnityWebcam.write.1u.tlog and /dev/null differ diff --git a/UnityWebcam/x64/Debug/UnityWebcam.tlog/cl.command.1.tlog b/UnityWebcam/x64/Debug/UnityWebcam.tlog/cl.command.1.tlog deleted file mode 100644 index 7eeb4b8..0000000 Binary files a/UnityWebcam/x64/Debug/UnityWebcam.tlog/cl.command.1.tlog and /dev/null differ diff --git a/UnityWebcam/x64/Debug/UnityWebcam.tlog/link.command.1.tlog b/UnityWebcam/x64/Debug/UnityWebcam.tlog/link.command.1.tlog deleted file mode 100644 index 751f401..0000000 Binary files a/UnityWebcam/x64/Debug/UnityWebcam.tlog/link.command.1.tlog and /dev/null differ diff --git a/UnityWebcam/x64/Debug/UnityWebcam.tlog/link.read.1.tlog b/UnityWebcam/x64/Debug/UnityWebcam.tlog/link.read.1.tlog deleted file mode 100644 index 08decc1..0000000 Binary files a/UnityWebcam/x64/Debug/UnityWebcam.tlog/link.read.1.tlog and /dev/null differ diff --git a/UnityWebcam/x64/Debug/UnityWebcam.tlog/link.write.1.tlog b/UnityWebcam/x64/Debug/UnityWebcam.tlog/link.write.1.tlog deleted file mode 100644 index b9fb86b..0000000 Binary files a/UnityWebcam/x64/Debug/UnityWebcam.tlog/link.write.1.tlog and /dev/null differ diff --git a/UnityWebcam/x64/Debug/vc120.idb b/UnityWebcam/x64/Debug/vc120.idb deleted file mode 100644 index acfff4e..0000000 Binary files a/UnityWebcam/x64/Debug/vc120.idb and /dev/null differ diff --git a/UnityWebcam/x64/Release/UnityCamService.exp b/UnityWebcam/x64/Release/UnityCamService.exp deleted file mode 100644 index b691ee0..0000000 Binary files a/UnityWebcam/x64/Release/UnityCamService.exp and /dev/null differ diff --git a/UnityWebcam/x64/Release/UnityCamService.tlog/UnityCamService.lastbuildstate b/UnityWebcam/x64/Release/UnityCamService.tlog/UnityCamService.lastbuildstate deleted file mode 100644 index 42ab9f0..0000000 --- a/UnityWebcam/x64/Release/UnityCamService.tlog/UnityCamService.lastbuildstate +++ /dev/null @@ -1,2 +0,0 @@ -#TargetFrameworkVersion=v4.0:PlatformToolSet=v120:EnableManagedIncrementalBuild=false:VCToolArchitecture=Native32Bit -Release|x64|D:\Development\GitRepos\UnityCam\UnityWebcam\| diff --git a/UnityWebcam/x64/Release/UnityCamService.tlog/UnityCamService.write.1u.tlog b/UnityWebcam/x64/Release/UnityCamService.tlog/UnityCamService.write.1u.tlog deleted file mode 100644 index 78f0096..0000000 Binary files a/UnityWebcam/x64/Release/UnityCamService.tlog/UnityCamService.write.1u.tlog and /dev/null differ diff --git a/UnityWebcam/x64/Release/UnityCamService.tlog/cl.command.1.tlog b/UnityWebcam/x64/Release/UnityCamService.tlog/cl.command.1.tlog deleted file mode 100644 index 6515a64..0000000 Binary files a/UnityWebcam/x64/Release/UnityCamService.tlog/cl.command.1.tlog and /dev/null differ diff --git a/UnityWebcam/x64/Release/UnityCamService.tlog/cl.read.1.tlog b/UnityWebcam/x64/Release/UnityCamService.tlog/cl.read.1.tlog deleted file mode 100644 index 7c3fe25..0000000 Binary files a/UnityWebcam/x64/Release/UnityCamService.tlog/cl.read.1.tlog and /dev/null differ diff --git a/UnityWebcam/x64/Release/UnityCamService.tlog/cl.write.1.tlog b/UnityWebcam/x64/Release/UnityCamService.tlog/cl.write.1.tlog deleted file mode 100644 index 2aceb09..0000000 Binary files a/UnityWebcam/x64/Release/UnityCamService.tlog/cl.write.1.tlog and /dev/null differ diff --git a/UnityWebcam/x64/Release/UnityCamService.tlog/link.command.1.tlog b/UnityWebcam/x64/Release/UnityCamService.tlog/link.command.1.tlog deleted file mode 100644 index 3e20cb6..0000000 Binary files a/UnityWebcam/x64/Release/UnityCamService.tlog/link.command.1.tlog and /dev/null differ diff --git a/UnityWebcam/x64/Release/UnityCamService.tlog/link.read.1.tlog b/UnityWebcam/x64/Release/UnityCamService.tlog/link.read.1.tlog deleted file mode 100644 index 309b1de..0000000 Binary files a/UnityWebcam/x64/Release/UnityCamService.tlog/link.read.1.tlog and /dev/null differ diff --git a/UnityWebcam/x64/Release/UnityCamService.tlog/link.write.1.tlog b/UnityWebcam/x64/Release/UnityCamService.tlog/link.write.1.tlog deleted file mode 100644 index f44d79e..0000000 Binary files a/UnityWebcam/x64/Release/UnityCamService.tlog/link.write.1.tlog and /dev/null differ diff --git a/UnityWebcam/x64/Release/UnityWebcam.dll b/UnityWebcam/x64/Release/UnityWebcam.dll deleted file mode 100644 index 218eb2b..0000000 Binary files a/UnityWebcam/x64/Release/UnityWebcam.dll and /dev/null differ diff --git a/UnityWebcam/x64/Release/UnityWebcam.exp b/UnityWebcam/x64/Release/UnityWebcam.exp deleted file mode 100644 index 994e842..0000000 Binary files a/UnityWebcam/x64/Release/UnityWebcam.exp and /dev/null differ diff --git a/UnityWebcam/x64/Release/UnityWebcam.lib b/UnityWebcam/x64/Release/UnityWebcam.lib deleted file mode 100644 index ed87d2e..0000000 Binary files a/UnityWebcam/x64/Release/UnityWebcam.lib and /dev/null differ diff --git a/UnityWebcam/x64/Release/UnityWebcam.tlog/CL.read.1.tlog b/UnityWebcam/x64/Release/UnityWebcam.tlog/CL.read.1.tlog deleted file mode 100644 index 2cc007f..0000000 Binary files a/UnityWebcam/x64/Release/UnityWebcam.tlog/CL.read.1.tlog and /dev/null differ diff --git a/UnityWebcam/x64/Release/UnityWebcam.tlog/CL.write.1.tlog b/UnityWebcam/x64/Release/UnityWebcam.tlog/CL.write.1.tlog deleted file mode 100644 index 62f7713..0000000 Binary files a/UnityWebcam/x64/Release/UnityWebcam.tlog/CL.write.1.tlog and /dev/null differ diff --git a/UnityWebcam/x64/Release/UnityWebcam.tlog/UnityWebcam.lastbuildstate b/UnityWebcam/x64/Release/UnityWebcam.tlog/UnityWebcam.lastbuildstate deleted file mode 100644 index d3867f4..0000000 --- a/UnityWebcam/x64/Release/UnityWebcam.tlog/UnityWebcam.lastbuildstate +++ /dev/null @@ -1,2 +0,0 @@ -#TargetFrameworkVersion=v4.0:PlatformToolSet=v120:EnableManagedIncrementalBuild=false:VCToolArchitecture=Native32Bit -Release|x64|C:\Users\Torso\Documents\Development\GITRepos\UnityCam\UnityWebcam\| diff --git a/UnityWebcam/x64/Release/UnityWebcam.tlog/UnityWebcam.write.1u.tlog b/UnityWebcam/x64/Release/UnityWebcam.tlog/UnityWebcam.write.1u.tlog deleted file mode 100644 index 4a688ba..0000000 Binary files a/UnityWebcam/x64/Release/UnityWebcam.tlog/UnityWebcam.write.1u.tlog and /dev/null differ diff --git a/UnityWebcam/x64/Release/UnityWebcam.tlog/cl.command.1.tlog b/UnityWebcam/x64/Release/UnityWebcam.tlog/cl.command.1.tlog deleted file mode 100644 index 6443de4..0000000 Binary files a/UnityWebcam/x64/Release/UnityWebcam.tlog/cl.command.1.tlog and /dev/null differ diff --git a/UnityWebcam/x64/Release/UnityWebcam.tlog/link.command.1.tlog b/UnityWebcam/x64/Release/UnityWebcam.tlog/link.command.1.tlog deleted file mode 100644 index 9155eed..0000000 Binary files a/UnityWebcam/x64/Release/UnityWebcam.tlog/link.command.1.tlog and /dev/null differ diff --git a/UnityWebcam/x64/Release/UnityWebcam.tlog/link.read.1.tlog b/UnityWebcam/x64/Release/UnityWebcam.tlog/link.read.1.tlog deleted file mode 100644 index 014ef77..0000000 Binary files a/UnityWebcam/x64/Release/UnityWebcam.tlog/link.read.1.tlog and /dev/null differ diff --git a/UnityWebcam/x64/Release/UnityWebcam.tlog/link.write.1.tlog b/UnityWebcam/x64/Release/UnityWebcam.tlog/link.write.1.tlog deleted file mode 100644 index 5f41e57..0000000 Binary files a/UnityWebcam/x64/Release/UnityWebcam.tlog/link.write.1.tlog and /dev/null differ