-1

I am new to COM and Windows programming. I am trying to play a mp3 file using media foundation.

Below is the code which I have tried to execute on windows 10. Here is the overview what I did in this code.

I first initialize the COM Then I start the Media Foundation. Then I created media source with the help of source resolver Then I created a MP3 Decoder MFT Then I created a Audio Media Activation object Then I created a Audio Media Sink Then I created a Topology Then I created 3 topology nodes and added Media source, Mp3 Decoder and Audio Media sink to it. Then I added all the topology nodes to the topology Then I created the Media Session and added the topology to media session Then I started the media session. Then I release all the COM objects. Then I shutdown the Media Foundation. Then I uninitialized the COM.

But unfortunately, the file does not start playing.

Please tell what is wrong with my code.

// ConsoleApplication1.cpp : This file contains the 'main' function. Program execution begins and ends there.
//

#include <iostream>
#include <mfapi.h>
#include <mfidl.h>
#include <mfreadwrite.h>
#include <Wmcodecdsp.h>
#include <combaseapi.h>
#include <mferror.h>
#include <tchar.h>
#include <evr.h>

int main()
{
    HRESULT hr = CoInitialize(NULL);

    if (FAILED(hr)) {
        std::cout << "cannot initilize COM";
    }

   
   
        // Initialize the Media Foundation platform.
  hr=     MFStartup(MF_VERSION);

  if (FAILED(hr)) {
      std::cout << "cannot initilize MF";
  }
      
            MF_OBJECT_TYPE ObjectType = MF_OBJECT_INVALID;
            IMFSourceResolver* pSourceResolver;
            IUnknown* pSource = nullptr;
            IMFMediaSource* mSource;
            IMFPresentationDescriptor* ppPresentationDescriptor;
            IMFTransform* mtransform = NULL;
            IMFTopology* topology = NULL;
            IMFStreamDescriptor* sdesip = NULL;
            IMFTopologyNode* source = NULL;
            IMFTopologyNode* transform;
            IMFTopologyNode* output = NULL;
            IMFMediaSink* mediasink = NULL;
            IMFMediaTypeHandler* mediatypehandler;
            IMFMediaType* mediatype;
            IMFMediaType* decodermediatype;
            IMFMediaSession* mediasession;
            DWORD streamdesip;

   hr =      MFCreateSourceResolver(&pSourceResolver);

   if (FAILED(hr)) {
       std::cout << "cannot create source resolver";
   }
           

      hr =    pSourceResolver->CreateObjectFromURL(
                L"song.mp3",                       // URL of the source.
                MF_RESOLUTION_MEDIASOURCE,  // Create a source object.
                NULL,                       // Optional property store.
                &ObjectType,     // Receives the created object type. 
                &pSource          // Receives a pointer to the media source.
            );
         
      if (FAILED(hr)) {
          std::cout << "media source";
      }
         hr =  pSource->QueryInterface(IID_PPV_ARGS(&mSource));

         if (FAILED(hr)) {
             std::cout << "media source interface";
         }



      hr =      mSource->CreatePresentationDescriptor(&ppPresentationDescriptor);

      if (FAILED(hr)) {
          std::cout << "presentation discriptor";
      }

            ppPresentationDescriptor->SelectStream(0);
         hr = CoCreateInstance(__uuidof(CMP3DecMediaObject),
                NULL,
                CLSCTX_INPROC_SERVER,
                IID_IMFTransform,
                (void**)&mtransform);
        
         
         if (FAILED(hr)) {
             std::cout << "Decoder";
         }
      hr =      MFCreateTopology(
                &topology
            );

      if (FAILED(hr)) {
          std::cout << "topology";
      }

     hr =       MFCreateTopologyNode(MF_TOPOLOGY_SOURCESTREAM_NODE, &source);

     if (FAILED(hr)) {
         std::cout << "source topology node";
     }

       hr =     source->SetUnknown(MF_TOPONODE_SOURCE, mSource);

       if (FAILED(hr)) {
           std::cout << "source set to topology node";
       }
         hr =   source->SetUnknown(MF_TOPONODE_PRESENTATION_DESCRIPTOR, ppPresentationDescriptor);

         if (FAILED(hr)) {
             std::cout << "desciption set to topology node";
         }
            BOOL value;
         hr =   ppPresentationDescriptor->GetStreamDescriptorByIndex(0, &value, &sdesip);
         if (FAILED(hr)) {
             std::cout << "stream desciption get";
         }

         sdesip->GetStreamIdentifier(&streamdesip);
          
hr =  sdesip->GetMediaTypeHandler(&mediatypehandler);

if (FAILED(hr)) {
    std::cout << "media handler";
}

       hr=      mediatypehandler->GetCurrentMediaType(&mediatype);

       if (FAILED(hr)) {
           std::cout << "current media type";
       }
           

       hr =      source->SetUnknown(MF_TOPONODE_STREAM_DESCRIPTOR, sdesip);

       if (FAILED(hr)) {
           std::cout << "set stream desiptor";
       }

      hr =      topology->AddNode(source);

      if (FAILED(hr)) {
          std::cout << "add source node";
      }

        hr =     MFCreateTopologyNode(MF_TOPOLOGY_TRANSFORM_NODE, &transform);

        if (FAILED(hr)) {
            std::cout << "transform node";
        }
           hr =  MFCreateMediaType(&decodermediatype);

           if (FAILED(hr)) {
               std::cout << "decoder media type";
           }


           mediatype->CopyAllItems(decodermediatype);
           

            if (FAILED(hr)) {
                std::cout << "set major type";
            }

           hr =  decodermediatype->SetGUID(MF_MT_SUBTYPE, MFAudioFormat_PCM);

           if (FAILED(hr)) {
               std::cout << "set sub type";
           }


         

     


     








       hr =    mtransform->SetInputType(0, mediatype, NULL);

       if (SUCCEEDED(hr)) {
          
       }

       IMFMediaType* newmediatype;
      hr = MFCreateMediaType(&newmediatype);

      if (FAILED(hr)) {
          std::cout << "unable to create";
      }

       hr = mtransform->GetOutputAvailableType(0, 1, &newmediatype);

       if (FAILED(hr)) {
           std::cout << "nodata";
       }
        hr =     mtransform->SetOutputType(0, newmediatype, 0);

        if (FAILED(hr)) {
            std::cout << "output";
        }

       

           

       
         hr =    transform->SetObject(mtransform);

         if (FAILED(hr)) {
             std::cout << "set transform node";
         }

           hr =  topology->AddNode(transform);

           if (FAILED(hr)) {
               std::cout << "add trasnform node";
           }

            IMFActivate* active;


           hr =  MFCreateAudioRendererActivate(&active);

          if (FAILED(hr)) {
              
              std::cout << "active object";
          }

         
        
          

        hr =     active->ActivateObject(__uuidof(IMFMediaSink), (void**)&mediasink);


        if (FAILED(hr)) {
           
            std::cout << "media sink";
        }
           
           
      hr =       MFCreateTopologyNode(MF_TOPOLOGY_OUTPUT_NODE, &output);

      if (FAILED(hr)) {

          std::cout << "output node topology";
      }

      IMFStreamSink* streamsink;

     hr  =  mediasink->GetStreamSinkByIndex(0, &streamsink);

     if (FAILED(hr)) {

         std::cout << "get stream sink";
     }

   hr =    output->SetObject(streamsink);

   if (FAILED(hr)) {

       std::cout << "set out put node";
   }

        hr =     output->SetUINT32(MF_TOPONODE_STREAMID, 0);


        if (FAILED(hr)) {

            std::cout << "uint set";
        }
          hr =  output->SetUINT32(MF_TOPONODE_NOSHUTDOWN_ON_REMOVE, FALSE);
          if (FAILED(hr)) {

              std::cout << "uint set";
          }
       hr =     topology->AddNode(output);
       if (FAILED(hr)) {

           std::cout << "add topo node output";
       }

     hr =   source->ConnectOutput(0, transform, 0);

     if (FAILED(hr)) {

         std::cout << "connect source";
     }

       hr =    transform->ConnectOutput(0, output, 0);

       if (FAILED(hr)) {

           std::cout << "connect output";
       }

  hr =          MFCreateMediaSession(
                NULL,
                &mediasession
            );

  if (FAILED(hr)) {

      std::cout << "create media session";
  }
 hr = mediasession->SetTopology(MFSESSION_SETTOPOLOGY_IMMEDIATE, topology);
 if (FAILED(hr)) {

     std::cout << "fail to set topology";
 }

            PROPVARIANT var;
            PropVariantInit(&var);
            
           
       hr =      mediasession->Start(&GUID_NULL, &var);

       if (FAILED(hr)) {

           std::cout << "media session start";
       }

          pSourceResolver->Release();
            pSource->Release();
            mSource->Release();
           ppPresentationDescriptor->Release();
           mtransform->Release();
           topology->Release();
           sdesip->Release();
           source->Release();
           transform->Release();
          output->Release();
           mediatypehandler->Release();
            mediatype->Release();
          decodermediatype->Release();
         
            mediasession->Release();
            mediasink->Release();

            MFShutdown();

        
        CoUninitialize();
        }
    


    
6
  • Several problems with code. Just a few I noticed: you need to set stream sink to output node, not media sink; decoded audio media type is incomplete, no topology resolution?. Obviously no error checking. Most important, you need to capture session events and let the topology to get resolved in the async call, then you'd get error event and you would be able to inspect the topology to get further details.
    – Roman R.
    Apr 19 at 16:13
  • Is there any good resource where I can learn more about MS Media Foundation?
    – Khur
    Apr 19 at 16:20
  • 1
    See links at the bottom there.
    – Roman R.
    Apr 19 at 16:30
  • Also have a look at How to Play Media Files with Media Foundation. Apr 20 at 2:18
  • You're welcome. Would you like to answer yourself? Apr 20 at 6:08

2 Answers 2

0

For educational purposes, I converted your code snippet to minimalistic sample under 100 lines of code that works.

https://github.com/roman380/MediaFoundationMinimalAudioPlayback

I removed decoder MFT because it can be supplied automatically during topology resolution, so this might be a starting point for you to add nodes yourself and enable MFSESSION_SETTOPOLOGY_NORESOLUTION if this was your original intent (or if this was your attempt to get something that works then you probably don't need it).

C:\Project\alax.info\...\build>debug\Sandbox.exe
Event: 101
Event: 112
Event: 110
Event: 111
Event: 111
Event: 2
Event: 110
Event: 103
^C

Next steps:

  1. Check event codes (101 = MESessionTopologySet etc)
  2. When the topology is ready, you can check it out, esp. what transforms are added, what are the media types and so on; note that resolution is asynchronous and so you cannot check this too early, before you get the respective event
  3. You can add transforms yourself along the lines of Media Foundation's logic you are seeing as a part of automatic topology resolution
3
  • Thank you for the code. as far as my understanding is concern about media foundation you need to add an MFT between the source and output node if you need to perform some digital signal processing (DSP). So my intent was to create a full topology with a decoder MFT to learn more about full topology. I am just learning the things as I am not really expert in it. So my understanding can be wrong but I am ready to do more experiments to produce something. Thanks again for your code.
    – Khur
    Apr 20 at 8:54
  • You have a starting point here, see my update above - a few things worth looking at now, and how exactly you can develop the sample code for DSP needs.
    – Roman R.
    Apr 20 at 9:18
  • Thank you so much I will surely look into the code to understand it better. My weakness is the concept of events in Media Foundation or in general in COM. I am working to it to understand this concept once i will grasp the idea i will be in better position to understand your code. Thanks again for the efforts you put to teach me something which is special for me.
    – Khur
    Apr 20 at 10:09
0

I modified code a bit and removed the Decoder MFT. Now I am using partial topology. One important thing which I was missing in the code is that my application exit as soon as it starts executing. I added a std::cin at the bottom to stop my application exiting. The code is working on my machine. Hope this code will work on other machines as well. Here is the link of the code.

https://github.com/khuramhaf/Microsoft-Media-Foundation-Playback-Topology

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.