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:

// 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:

/// 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:

// 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:

:
#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).

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...

dshowMovieTextureSystem->playMovie();
dshowMovieTextureSystem->pauseMovie();
dshowMovieTextureSystem->stopMovie();
dshowMovieTextureSystem->rewindMovie();


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

bool isPlaying=dshowMovieTextureSystem->isPlayingMovie();


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

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):

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:

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:

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:

/// 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:

/// \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:

/// \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

<HR>
Creative Commons Copyright -- Some rights reserved.


THE WORK (AS DEFINED BELOW) IS PROVIDED UNDER THE TERMS OF THIS CREATIVE COMMONS PUBLIC LICENSE ("CCPL" OR "LICENSE"). THE WORK IS PROTECTED BY COPYRIGHT AND/OR OTHER APPLICABLE LAW. ANY USE OF THE WORK OTHER THAN AS AUTHORIZED UNDER THIS LICENSE OR COPYRIGHT LAW IS PROHIBITED.

BY EXERCISING ANY RIGHTS TO THE WORK PROVIDED HERE, YOU ACCEPT AND AGREE TO BE BOUND BY THE TERMS OF THIS LICENSE. THE LICENSOR GRANTS YOU THE RIGHTS CONTAINED HERE IN CONSIDERATION OF YOUR ACCEPTANCE OF SUCH TERMS AND CONDITIONS.

1. Definitions

  • "Collective Work" means a work, such as a periodical issue, anthology or encyclopedia, in which the Work in its entirety in unmodified form, along with a number of other contributions, constituting separate and independent works in themselves, are assembled into a collective whole. A work that constitutes a Collective Work will not be considered a Derivative Work (as defined below) for the purposes of this License.
  • "Derivative Work" means a work based upon the Work or upon the Work and other pre-existing works, such as a translation, musical arrangement, dramatization, fictionalization, motion picture version, sound recording, art reproduction, abridgment, condensation, or any other form in which the Work may be recast, transformed, or adapted, except that a work that constitutes a Collective Work will not be considered a Derivative Work for the purpose of this License. For the avoidance of doubt, where the Work is a musical composition or sound recording, the synchronization of the Work in timed-relation with a moving image ("synching") will be considered a Derivative Work for the purpose of this License.
  • "Licensor" means the individual or entity that offers the Work under the terms of this License.
  • "Original Author" means the individual or entity who created the Work.
  • "Work" means the copyrightable work of authorship offered under the terms of this License.
  • "You" means an individual or entity exercising rights under this License who has not previously violated the terms of this License with respect to the Work, or who has received express permission from the Licensor to exercise rights under this License despite a previous violation.
  • "License Elements" means the following high-level license attributes as selected by Licensor and indicated in the title of this License: Attribution, ShareAlike.

2. Fair Use Rights

Nothing in this license is intended to reduce, limit, or restrict any rights arising from fair use, first sale or other limitations on the exclusive rights of the copyright owner under copyright law or other applicable laws.

3. License Grant

Subject to the terms and conditions of this License, Licensor hereby grants You a worldwide, royalty-free, non-exclusive, perpetual (for the duration of the applicable copyright) license to exercise the rights in the Work as stated below:

  • to reproduce the Work, to incorporate the Work into one or more Collective Works, and to reproduce the Work as incorporated in the Collective Works;
  • to create and reproduce Derivative Works;
  • to distribute copies or phonorecords of, display publicly, perform publicly, and perform publicly by means of a digital audio transmission the Work including as incorporated in Collective Works;
  • to distribute copies or phonorecords of, display publicly, perform publicly, and perform publicly by means of a digital audio transmission Derivative Works.
  • For the avoidance of doubt, where the work is a musical composition:
    • Performance Royalties Under Blanket Licenses. Licensor waives the exclusive right to collect, whether individually or via a performance rights society (e.g. ASCAP, BMI, SESAC), royalties for the public performance or public digital performance (e.g. webcast) of the Work.
    • Mechanical Rights and Statutory Royalties. Licensor waives the exclusive right to collect, whether individually or via a music rights society or designated agent (e.g. Harry Fox Agency), royalties for any phonorecord You create from the Work ("cover version") and distribute, subject to the compulsory license created by 17 USC Section 115 of the US Copyright Act (or the equivalent in other jurisdictions).
    • Webcasting Rights and Statutory Royalties. For the avoidance of doubt, where the Work is a sound recording, Licensor waives the exclusive right to collect, whether individually or via a performance-rights society (e.g. SoundExchange), royalties for the public digital performance (e.g. webcast) of the Work, subject to the compulsory license created by 17 USC Section 114 of the US Copyright Act (or the equivalent in other jurisdictions).


The above rights may be exercised in all media and formats whether now known or hereafter devised. The above rights include the right to make such modifications as are technically necessary to exercise the rights in other media and formats. All rights not expressly granted by Licensor are hereby reserved.

4. Restrictions

The license granted in Section 3 above is expressly made subject to and limited by the following restrictions:

  • You may distribute, publicly display, publicly perform, or publicly digitally perform the Work only under the terms of this License, and You must include a copy of, or the Uniform Resource Identifier for, this License with every copy or phonorecord of the Work You distribute, publicly display, publicly perform, or publicly digitally perform. You may not offer or impose any terms on the Work that alter or restrict the terms of this License or the recipients' exercise of the rights granted hereunder. You may not sublicense the Work. You must keep intact all notices that refer to this License and to the disclaimer of warranties. You may not distribute, publicly display, publicly perform, or publicly digitally perform the Work with any technological measures that control access or use of the Work in a manner inconsistent with the terms of this License Agreement. The above applies to the Work as incorporated in a Collective Work, but this does not require the Collective Work apart from the Work itself to be made subject to the terms of this License. If You create a Collective Work, upon notice from any Licensor You must, to the extent practicable, remove from the Collective Work any credit as required by clause 4(c), as requested. If You create a Derivative Work, upon notice from any Licensor You must, to the extent practicable, remove from the Derivative Work any credit as required by clause 4(c), as requested.
  • You may distribute, publicly display, publicly perform, or publicly digitally perform a Derivative Work only under the terms of this License, a later version of this License with the same License Elements as this License, or a Creative Commons iCommons license that contains the same License Elements as this License (e.g. Attribution-ShareAlike 2.5 Japan). You must include a copy of, or the Uniform Resource Identifier for, this License or other license specified in the previous sentence with every copy or phonorecord of each Derivative Work You distribute, publicly display, publicly perform, or publicly digitally perform. You may not offer or impose any terms on the Derivative Works that alter or restrict the terms of this License or the recipients' exercise of the rights granted hereunder, and You must keep intact all notices that refer to this License and to the disclaimer of warranties. You may not distribute, publicly display, publicly perform, or publicly digitally perform the Derivative Work with any technological measures that control access or use of the Work in a manner inconsistent with the terms of this License Agreement. The above applies to the Derivative Work as incorporated in a Collective Work, but this does not require the Collective Work apart from the Derivative Work itself to be made subject to the terms of this License.
  • If you distribute, publicly display, publicly perform, or publicly digitally perform the Work or any Derivative Works or Collective Works, You must keep intact all copyright notices for the Work and provide, reasonable to the medium or means You are utilizing: (i) the name of the Original Author (or pseudonym, if applicable) if supplied, and/or (ii) if the Original Author and/or Licensor designate another party or parties (e.g. a sponsor institute, publishing entity, journal) for attribution in Licensor's copyright notice, terms of service or by other reasonable means, the name of such party or parties; the title of the Work if supplied; to the extent reasonably practicable, the Uniform Resource Identifier, if any, that Licensor specifies to be associated with the Work, unless such URI does not refer to the copyright notice or licensing information for the Work; and in the case of a Derivative Work, a credit identifying the use of the Work in the Derivative Work (e.g., "French translation of the Work by Original Author," or "Screenplay based on original Work by Original Author"). Such credit may be implemented in any reasonable manner; provided, however, that in the case of a Derivative Work or Collective Work, at a minimum such credit will appear where any other comparable authorship credit appears and in a manner at least as prominent as such other comparable authorship credit.

5. Representations, Warranties and Disclaimer

UNLESS OTHERWISE AGREED TO BY THE PARTIES IN WRITING, LICENSOR OFFERS THE WORK AS-IS AND MAKES NO REPRESENTATIONS OR WARRANTIES OF ANY KIND CONCERNING THE MATERIALS, EXPRESS, IMPLIED, STATUTORY OR OTHERWISE, INCLUDING, WITHOUT LIMITATION, WARRANTIES OF TITLE, MERCHANTIBILITY, FITNESS FOR A PARTICULAR PURPOSE, NONINFRINGEMENT, OR THE ABSENCE OF LATENT OR OTHER DEFECTS, ACCURACY, OR THE PRESENCE OF ABSENCE OF ERRORS, WHETHER OR NOT DISCOVERABLE. SOME JURISDICTIONS DO NOT ALLOW THE EXCLUSION OF IMPLIED WARRANTIES, SO SUCH EXCLUSION MAY NOT APPLY TO YOU.

6. Limitation on Liability.

EXCEPT TO THE EXTENT REQUIRED BY APPLICABLE LAW, IN NO EVENT WILL LICENSOR BE LIABLE TO YOU ON ANY LEGAL THEORY FOR ANY SPECIAL, INCIDENTAL, CONSEQUENTIAL, PUNITIVE OR EXEMPLARY DAMAGES ARISING OUT OF THIS LICENSE OR THE USE OF THE WORK, EVEN IF LICENSOR HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES.

7. Termination

  • This License and the rights granted hereunder will terminate automatically upon any breach by You of the terms of this License. Individuals or entities who have received Derivative Works or Collective Works from You under this License, however, will not have their licenses terminated provided such individuals or entities remain in full compliance with those licenses. Sections 1, 2, 5, 6, 7, and 8 will survive any termination of this License.
  • Subject to the above terms and conditions, the license granted here is perpetual (for the duration of the applicable copyright in the Work). Notwithstanding the above, Licensor reserves the right to release the Work under different license terms or to stop distributing the Work at any time; provided, however that any such election will not serve to withdraw this License (or any other license that has been, or is required to be, granted under the terms of this License), and this License will continue in full force and effect unless terminated as stated above.

8. Miscellaneous

  • Each time You distribute or publicly digitally perform the Work or a Collective Work, the Licensor offers to the recipient a license to the Work on the same terms and conditions as the license granted to You under this License.
  • Each time You distribute or publicly digitally perform a Derivative Work, Licensor offers to the recipient a license to the original Work on the same terms and conditions as the license granted to You under this License.
  • If any provision of this License is invalid or unenforceable under applicable law, it shall not affect the validity or enforceability of the remainder of the terms of this License, and without further action by the parties to this agreement, such provision shall be reformed to the minimum extent necessary to make such provision valid and enforceable.
  • No term or provision of this License shall be deemed waived and no breach consented to unless such waiver or consent shall be in writing and signed by the party to be charged with such waiver or consent.
  • This License constitutes the entire agreement between the parties with respect to the Work licensed here. There are no understandings, agreements or representations with respect to the Work not specified here. Licensor shall not be bound by any additional provisions that may appear in any communication from You. This License may not be modified without the mutual written agreement of the Licensor and You.