Skip to main content
DirectShow video in ogre texture         A small code snippet for playing videos on Ogre materials / textures using DirectShow

This is a small video reproduction code snippet using Direct Show.

The idea is simple: A small code snippet for playing videos on Ogre materials / textures. Not a full-blown video player but a class that is small enough that other coders can adapt it to their needs. It's also useful for seeing how you manage to do realtime writing in textures in Ogre (check the updateMovieTexture() method implementation for that). For more complex video reproduction code (that is also portable), check in the add-ons page.

Here is the original forums thread on this code snippet. Please post your ideas, suggestions and bug reports there.

Thank you, and enjoy it!

Code

First, the code and then some extra information about its use:

UtilsOgreDshow.h:

Copy to clipboard
// Ogre Dshow: small wrapper for video reproduction in Ogre, using Direct Show 9. /* Wrapper for video reproduction using Direct Show in the Ogre 3d engine. Coded by H. Hernán Moraldo from Moraldo Games www.hernan.moraldo.com.ar/pmenglish/field.php -------------------- Copyright (c) 2007 Horacio Hernan Moraldo 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. */ #ifndef __FILE_UTILSOGREDSHOW_INCLUDED #define __FILE_UTILSOGREDSHOW_INCLUDED #define __FILE_UTILSOGREDSHOW_VERSION "11-18-2008a" #include <Ogre.h> #include <OgreVector2.h> namespace OgreUtils { struct DirectShowData; /// A class for playing movies in an ogre texture class DirectShowMovieTexture { public: // cons / decons /// Initializes the dshow object, and creates a texture with the given dimensions. /** If dontModifyDimensions is false, the system might modify the texture dimensions by setting them to the nearest power of two (useful for old computers). (Ie, 1024x512 if the original dimensions were 640x480). */ DirectShowMovieTexture(int width, int height, bool dontModifyDimensions=true); /// Destroys the dshow object virtual ~DirectShowMovieTexture(); // basic movie methods /// Loads a given movie /** /param moviePath A string telling the full path of the file to be loaded. /param horizontalMirroring A bool telling whether the video should be rendered as if seen through a mirror, or not. */ void loadMovie(const Ogre::String& moviePath, bool horizontalMirroring=false); /// Obtains the dimensions of the current movie Ogre::Vector2 getMovieDimensions(); /// Unloads the current movie void unloadMovie(); // methods for movie control /// Pauses the current movie void pauseMovie(); /// Starts playing the current movie void playMovie(); /// Makes the current movie rewind void rewindMovie(); /// Stops the current movie void stopMovie(); /// Is the latest video put to play, now playing? /** (This is an old implementation of mine; I guess I should re-check this) */ bool isPlayingMovie(); // methods on movie texture /// Obtain the ogre texture where the movie is rendered Ogre::TexturePtr getMovieTexture(); /// Render a movie frame in the ogre texture void updateMovieTexture(); protected: /// Texture where to render the movie Ogre::TexturePtr mTexture; /// Real texture width Ogre::Real mTexWidth; /// Real texture height Ogre::Real mTexHeight; /// Direct Show specific data DirectShowData* dsdata; /// Do we do horizontal mirroring by software? bool mHorizontalMirroring; /// Clean the full texture (paint it all black) void cleanTextureContents(); }; } #endif // __FILE_UTILSOGREDSHOW_INCLUDED


UtilsOgreDshow_private.h:

Copy to clipboard
/// Do not include this file directly, always use UtilsOgreDshow.h instead. // Ogre Dshow: small wrapper for video reproduction in Ogre, using Direct Show 9. /* Wrapper for video reproduction using Direct Show in the Ogre 3d engine. Coded by H. Hernán Moraldo from Moraldo Games www.hernan.moraldo.com.ar/pmenglish/field.php -------------------- Copyright (c) 2007 Horacio Hernan Moraldo 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. */ #ifndef __FILE_UTILSOGREDSHOW_PRIVATE_INCLUDED #define __FILE_UTILSOGREDSHOW_PRIVATE_INCLUDED #include <dshow.h> #include <Qedit.h>// for sample grabber #include <windows.h> namespace OgreUtils { struct DirectShowData { /// Graph object IGraphBuilder *pGraph; /// Media control object IMediaControl *pControl; /// Media event object IMediaEvent *pEvent; /// Grabber filter IBaseFilter *pGrabberF; /// Grabber object ISampleGrabber *pGrabber; /// Interface for seeking object IMediaSeeking *pSeeking; /// Window interface /** Useful for some configuration */ IVideoWindow *pWindow; /// Video output width int videoWidth; /// Video output height int videoHeight; }; /// Util function for converting C strings to wide strings /** (as needed for path in directshow). */ WCHAR* util_convertCStringToWString(const char* string); } #endif // __FILE_UTILSOGREDSHOW_PRIVATE_INCLUDED


UtilsOgreDshow.cpp:

Copy to clipboard
// Ogre Dshow: small wrapper for video reproduction in Ogre, using Direct Show 9. /* Wrapper for video reproduction using Direct Show in the Ogre 3d engine. Coded by H. Hernán Moraldo from Moraldo Games www.hernan.moraldo.com.ar/pmenglish/field.php -------------------- Copyright (c) 2007 Horacio Hernan Moraldo 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 "UtilsOgreDshow.h" #include "UtilsOgreDshow_private.h" #include <OgreStringConverter.h> #include <dshow.h> namespace OgreUtils { DirectShowMovieTexture::DirectShowMovieTexture(int width, int height, bool dontModifyDimensions) { // 1) CREATE DSDATA dsdata=new DirectShowData; // 2) CREATE TEXTURE // get width and height to the next square of two int twoSquared; mTexWidth=0; mTexHeight=0; for (twoSquared=2; mTexWidth==0 || mTexHeight==0; twoSquared*=2) { if (mTexWidth==0 && twoSquared>=width) mTexWidth=twoSquared; if (mTexHeight==0 && twoSquared>=height) mTexHeight=twoSquared; } if (dontModifyDimensions) { // back to the original dimensions mTexWidth=width; mTexHeight=height; } // log it Ogre::LogManager::getSingletonPtr()->logMessage( Ogre::String("[DSHOW] Creating texture with dimensions ")+ Ogre::StringConverter::toString(mTexWidth)+"x"+ Ogre::StringConverter::toString(mTexHeight)+"."); // first, create the texture we are going to use mTexture=Ogre::TextureManager::getSingleton().createManual( "DirectShowManualTexture",// name Ogre::ResourceGroupManager::DEFAULT_RESOURCE_GROUP_NAME, Ogre::TEX_TYPE_2D,// texture type mTexWidth, mTexHeight, 0,// number of mipmaps Ogre::PF_BYTE_BGRA,// pixel format Ogre::TU_DYNAMIC_WRITE_ONLY_DISCARDABLE// usage ); // 3) INITIALIZE DIRECT SHOW HRESULT hr; hr=CoInitialize(NULL); if (FAILED(hr)) throw("[DSHOW] Error in co initialize"); // initialize all pointers dsdata->pGraph=0; dsdata->pControl=0; dsdata->pEvent=0; dsdata->pGrabberF=0; dsdata->pGrabber=0; dsdata->pSeeking=0; dsdata->pWindow=0; } DirectShowMovieTexture::~DirectShowMovieTexture() { // 1) DEINITIALIZE DIRECT SHOW unloadMovie(); CoUninitialize(); // 2) DESTROY TEXTURE Ogre::TextureManager::getSingleton().remove(mTexture->getName()); // 3) DELETE DSDATA delete dsdata; } void DirectShowMovieTexture::loadMovie( const Ogre::String& moviePath, bool horizontalMirroring) { HRESULT hr; // log it! Ogre::LogManager::getSingletonPtr()->logMessage( Ogre::String("[DSHOW] Loading movie named '")+ moviePath+"'."); // destroy previous movie objects (if any) unloadMovie(); // create filter graph and get interfaces hr=CoCreateInstance(CLSID_FilterGraph, NULL, CLSCTX_INPROC_SERVER, IID_IGraphBuilder, (void**) &dsdata->pGraph); if (FAILED(hr)) throw("[DSHOW] Error in creating graph"); hr=dsdata->pGraph->QueryInterface(IID_IMediaControl, (void**) & dsdata->pControl); if (FAILED(hr)) throw("[DSHOW] Error in querying media control"); hr=dsdata->pGraph->QueryInterface(IID_IMediaEvent, (void**) & dsdata->pEvent); if (FAILED(hr)) throw("[DSHOW] Error in querying media event"); hr=dsdata->pGraph->QueryInterface(IID_IMediaSeeking, (void**) & dsdata->pSeeking); if (FAILED(hr)) throw("[DSHOW] Error in querying seeking interface"); // create sample grabber hr=CoCreateInstance(CLSID_SampleGrabber, NULL, CLSCTX_INPROC_SERVER, IID_IBaseFilter, (void**)&dsdata->pGrabberF); if (FAILED(hr)) throw("[DSHOW] Error in creating sample grabber"); // add sample grabber to the graph hr=dsdata->pGraph->AddFilter(dsdata->pGrabberF, L"Sample Grabber"); if (FAILED(hr)) throw("[DSHOW] Error in adding sample grabber to the graph"); // get sample grabber object dsdata->pGrabberF->QueryInterface(IID_ISampleGrabber, (void**)&dsdata->pGrabber); // set sample grabber media type AM_MEDIA_TYPE mt; ZeroMemory(&mt, sizeof(AM_MEDIA_TYPE)); mt.majortype = MEDIATYPE_Video; mt.subtype = MEDIASUBTYPE_RGB24; mt.formattype = FORMAT_VideoInfo; hr=dsdata->pGrabber->SetMediaType(&mt); if (FAILED(hr)) throw("[DSHOW] Error in setting sample grabber media type"); //--------------- Seregvan's modification IBaseFilter* srcFilter; WCHAR* filepath = util_convertCStringToWString(moviePath.c_str()); hr = dsdata->pGraph->AddSourceFilter(filepath, L"Source", &srcFilter); if(FAILED(hr)) throw ("[DSHOW] Unsupported media type!"); // Connect the src and grabber hr = ConnectFilters(dsdata->pGraph, srcFilter, dsdata->pGrabberF); if(FAILED(hr)) throw ("[DSHOW] Unsupported media type!"); IBaseFilter * render; hr = CoCreateInstance(CLSID_NullRenderer, NULL, CLSCTX_INPROC_SERVER, IID_IBaseFilter, (void**)&render); if(FAILED(hr)) throw ("[DSHOW] Unsupported media type!"); dsdata->pGraph->AddFilter(render, L"Render"); hr = ConnectFilters(dsdata->pGraph, dsdata->pGrabberF, render); if(FAILED(hr)) throw ("[DSHOW] Can't create render!"); //--------------- End of modification // open the file! WCHAR* filepath=util_convertCStringToWString(moviePath.c_str()); hr=dsdata->pGraph->RenderFile(filepath, NULL); if (FAILED(hr)) throw("[DSHOW] Error opening video file!"); // disable auto show // (wouldn't be needed if we used the null renderer) hr=dsdata->pGraph->QueryInterface(IID_IVideoWindow, (void**) & dsdata->pWindow); if (FAILED(hr)) throw("[DSHOW] Error getting video window interface"); dsdata->pWindow->put_AutoShow(OAFALSE); // get video information AM_MEDIA_TYPE mtt; hr=dsdata->pGrabber->GetConnectedMediaType(&mtt); if (FAILED(hr)) throw("[DSHOW] Error getting connected media type info"); VIDEOINFOHEADER *vih = (VIDEOINFOHEADER*) mtt.pbFormat; dsdata->videoWidth=vih->bmiHeader.biWidth; dsdata->videoHeight=vih->bmiHeader.biHeight; // microsoft's help version of free media type if (mtt.cbFormat != 0) { CoTaskMemFree((PVOID)mtt.pbFormat); mtt.cbFormat = 0; mtt.pbFormat = NULL; } if (mtt.pUnk != NULL) { mtt.pUnk->Release(); mtt.pUnk = NULL; } // log it Ogre::LogManager::getSingletonPtr()->logMessage( Ogre::String("[DSHOW] -> This movie has dimensions: ")+ Ogre::StringConverter::toString(dsdata->videoWidth)+"x"+ Ogre::StringConverter::toString(dsdata->videoHeight)+"."); // set sampling options dsdata->pGrabber->SetOneShot(FALSE); dsdata->pGrabber->SetBufferSamples(TRUE); // set some basic data mHorizontalMirroring=horizontalMirroring; // clean the texture, so that it's ready for rendering this video cleanTextureContents(); } Ogre::Vector2 DirectShowMovieTexture::getMovieDimensions() { return Ogre::Vector2(dsdata->videoWidth, dsdata->videoHeight); } void DirectShowMovieTexture::unloadMovie() { if (dsdata->pGraph==0) return; if (dsdata->pGrabber!=0) { dsdata->pGrabber->Release(); dsdata->pGrabber=0; } if (dsdata->pGrabberF!=0) { dsdata->pGrabberF->Release(); dsdata->pGrabberF=0; } if (dsdata->pWindow!=0) { dsdata->pWindow->Release(); dsdata->pWindow=0; } if (dsdata->pSeeking!=0) { dsdata->pSeeking->Release(); dsdata->pSeeking=0; } if (dsdata->pControl!=0) { dsdata->pControl->Release(); dsdata->pControl=0; } if (dsdata->pEvent!=0) { dsdata->pEvent->Release(); dsdata->pEvent=0; } if (dsdata->pGraph!=0) { dsdata->pGraph->Release(); dsdata->pGraph=0; } } void DirectShowMovieTexture::pauseMovie() { // pause! if (dsdata->pControl) dsdata->pControl->Pause(); } void DirectShowMovieTexture::playMovie() { // play! if (dsdata->pControl) dsdata->pControl->Run(); } void DirectShowMovieTexture::rewindMovie() { if (!dsdata->pSeeking) return; // rewind! LONGLONG p1=0; LONGLONG p2=0; dsdata->pSeeking->SetPositions( &p1, AM_SEEKING_AbsolutePositioning, &p2, AM_SEEKING_NoPositioning); } void DirectShowMovieTexture::stopMovie() { // stop! if (dsdata->pControl) dsdata->pControl->Stop(); } Ogre::TexturePtr DirectShowMovieTexture::getMovieTexture() { return mTexture; } void DirectShowMovieTexture::updateMovieTexture() { HRESULT hr; unsigned int i, idx; int x, y; BYTE* bmpTmp; // only do this if there is a graph that has been set up if (!dsdata->pGraph) return; // Find the required buffer size. long cbBuffer = 0; hr = dsdata->pGrabber->GetCurrentBuffer(&cbBuffer, NULL); if (cbBuffer<=0) { // nothing to do here yet return; } char *pBuffer = new char[cbBuffer]; if (!pBuffer) { // out of memory! throw("[DSHOW] Out of memory or empty buffer"); } hr = dsdata->pGrabber->GetCurrentBuffer(&cbBuffer, (long*)pBuffer); if (hr==E_INVALIDARG || hr==VFW_E_NOT_CONNECTED || hr==VFW_E_WRONG_STATE) { // we aren't buffering samples yet, do nothing delete[] pBuffer; return; } if (FAILED(hr)) throw("[DSHOW] Failed at GetCurrentBuffer!"); // OGRE BEGIN // OGRE TEXTURE LOCK // get the texture pixel buffer int texw=mTexture->getWidth(); int texh=mTexture->getHeight(); Ogre::HardwarePixelBufferSharedPtr pixelBuffer = mTexture->getBuffer(); bmpTmp=(BYTE*)pBuffer; // lock the pixel buffer and get a pixel box pixelBuffer->lock(Ogre::HardwareBuffer::HBL_DISCARD); const Ogre::PixelBox& pixelBox = pixelBuffer->getCurrentLock(); Ogre::uint8* pDest = static_cast<Ogre::uint8*>(pixelBox.data); // FILL! // check for mirroring... bool shouldBeMirrored=mHorizontalMirroring; if (shouldBeMirrored){ x=dsdata->videoWidth-1; y=dsdata->videoHeight-1; }else{ x=0; y=dsdata->videoHeight-1; } // go set all bits... for (i=0; i<(dsdata->videoWidth*dsdata->videoHeight*3); i+=3){ idx=(x*4)+y*pixelBox.rowPitch*4; // paint pDest[idx]=bmpTmp[i];//b pDest[idx+1]=bmpTmp[i+1];//g pDest[idx+2]=bmpTmp[i+2];//r pDest[idx+3]=255;//a if (shouldBeMirrored){ x--; if (x<0){ x=dsdata->videoWidth-1; y--; if (y<0) y=0; } }else{ x++; if (x>=dsdata->videoWidth){ x=0; y--; if (y<0) y=0; } } } // UNLOCK EVERYTHING! // unlock the pixel buffer pixelBuffer->unlock(); // OGRE END // bye delete[] pBuffer; } void DirectShowMovieTexture::cleanTextureContents() { unsigned int idx; int x, y; // OGRE TEXTURE LOCK // get the texture pixel buffer int texw=mTexture->getWidth(); int texh=mTexture->getHeight(); Ogre::HardwarePixelBufferSharedPtr pixelBuffer = mTexture->getBuffer(); // lock the pixel buffer and get a pixel box pixelBuffer->lock(Ogre::HardwareBuffer::HBL_DISCARD); const Ogre::PixelBox& pixelBox = pixelBuffer->getCurrentLock(); Ogre::uint8* pDest = static_cast<Ogre::uint8*>(pixelBox.data); // FILL! for (x=0, y=0; y<texh; ){ idx=(x*4)+y*pixelBox.rowPitch*4; // paint pDest[idx]=0;//b pDest[idx+1]=0;//g pDest[idx+2]=0;//r pDest[idx+3]=255;//a x++; if (x>=texw) { x=0; y++; } } // UNLOCK EVERYTHING! // unlock the pixel buffer pixelBuffer->unlock(); // OGRE END } bool DirectShowMovieTexture::isPlayingMovie() { OAFilterState pfs; HRESULT hr; if (dsdata->pEvent!=NULL){ long ev, p1, p2; while (E_ABORT!=dsdata->pEvent->GetEvent(&ev, &p1, &p2, 0)){ // check for completion if (ev==EC_COMPLETE) { pauseMovie(); return false; } // release event params hr=dsdata->pEvent->FreeEventParams(ev, p1, p2); if (FAILED(hr)) { pauseMovie(); return false; } } } // get the running state! if (dsdata->pControl!=NULL) { hr=dsdata->pControl->GetState(0, &pfs); if (FAILED(hr)) { pauseMovie(); return false; } return pfs==State_Running; } // it hasn't even been initialized! return false; } WCHAR* util_convertCStringToWString(const char* string) { const int MAX_STRINGZ=500; static WCHAR wtext[MAX_STRINGZ+2]; if (strlen(string)>MAX_STRINGZ) return 0; // convert text to wchar if (MultiByteToWideChar( CP_ACP,// ansi code page 0,// flags string,// orig string -1,// calculate len wtext,// where to put the string MAX_STRINGZ)// maximum allowed path ==0) { throw("[DSHOW] convertCStringToWString failed with no extra error info"); } return wtext; } }

Usage

First, to compile this - if you are using Visual Studio 2003 - you will need to install the Windows 2003 SDK (as DirectShow is in there and does not come bundled with Visual Studio). You get it here.

After that, add Strmiids.lib to the list of libraries you link to. This can be done by adding that filename in your Linker / Input / Additional Dependencies (in Project Properties).

Then, after you have properly initialized Ogre, you create a DirectShowMovieTexture object in your code:

Copy to clipboard
: #include "UtilsOgreDshow.h" OgreUtils::DirectShowMovieTexture* dshowMovieTextureSystem=new OgreUtils::DirectShowMovieTexture(640, 480);


Where I used 640 and 480, you can set any width and height values. Those will be the dimensions used for the texture where all videos played will be rendered to (so they should be always bigger than any of the videos to be played).

Note: There is an optional third parameter for that constructor, that lets the system create textures with dimensions that are different if needed, so that they are always powers of two (which is useful for old computers). In this case, the texture asked to have a size of 640x480, would actually have a size of 1024x512. By default, that parameter is disabled.

Afterwards, you ask it to load a movie. It can play any movie that your Windows Media Player can also deal with (mpeg, avi, divx, whatever).

Copy to clipboard
Ogre::String movieName="C:/videofiles/video.avi"; dshowMovieTextureSystem->loadMovie(movieName);


THe function loadMovie() sets everything up to stream a video. Videos can be played from the hard disk with no regards to their size and definition, as they are directly streamed from the disk (by that, they don't have to be loaded to the RAM, but are directly played from the disk).

At any time, the loadMovie() method can be called again, for loading a new movie.

After that, you can play, stop, pause and rewind the file...

Copy to clipboard
dshowMovieTextureSystem->playMovie(); dshowMovieTextureSystem->pauseMovie(); dshowMovieTextureSystem->stopMovie(); dshowMovieTextureSystem->rewindMovie();


...and also check if it's playing the current movie or not:

Copy to clipboard
bool isPlaying=dshowMovieTextureSystem->isPlayingMovie();


Then, in every frame, you need to ask the system to draw the current playing video to the created texture:

Copy to clipboard
dshowMovieTextureSystem->updateMovieTexture();


Now you have video that is playing in a texture! The last step is now to actually use that texture. To do so, you use the getMovieTexture() method, for example to assign such a texture to a material named MyMaterial (assuming the material has already been loaded, ie: is currently in use in some object):

Copy to clipboard
Ogre::MaterialPtr mat; Ogre::TextureUnitState* tex; Ogre::String materialName="MyMaterial"; if (!Ogre::MaterialManager::getSingleton().resourceExists(materialName)) { throw("Error, material doesn't exist!"); return 0; } mat=Ogre::MaterialManager::getSingleton().getByName(materialName); tex=mat->getTechnique(0)->getPass(0)->getTextureUnitState(0); tex->setTextureName( dshowMovieTextureSystem->getMovieTexture()->getName());


And of course, once you finish using this, don't forget to destroy the object:

Copy to clipboard
delete dshowMovieTextureSystem;


When destroying this, the texture created by dshowMovieTextureSystem will be destroyed. So, you are advised to stop using that texture before the object destruction.

So, some code like this should be proceeded before deleting the dshowMovieTextureSystem object:

Copy to clipboard
Ogre::String materialName="MyMaterial"; if (Ogre::MaterialManager::getSingleton().resourceExists(materialName)) { Ogre::MaterialPtr mat; Ogre::TextureUnitState* tex; mat=Ogre::MaterialManager::getSingleton().getByName(materialName); tex=mat->getTechnique(0)->getPass(0)->getTextureUnitState(0); tex->setTextureName(Ogre::String("")); }


And that's all!

I hope you like it.

Missing header files fix

With the latest release of Windows SDK 7.0 and post DirectX SDK 9 (August 2007), you get the error of missing qedit.h and CVDShowUtil.h. To fix this, replace UtilsOgreDShow_private.h with:

Copy to clipboard
/// Do not include this file directly, always use UtilsOgreDshow.h instead. // Ogre Dshow: small wrapper for video reproduction in Ogre, using Direct Show 9. /* Wrapper for video reproduction using Direct Show in the Ogre 3d engine. Coded by H. Hernán Moraldo from Moraldo Games www.hernan.moraldo.com.ar/pmenglish/field.php -------------------- Copyright (c) 2007 Horacio Hernan Moraldo 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. */ #pragma once #ifndef __FILE_UTILSOGREDSHOW_PRIVATE_INCLUDED #define __FILE_UTILSOGREDSHOW_PRIVATE_INCLUDED //#include <Qedit.h>// for sample grabber #include <dshow.h> #include <WTypes.h> // <hack> // Vite Falcon: Nasty hack to avoid the missing 'qedit.h' #include <windows.h> EXTERN_C const CLSID CLSID_SampleGrabber; class DECLSPEC_UUID("C1F400A0-3F08-11d3-9F0B-006008039E37") SampleGrabber; EXTERN_C const CLSID CLSID_NullRenderer; class DECLSPEC_UUID("C1F400A4-3F08-11d3-9F0B-006008039E37") NullRenderer; EXTERN_C const IID IID_ISampleGrabberCB; MIDL_INTERFACE("0579154A-2B53-4994-B0D0-E773148EFF85") ISampleGrabberCB : public IUnknown { public: virtual HRESULT STDMETHODCALLTYPE SampleCB( double SampleTime, IMediaSample *pSample) = 0; virtual HRESULT STDMETHODCALLTYPE BufferCB( double SampleTime, BYTE *pBuffer, long BufferLen) = 0; }; EXTERN_C const IID IID_ISampleGrabber; MIDL_INTERFACE("6B652FFF-11FE-4fce-92AD-0266B5D7C78F") ISampleGrabber : public IUnknown { public: virtual HRESULT STDMETHODCALLTYPE SetOneShot( BOOL OneShot) = 0; virtual HRESULT STDMETHODCALLTYPE SetMediaType( const AM_MEDIA_TYPE *pType) = 0; virtual HRESULT STDMETHODCALLTYPE GetConnectedMediaType( AM_MEDIA_TYPE *pType) = 0; virtual HRESULT STDMETHODCALLTYPE SetBufferSamples( BOOL BufferThem) = 0; virtual HRESULT STDMETHODCALLTYPE GetCurrentBuffer( /* [out][in] */ long *pBufferSize, /* [out] */ long *pBuffer) = 0; virtual HRESULT STDMETHODCALLTYPE GetCurrentSample( /* [retval][out] */ IMediaSample **ppSample) = 0; virtual HRESULT STDMETHODCALLTYPE SetCallback( ISampleGrabberCB *pCallback, long WhichMethodToCallback) = 0; }; // </hack> namespace OgreUtils { struct DirectShowData { /// Graph object IGraphBuilder *pGraph; /// Media control object IMediaControl *pControl; /// Media event object IMediaEvent *pEvent; /// Grabber filter IBaseFilter *pGrabberF; /// Grabber object ISampleGrabber *pGrabber; /// Interface for seeking object IMediaSeeking *pSeeking; /// Window interface /** Useful for some configuration */ IVideoWindow *pWindow; /// Video output width int videoWidth; /// Video output height int videoHeight; }; /// Util function for converting C strings to wide strings /** (as needed for path in directshow). */ WCHAR* util_convertCStringToWString(const char* string); } #endif // __FILE_UTILSOGREDSHOW_PRIVATE_INCLUDED


Add CVDShowUtil.h as:

Copy to clipboard
/// \file CVDShowUtil.h /// \brief DirectShow utility functions straight out of the DirectX 9 documentation. /// /// These provide easy calls to connect between Direct Show filters and manage /// the memory associated with media type objects. /// #ifndef CVDShowUtil_H_ #define CVDShowUtil_H_ //#include #include <DShow.h>// DirectShow (using DirectX 9.0 for dev) //#include // Sample grabber defines /// GetUnconnectedPin finds an unconnected pin on a filter /// in the desired direction. /// /// \param pFilter - pointer to filter /// \param PinDir - direction of pin (PINDIR_INPUT or PINDIR_OUTPUT) /// \param ppPin - Receives pointer to pin interface /// /// \return HRESULT - S_OK on success /// \sa ConnectFilters(), CVVidCaptureDSWin32 HRESULT GetUnconnectedPin( IBaseFilter *pFilter, PIN_DIRECTION PinDir, IPin **ppPin); /// /// ConnectFilters connects a pin of an upstream filter to the /// downstream filter pDest. /// /// \param pGraph - Filter graph (both filters must be already added) /// \param pOut - Output pin on upstream filter. See GetUnconnectedPin() /// \param pDest - Downstream filter to be connected /// /// \return HRESULT - S_OK on success /// \sa GetUnconnectedPin(), CVVidCaptureDSWin32 HRESULT ConnectFilters( IGraphBuilder *pGraph, IPin *pOut, IBaseFilter *pDest); /// /// DisconnectPins() disconnects any attached filters. /// /// \param pFilter - filter to disconnect /// \return HRESULT - S_OK on success /// HRESULT DisconnectPins(IBaseFilter *pFilter); /// /// ConnectFilters connects two filters together. /// /// \param pGraph - Filter graph (both filters must be already added) /// \param pSrc - Upstream filter /// \param pDest - Downstream filter to be connected /// /// \return HRESULT - S_OK on success /// \sa GetUnconnectedPin(), CVVidCaptureDSWin32 HRESULT ConnectFilters( IGraphBuilder *pGraph, IBaseFilter *pSrc, IBaseFilter *pDest); /// /// LocalFreeMediaType frees the format block of a media type object /// \param mt - reference to media type /// \sa LocalDeleteMediaType void LocalFreeMediaType(AM_MEDIA_TYPE& mt); /// LocalDeleteMediaType frees the format block of a media type object, /// then deletes it. /// \param pmt - pointer to media type /// \sa LocalFreeMediaType void LocalDeleteMediaType(AM_MEDIA_TYPE *pmt); #endif //CVDShowUtil_H_


And finally, add CVDShowUtil.cpp as:

Copy to clipboard
/// \file CVDShowUtil.cpp /// \brief DirectShow utility functions straight out of the DirectX 9.0 documentation. #include "CVDShowUtil.h" // GetUnconnectedPin // Finds an unconnected pin on a filter in the desired direction HRESULT GetUnconnectedPin( IBaseFilter *pFilter, // Pointer to the filter. PIN_DIRECTION PinDir, // Direction of the pin to find. IPin **ppPin) // Receives a pointer to the pin. { *ppPin = 0; IEnumPins *pEnum = 0; IPin *pPin = 0; HRESULT hr = pFilter->EnumPins(&pEnum); if (FAILED(hr)) { return hr; } while (pEnum->Next(1, &pPin, NULL) == S_OK) { PIN_DIRECTION ThisPinDir; pPin->QueryDirection(&ThisPinDir); if (ThisPinDir == PinDir) { IPin *pTmp = 0; hr = pPin->ConnectedTo(&pTmp); if (SUCCEEDED(hr)) // Already connected, not the pin we want. { pTmp->Release(); } else // Unconnected, this is the pin we want. { pEnum->Release(); *ppPin = pPin; return S_OK; } } pPin->Release(); } pEnum->Release(); // Did not find a matching pin. return E_FAIL; } // Disconnect any connections to the filter. HRESULT DisconnectPins(IBaseFilter *pFilter) { IEnumPins *pEnum = 0; IPin *pPin = 0; HRESULT hr = pFilter->EnumPins(&pEnum); if (FAILED(hr)) { return hr; } while (pEnum->Next(1, &pPin, NULL) == S_OK) { pPin->Disconnect(); pPin->Release(); } pEnum->Release(); // Did not find a matching pin. return S_OK; } // ConnectFilters // Connects a pin of an upstream filter to the pDest downstream filter HRESULT ConnectFilters( IGraphBuilder *pGraph, // Filter Graph Manager. IPin *pOut, // Output pin on the upstream filter. IBaseFilter *pDest) // Downstream filter. { if ((pGraph == NULL) || (pOut == NULL) || (pDest == NULL)) { return E_POINTER; } #ifdef debug PIN_DIRECTION PinDir; pOut->QueryDirection(&PinDir); _ASSERTE(PinDir == PINDIR_OUTPUT); #endif // Find an input pin on the downstream filter. IPin *pIn = 0; HRESULT hr = GetUnconnectedPin(pDest, PINDIR_INPUT, &pIn); if (FAILED(hr)) { return hr; } // Try to connect them. hr = pGraph->Connect(pOut, pIn); pIn->Release(); return hr; } // ConnectFilters // Connects two filters HRESULT ConnectFilters( IGraphBuilder *pGraph, IBaseFilter *pSrc, IBaseFilter *pDest) { if ((pGraph == NULL) || (pSrc == NULL) || (pDest == NULL)) { return E_POINTER; } // Find an output pin on the first filter. IPin *pOut = 0; HRESULT hr = GetUnconnectedPin(pSrc, PINDIR_OUTPUT, &pOut); if (FAILED(hr)) { return hr; } hr = ConnectFilters(pGraph, pOut, pDest); pOut->Release(); return hr; } // LocalFreeMediaType // Free the format buffer in the media type void LocalFreeMediaType(AM_MEDIA_TYPE& mt) { if (mt.cbFormat != 0) { CoTaskMemFree((PVOID)mt.pbFormat); mt.cbFormat = 0; mt.pbFormat = NULL; } if (mt.pUnk != NULL) { // Unecessary because pUnk should not be used, but safest. mt.pUnk->Release(); mt.pUnk = NULL; } } // LocalDeleteMediaType // Free the format buffer in the media type, // then delete the MediaType ptr itself void LocalDeleteMediaType(AM_MEDIA_TYPE *pmt) { if (pmt != NULL) { LocalFreeMediaType(*pmt); // See FreeMediaType for the implementation. CoTaskMemFree(pmt); } }


Hope this helps anyone out there with this issue ๐Ÿ˜Š


Alias: DirectShow_video_in_ogre_texture