Example #1
0
        public void Initialize(IWMProfile profile, string filePath)
        {
            if (filePath == null || filePath.Length == 0)
            {
                throw new ArgumentNullException("filePath", "Invalid string parameter.");
            }

            //
            // assign profile to writer
            //
            _writer.SetProfile(profile);

            Logger.WriteLogMessage("Set profile on writer.");

            _writer.SetOutputFilename(filePath);

            Logger.WriteLogMessage("Set output filename [" + filePath + "] for writing.");

            _writer.GetInputCount(out _writerInputCount);

            Logger.WriteLogMessage("Found " + _writerInputCount + " writer inputs.");

            profile.GetStreamCount(out _writerStreamCount);

            Logger.WriteLogMessage("Found " + _writerStreamCount + " writer streams.");
        }
Example #2
0
        /// <summary>
        /// Configs the asf.
        /// </summary>
        /// <param name="capGraph">The cap graph.</param>
        /// <param name="szOutputFileName">Name of the sz output file.</param>
        /// <returns></returns>
        private IBaseFilter ConfigAsf(ICaptureGraphBuilder2 capGraph, string szOutputFileName)
        {
            IBaseFilter       asfWriter        = null;
            IFileSinkFilter   pTmpSink         = null;
            IWMProfileManager ppProfileManager = null;
            IWMProfile        ppProfile        = null;

            try
            {
                WindowsMediaLib.WMUtils.WMCreateProfileManager(out ppProfileManager);
                string prx = File.ReadAllText(Path.Combine(Path.GetDirectoryName(
                                                               Assembly.GetEntryAssembly().Location), "profile.prx"));
                ppProfileManager.LoadProfileByData(prx, out ppProfile);

                int hr = capGraph.SetOutputFileName(MediaSubType.Asf, szOutputFileName, out asfWriter, out pTmpSink);
                Marshal.ThrowExceptionForHR(hr);

                WindowsMediaLib.IConfigAsfWriter lConfig = asfWriter as WindowsMediaLib.IConfigAsfWriter;
                lConfig.ConfigureFilterUsingProfile(ppProfile);
            }
            finally
            {
                Marshal.ReleaseComObject(pTmpSink);
                Marshal.ReleaseComObject(ppProfile);
                Marshal.ReleaseComObject(ppProfileManager);
            }

            return(asfWriter);
        }
        private void Config()
        {
            IWMWriter         pWMWriter;
            IWMProfileManager pWMProfileManager = null;
            IWMProfile        pWMProfile        = null;
            INSSBuffer        pSample;

            // Profile id for "Windows Media Video 8 for Dial-up Modem (No audio, 56 Kbps)"
            Guid guidProfileID = new Guid(0x6E2A6955, 0x81DF, 0x4943, 0xBA, 0x50, 0x68, 0xA9, 0x86, 0xA7, 0x08, 0xF6);

            WMUtils.WMCreateProfileManager(out pWMProfileManager);
            IWMProfileManager2 pProfileManager2 = (IWMProfileManager2)pWMProfileManager;

            pProfileManager2.SetSystemProfileVersion(WMVersion.V8_0);
            pProfileManager2.LoadProfileByID(guidProfileID, out pWMProfile);

            WMUtils.WMCreateWriter(IntPtr.Zero, out pWMWriter);
            pWMWriter.SetProfile(pWMProfile);
            pWMWriter.SetOutputFilename("foo.out");

            Marshal.ReleaseComObject(pWMProfile);
            Marshal.ReleaseComObject(pWMProfileManager);

            pWMWriter.BeginWriting();
            pWMWriter.AllocateSample(MAXLENGTH, out pSample);
            m_pSample = (INSSBuffer3)pSample;
        }
Example #4
0
        public bool FindAudioInfo(ref WM_MEDIA_TYPE mediaType, ref WaveFormat waveFormat)
        {
            bool            success = false;
            IWMStreamConfig stream  = null;
            IWMMediaProps   props   = null;
            Guid            mediaTypeGuid;

            IWMProfile profile = (IWMProfile)_reader;

            for (uint i = 0; i < _readerStreamCount; i++)
            {
                profile.GetStream(i, out stream);

                props = (IWMMediaProps)stream;

                WMMediaProps mediaProps = new WMMediaProps(props);

                mediaType     = mediaProps.MediaType;
                mediaTypeGuid = mediaType.majortype;

                if (mediaTypeGuid == MediaTypes.WMMEDIATYPE_Audio)
                {
                    Logger.WriteLogMessage("Found audio stream [" + i + "], format type [" + mediaType.formattype + "].");

                    waveFormat = (WaveFormat)Marshal.PtrToStructure(mediaType.pbFormat, typeof(WaveFormat));
                    success    = true;
                    break;
                }
            }

            return(success);
        }
Example #5
0
    /// <summary>
    /// Create the writer indicating Metadata information
    /// </summary>
    /// <param name="output"><see cref="System.IO.Stream"/> Where resulting WMA string will be written</param>
    /// <param name="format">PCM format of input data received in <see cref="WmaWriter.Write"/> method</param>
    /// <param name="profile">IWMProfile that describe the resulting compressed stream</param>
    /// <param name="MetadataAttributes">Array of <see cref="Yeti.WMFSdk.WM_Attr"/> structures describing the metadata information that will be in the result stream</param>
    public WmaWriter(Stream output, WaveFormat format, IWMProfile profile, WM_Attr[] MetadataAttributes)
      : base(output, format)
		{
			m_Writer = WM.CreateWriter();
      IWMWriterAdvanced wa = (IWMWriterAdvanced)m_Writer;
      wa.AddSink((IWMWriterSink)this);
      m_Writer.SetProfile(profile);
      uint inputs;
      m_Writer.GetInputCount(out inputs);
      if (inputs == 1)
      {
        IWMInputMediaProps InpProps;
        Guid type;
        m_Writer.GetInputProps(0, out InpProps);
        InpProps.GetType(out type);
        if (type == MediaTypes.WMMEDIATYPE_Audio)
        {
          WM_MEDIA_TYPE mt;
          mt.majortype = MediaTypes.WMMEDIATYPE_Audio;
          mt.subtype = MediaTypes.WMMEDIASUBTYPE_PCM;
          mt.bFixedSizeSamples	= true;
          mt.bTemporalCompression = false;
          mt.lSampleSize	= (uint)m_InputDataFormat.nBlockAlign;
          mt.formattype	= MediaTypes.WMFORMAT_WaveFormatEx;
          mt.pUnk	= IntPtr.Zero;
          mt.cbFormat	= (uint)Marshal.SizeOf(m_InputDataFormat);

          GCHandle h = GCHandle.Alloc(m_InputDataFormat, GCHandleType.Pinned);
          try
          {
            mt.pbFormat	= h.AddrOfPinnedObject();
            InpProps.SetMediaType(ref mt);
          }
          finally
          {
            h.Free();
          }
          m_Writer.SetInputProps(0, InpProps);
          if ( MetadataAttributes != null )
          {
            WMHeaderInfo info = new WMHeaderInfo((IWMHeaderInfo)m_Writer);
            foreach(WM_Attr attr in MetadataAttributes)
            {
              info.SetAttribute(attr);
            }
            info = null;
          }
          m_Writer.BeginWriting();
          m_Profile = profile;
        }
        else
        {
          throw new ArgumentException("Invalid profile", "profile");
        }
      }
      else
      {
        throw new ArgumentException("Invalid profile", "profile");
      }
		}
Example #6
0
        /// <summary>
        /// Create the writer indicating Metadata information
        /// </summary>
        /// <param name="output"><see cref="System.IO.Stream"/> Where resulting WMA string will be written</param>
        /// <param name="format">PCM format of input data received in <see cref="WmaWriter.Write"/> method</param>
        /// <param name="profile">IWMProfile that describe the resulting compressed stream</param>
        /// <param name="MetadataAttributes">Array of <see cref="Yeti.WMFSdk.WM_Attr"/> structures describing the metadata information that will be in the result stream</param>
        public WmaWriter(Stream output, WaveFormat format, IWMProfile profile, WM_Attr[] MetadataAttributes)
            : base(output, format)
        {
            m_Writer = WM.CreateWriter();
            IWMWriterAdvanced wa = (IWMWriterAdvanced)m_Writer;

            wa.AddSink((IWMWriterSink)this);
            m_Writer.SetProfile(profile);
            uint inputs;

            m_Writer.GetInputCount(out inputs);
            if (inputs == 1)
            {
                IWMInputMediaProps InpProps;
                Guid type;
                m_Writer.GetInputProps(0, out InpProps);
                InpProps.GetType(out type);
                if (type == MediaTypes.WMMEDIATYPE_Audio)
                {
                    WM_MEDIA_TYPE mt;
                    mt.majortype            = MediaTypes.WMMEDIATYPE_Audio;
                    mt.subtype              = MediaTypes.WMMEDIASUBTYPE_PCM;
                    mt.bFixedSizeSamples    = true;
                    mt.bTemporalCompression = false;
                    mt.lSampleSize          = (uint)m_InputDataFormat.nBlockAlign;
                    mt.formattype           = MediaTypes.WMFORMAT_WaveFormatEx;
                    mt.pUnk     = IntPtr.Zero;
                    mt.cbFormat = (uint)Marshal.SizeOf(m_InputDataFormat);

                    GCHandle h = GCHandle.Alloc(m_InputDataFormat, GCHandleType.Pinned);
                    try {
                        mt.pbFormat = h.AddrOfPinnedObject();
                        InpProps.SetMediaType(ref mt);
                    }
                    finally {
                        h.Free();
                    }
                    m_Writer.SetInputProps(0, InpProps);
                    if (MetadataAttributes != null)
                    {
                        WMHeaderInfo info = new WMHeaderInfo((IWMHeaderInfo)m_Writer);
                        foreach (WM_Attr attr in MetadataAttributes)
                        {
                            info.SetAttribute(attr);
                        }
                        info = null;
                    }
                    m_Writer.BeginWriting();
                    m_Profile = profile;
                }
                else
                {
                    throw new ArgumentException("Invalid profile", "profile");
                }
            }
            else
            {
                throw new ArgumentException("Invalid profile", "profile");
            }
        }
Example #7
0
        /// <summary>
        /// Create an instance of WmaWriterConfig specifying the writer input format and the ouput profile
        /// </summary>
        /// <param name="format">Input data format</param>
        /// <param name="profile">Output profile</param>
        public WmaWriterConfig(WaveFormat format, IWMProfile profile)
            : base(format)
        {
            var prf = new WMProfile(profile);

            m_ProfileData = prf.ProfileData;
        }
Example #8
0
        public override void Close()

        {
            try

            {
                if (m_Writer != null)

                {
                    m_Writer.EndWriting();

                    IWMWriterAdvanced wa = (IWMWriterAdvanced)m_Writer;

                    wa.RemoveSink((IWMWriterSink)this);

                    m_Writer = null;

                    m_Profile = null;
                }
            }

            finally

            {
                base.Close();
            }
        }
Example #9
0
    /// <summary>
    /// Create an instance of WmaWriterConfig specifying the writer input format and the ouput profile
    /// </summary>
    /// <param name="format">Input data format</param>
    /// <param name="profile">Output profile</param>
    public WmaWriterConfig(WaveFormat format, IWMProfile profile)
      : base(format)

    {
      WMProfile prf = new WMProfile(profile);

      m_ProfileData = prf.ProfileData;
    }
Example #10
0
        private void SetStreams(string sName)
        {
            // First find the mapping between the output name and
            // the stream number
            IWMProfile pProfile = m_pReader as IWMProfile;

            int iCount;

            pProfile.GetStreamCount(out iCount);
            short[]           sss = new short[iCount];
            StreamSelection[] ss  = new StreamSelection[iCount];

            StringBuilder sSName;

            for (short j = 0; j < iCount; j++)
            {
                IWMStreamConfig pConfig;
                pProfile.GetStream(j, out pConfig);

                try
                {
                    pConfig.GetStreamNumber(out sss[j]);

                    short iSName = 0;
                    sSName = null;
                    pConfig.GetConnectionName(sSName, ref iSName);
                    sSName = new StringBuilder(iSName);
                    pConfig.GetConnectionName(sSName, ref iSName);
                }
                finally
                {
                    Marshal.ReleaseComObject(pConfig);
                }

                // Turn the stream on or off depending on whether
                // this is the one that matches the output we're
                // looking for
                if (sSName.ToString() == sName)
                {
                    ss[j] = StreamSelection.On;
                }
                else
                {
                    ss[j] = StreamSelection.Off;
                }
            }

            // Use the array we've built to specify the streams we want
            IWMReaderAdvanced ra = m_pReader as IWMReaderAdvanced;

            ra.SetStreamsSelected((short)iCount, sss, ss);

            // Learn the maximum sample size that will be send to OnSample
            ra.GetMaxOutputSampleSize(m_dwAudioOutputNum, out m_MaxSampleSize);

            // Have the Samples allocated using IWMReaderCallbackAdvanced::AllocateForOutput
            ra.SetAllocateForOutput(m_dwAudioOutputNum, true);
        }
Example #11
0
        private void TestProfile()
        {
            // Initialize all member variables

            IWMProfile pWMProfile = CreateProfile();

            m_Writer.SetProfile(pWMProfile);
            m_Writer.SetProfileByID(g);
        }
Example #12
0
        private void Config()
        {
            IWMProfileManager pWMProfileManager = null;
            IWMProfile        pWMProfile        = null;

            // Open the profile manager
            WMUtils.WMCreateProfileManager(out pWMProfileManager);

            pWMProfileManager.CreateEmptyProfile(WMVersion.V9_0, out pWMProfile);
            pWMProfile.CreateNewMutualExclusion(out m_pME);
        }
Example #13
0
        public void SetProfile(IWMProfile profile)
        {
            //
            // assign profile to writer
            //
            _writer.SetProfile(profile);

            Logger.WriteLogMessage("Set profile on writer.");

            profile.GetStreamCount(out _writerStreamCount);

            Logger.WriteLogMessage("Found " + _writerStreamCount + " writer streams.");
        }
Example #14
0
        private void Config()
        {
            IWMProfileManager pWMProfileManager = null;
            IWMProfile        pWMProfile        = null;
            IWMProfile3       pWMProfile3       = null;

            // Open the profile manager
            WMUtils.WMCreateProfileManager(out pWMProfileManager);

            pWMProfileManager.CreateEmptyProfile(WMVersion.V9_0, out pWMProfile);
            pWMProfile3 = pWMProfile as IWMProfile3;
            pWMProfile3.CreateNewBandwidthSharing(out m_pBS);
        }
Example #15
0
        //------------------------------------------------------------------------------
        // Name: CWMVCopy::GetProfileInfo()
        // Desc: Gets the profile information from the reader.
        //------------------------------------------------------------------------------
        protected void GetProfileInfo()
        {
            IWMStreamConfig pStreamConfig  = null;
            IWMMediaProps   pMediaProperty = null;

            //
            // Get the profile of the reader
            //
            m_pReaderProfile = m_pReader as IWMProfile;

            //
            // Get stream count
            //
            m_pReaderProfile.GetStreamCount(out m_dwStreamCount);

            //
            // Allocate memory for the stream type array and stream number array
            //
            m_pguidStreamType = new Guid[m_dwStreamCount];
            m_pwStreamNumber  = new short[m_dwStreamCount];

            for (int i = 0; i < m_dwStreamCount; i++)
            {
                m_pReaderProfile.GetStream(i, out pStreamConfig);

                try
                {
                    //
                    // Get the stream number of the current stream
                    //
                    pStreamConfig.GetStreamNumber(out m_pwStreamNumber[i]);

                    //
                    // Set the stream to be received in compressed mode
                    //
                    m_pReaderAdvanced.SetReceiveStreamSamples(m_pwStreamNumber[i], true);

                    pMediaProperty = pStreamConfig as IWMMediaProps;

                    //
                    // Get the stream type of the current stream
                    //
                    pMediaProperty.GetType(out m_pguidStreamType[i]);
                }
                finally
                {
                    Marshal.ReleaseComObject(pStreamConfig);
                }
            }
        }
Example #16
0
        // End of NEW

        /// <summary>
        /// Configure profile from file to Asf file writer
        /// </summary>
        /// <param name="asfWriter"></param>
        /// <param name="filename"></param>
        /// <returns></returns>
        public bool ConfigProfileFromFile(IBaseFilter asfWriter, string filename)
        {
            int hr;

            //string profilePath = "test.prx";
            // Set the profile to be used for conversion
            if ((filename != null) && (File.Exists(filename)))
            {
                // Load the profile XML contents
                string profileData;
                using (StreamReader reader = new StreamReader(File.OpenRead(filename)))
                {
                    profileData = reader.ReadToEnd();
                }

                // Create an appropriate IWMProfile from the data
                // Open the profile manager
                IWMProfileManager profileManager;
                IWMProfile        wmProfile = null;
                hr = WMLib.WMCreateProfileManager(out profileManager);
                if (hr >= 0)
                {
                    // error message: The profile is invalid (0xC00D0BC6)
                    // E.g. no <prx> tags
                    hr = profileManager.LoadProfileByData(profileData, out wmProfile);
                }

                if (profileManager != null)
                {
                    Marshal.ReleaseComObject(profileManager);
                    profileManager = null;
                }

                // Config only if there is a profile retrieved
                if (hr >= 0)
                {
                    // Set the profile on the writer
                    IConfigAsfWriter configWriter = (IConfigAsfWriter)asfWriter;
                    hr = configWriter.ConfigureFilterUsingProfile(wmProfile);
                    if (hr >= 0)
                    {
                        return(true);
                    }
                }
            }
            return(false);
        }
Example #17
0
 /// <summary>
 /// Return the name of a profile.
 /// </summary>
 /// <param name="profile"></param>
 /// <returns></returns>
 private static String GetProfileName(IWMProfile profile)
 {
     try
     {
         uint size = 0;
         profile.GetName(IntPtr.Zero, ref size);
         IntPtr buffer = Marshal.AllocCoTaskMem((int)(2 * (size + 1)));
         profile.GetName(buffer, ref size);
         String name = Marshal.PtrToStringAuto(buffer);
         Marshal.FreeCoTaskMem(buffer);
         return(name);
     }
     catch (Exception e)
     {
         Debug.WriteLine("Failed to get profile name: " + e.ToString());
         return("");
     }
 }
Example #18
0
        private IWMProfile CreateProfile()
        {
            IWMProfileManager pWMProfileManager = null;
            IWMProfile        pWMProfile        = null;

            // Open the profile manager
            WMUtils.WMCreateProfileManager(out pWMProfileManager);

            // Convert pWMProfileManager to a IWMProfileManager2
            IWMProfileManager2 pProfileManager2 = (IWMProfileManager2)pWMProfileManager;

            // Specify the version number of the profiles to use
            pProfileManager2.SetSystemProfileVersion(WMVersion.V8_0);

            pProfileManager2.LoadProfileByID(g, out pWMProfile);

            return(pWMProfile);
        }
Example #19
0
 public void Dispose()
 {
     try
     {
         if (m_Writer != null)
         {
             m_Writer.EndWriting();
             IWMWriterAdvanced wa = (IWMWriterAdvanced)m_Writer;
             wa.RemoveSink((IWMWriterSink)this);
             m_Writer  = null;
             m_Profile = null;
         }
     }
     finally
     {
         m_outputStream.Close();
     }
 }
Example #20
0
        /// <summary>
        /// Configures the WM ASF Writer filter. (populates member variables as well)
        /// </summary>
        protected void ConfigureWriterFilter()
        {
            IWMProfile profile = GetWMProfile(CurrentProfile);

            WindowsMediaLib.IConfigAsfWriter configAsf = (WindowsMediaLib.IConfigAsfWriter)_asfFilter;
            configAsf.ConfigureFilterUsingProfile(profile);

            //Retreive the IWMWriter* objects from the WM ASF Writer filter.
            _writerAdvanced = GetWriterAdvanced();
            _writer         = (IWMWriter)_writerAdvanced;

            //The WM ASF Writer comes with a File-Writer-Sink, which we need to remove.
            RemoveAllSinks(_writerAdvanced);

            //set SourceConfig settings
            _writerAdvanced.SetSyncTolerance(SourceConfig.SyncToleranceMilliseconds);

            _writerAdvanced.SetLiveSource(SourceConfig.LiveSource);
        }
Example #21
0
 public override void Close()
 {
     try
     {
         if (m_Writer != null)
         {
             m_Writer.EndWriting();
             var wa = (IWMWriterAdvanced)m_Writer;
             wa.RemoveSink((IWMWriterSink)this);
             Marshal.ReleaseComObject(m_Writer);
             m_Writer  = null;
             m_Profile = null;
         }
     }
     finally
     {
         //Purposefully leaving the stream open since it gets passed in,
         //its the responsibility of the calling class to manage its own resources.
         base.Flush();
     }
 }
        private void TestProfile()
        {
            int    hr;
            IntPtr prof;

            hr = m_asfw.GetCurrentProfile(out prof);
            DsError.ThrowExceptionForHR(hr);

#if false
            IWMProfile    ipr = o as IWMProfile;
            int           s   = 255;
            StringBuilder sb  = new StringBuilder(s, s);
            ipr.GetName(sb, ref s);
            Debug.Assert(sb.ToString() == "Intranet - High Speed LAN Multiple Bit Rate Video", "GetProfile");
#endif

#if false
            IntPtr ip = Marshal.GetIUnknownForObject(o);
            IntPtr ip2;
            Guid   g = typeof(IWMProfile).GUID;
            Marshal.QueryInterface(ip, ref g, out ip2);
#endif

            hr = m_asfw.ConfigureFilterUsingProfile(prof);
            DsError.ThrowExceptionForHR(hr);

#if false
            Guid   g2 = new Guid("00000000-0000-0000-C000-000000000046");
            IntPtr ip3;
            Marshal.QueryInterface(ip, ref g2, out ip3);

            hr = m_asfw.ConfigureFilterUsingProfile(ip3);
            DsError.ThrowExceptionForHR(hr);
            Marshal.Release(ip3);
#endif
#if false
            Marshal.Release(ip);
            Marshal.Release(ip2);
#endif
        }
Example #23
0
        private void InitAsfWriter(out IBaseFilter asfWriter, bool shittyQuality = false)
        {
            int hr;

            asfWriter = (IBaseFilter) new WMAsfWriter();

            hr = m_FilterGraph.AddFilter(asfWriter, "ASF Writer");
            Marshal.ThrowExceptionForHR(hr);

            if (shittyQuality)
            {
                return;
            }
            // Create an appropriate IWMProfile from the data
            // Open the profile manager
            IWMProfileManager profileManager;
            IWMProfile        wmProfile = null;

            WMUtils.WMCreateProfileManager(out profileManager);

            // error message: The profile is invalid (0xC00D0BC6)
            // E.g. no <prx> tags
            string profile = System.Text.Encoding.ASCII.GetString(Convert.FromBase64String(customGoodProfile));

            profileManager.LoadProfileByData(profile, out wmProfile);

            if (profileManager != null)
            {
                Marshal.ReleaseComObject(profileManager);
                profileManager = null;
            }

            // Config only if there is a profile retrieved
            // Set the profile on the writer
            IConfigAsfWriter configWriter = (IConfigAsfWriter)asfWriter;

            configWriter.ConfigureFilterUsingProfile(wmProfile);
        }
Example #24
0
        public void Open(string filePath, TimeSpan startTime, TimeSpan duration)
        {
            if (Utility.IsEmptyString(filePath))
            {
                throw new ArgumentNullException("inputFilePath", "Invalid string parameter.");
            }

            _reader.Open(filePath);

            Logger.WriteLogMessage("Opened file [" + filePath + "] for reading.");

            WMHeaderInfo readerHeaderInfo = new WMHeaderInfo((IWMHeaderInfo)_reader);

            WM_ATTR  attr           = readerHeaderInfo.GetAttribute(Constants.g_wszWMDuration);
            TimeSpan readerDuration = new TimeSpan((long)(ulong)attr.Value);

            Logger.WriteLogMessage("Found input duration [" + readerDuration + "].");

            if (startTime != TimeSpan.Zero)
            {
                //
                // startTime, duration are in 100-nsec ticks
                //
                _reader.SetRange((ulong)startTime.Ticks, duration.Ticks); // seek

                Logger.WriteLogMessage("Set range on reader, startTime [" + startTime + "], duration [" + duration + "].");
            }

            _reader.GetOutputCount(out _readerOutputCount);

            Logger.WriteLogMessage("Found " + _readerOutputCount + " reader outputs.");

            IWMProfile readerProfile = (IWMProfile)_reader;

            readerProfile.GetStreamCount(out _readerStreamCount);
        }
Example #25
0
        public void Initialize(IWMProfile profile, string filePath)
        {
            if (filePath == null || filePath.Length == 0)
                throw new ArgumentNullException("filePath", "Invalid string parameter.");

            //
            // assign profile to writer
            //
            _writer.SetProfile(profile);

            Logger.WriteLogMessage("Set profile on writer.");

            _writer.SetOutputFilename(filePath);

            Logger.WriteLogMessage("Set output filename [" + filePath + "] for writing.");

            _writer.GetInputCount(out _writerInputCount);

            Logger.WriteLogMessage("Found " + _writerInputCount + " writer inputs.");

            profile.GetStreamCount(out _writerStreamCount);

            Logger.WriteLogMessage("Found " + _writerStreamCount + " writer streams.");
        }
Example #26
0
 public override void Close()
 {
   try
   {
     if (m_Writer != null)
     {
       m_Writer.EndWriting();
       IWMWriterAdvanced wa = (IWMWriterAdvanced)m_Writer;
       wa.RemoveSink((IWMWriterSink)this);
       m_Writer = null;
       m_Profile = null;
     }
   }
   finally 
   {
     base.Close ();
   }
 }
Example #27
0
 /// <summary>
 /// Create the writer without metadata Information
 /// </summary>
 /// <param name="output"><see cref="System.IO.Stream"/> Where resulting WMA string will be written</param>
 /// <param name="format">PCM format of input data received in <see cref="WmaWriter.Write"/> method</param>
 /// <param name="profile">IWMProfile that describe the resulting compressed stream</param>
 public WmaWriter(Stream output, WaveFormat format, IWMProfile profile)
   :this(output, format, profile, null)
 {
 }
Example #28
0
 /// <summary>
 /// WMProfile constructor
 /// </summary>
 /// <param name="profile">Profile object to wrap</param>
 public WMProfile(IWMProfile profile)
 {
     m_Profile = profile;
 }
        // Use IWMStreamConfig interface to access
        // number of streams, each stream number, and bitrate
        ///////////////////////////////////////////////////////////////////////////////
        void GetPropertiesFromProfile(IWMProfile pProfile)
        {
            int dwStreamCount = 0;
            pProfile.GetStreamCount(out dwStreamCount);

            Console.WriteLine(string.Format("This Windows Media file has {0} stream(s)", dwStreamCount));

            for (int dwIndex = 0; dwIndex < dwStreamCount; dwIndex++)
            {
                IWMStreamConfig pConfig = null;
                pProfile.GetStream(dwIndex, out pConfig);

                try
                {
                    Guid guid;
                    pConfig.GetStreamType(out guid);
                    if (MediaType.Video == guid)
                    {
                        short wStreamNum = -1;
                        int dwBitrate = -1;

                        try
                        {
                            pConfig.GetStreamNumber(out wStreamNum);
                        }
                        catch { }
                        try
                        {
                            pConfig.GetBitrate(out dwBitrate);
                        }
                        catch { }

                        Console.WriteLine("Video Stream properties:");
                        Console.WriteLine(string.Format("Stream number: {0}", wStreamNum));
                        Console.WriteLine(string.Format("Bitrate: {0} bps", dwBitrate));

                        PrintCodecName(pConfig);
                    }
                    else if (MediaType.Audio == guid)
                    {
                        short wStreamNum = -1;
                        int dwBitrate = -1;

                        try
                        {
                            pConfig.GetStreamNumber(out wStreamNum);
                        }
                        catch { }
                        try
                        {
                            pConfig.GetBitrate(out dwBitrate);
                        }
                        catch { }

                        Console.WriteLine("Audio Stream properties:");
                        Console.WriteLine(string.Format("Stream number: {0}", wStreamNum));
                        Console.WriteLine(string.Format("Bitrate: {0} bps", dwBitrate));

                        PrintCodecName(pConfig);
                    }
                    else if (MediaType.ScriptCommand == guid)
                    {
                        short wStreamNum = -1;
                        int dwBitrate = -1;

                        try
                        {
                            pConfig.GetStreamNumber(out wStreamNum);
                        }
                        catch { }
                        try
                        {
                            pConfig.GetBitrate(out dwBitrate);
                        }
                        catch { }

                        Console.WriteLine("Script Stream properties:");
                        Console.WriteLine(string.Format("Stream number: {0}", wStreamNum));
                        Console.WriteLine(string.Format("Bitrate: {0} bps\n", dwBitrate));
                    }
                }
                finally
                {
                    Marshal.ReleaseComObject(pConfig);
                }
            }
        }
Example #30
0
        // Use IWMStreamConfig interface to access
        // number of streams, each stream number, and bitrate
        ///////////////////////////////////////////////////////////////////////////////
        void GetPropertiesFromProfile(IWMProfile pProfile)
        {
            int dwStreamCount = 0;

            pProfile.GetStreamCount(out dwStreamCount);

            Console.WriteLine(string.Format("This Windows Media file has {0} stream(s)", dwStreamCount));

            for (int dwIndex = 0; dwIndex < dwStreamCount; dwIndex++)
            {
                IWMStreamConfig pConfig = null;
                pProfile.GetStream(dwIndex, out pConfig);

                try
                {
                    Guid guid;
                    pConfig.GetStreamType(out guid);
                    if (MediaType.Video == guid)
                    {
                        short wStreamNum = -1;
                        int   dwBitrate  = -1;

                        try
                        {
                            pConfig.GetStreamNumber(out wStreamNum);
                        }
                        catch { }
                        try
                        {
                            pConfig.GetBitrate(out dwBitrate);
                        }
                        catch { }

                        Console.WriteLine("Video Stream properties:");
                        Console.WriteLine(string.Format("Stream number: {0}", wStreamNum));
                        Console.WriteLine(string.Format("Bitrate: {0} bps", dwBitrate));

                        PrintCodecName(pConfig);
                    }
                    else if (MediaType.Audio == guid)
                    {
                        short wStreamNum = -1;
                        int   dwBitrate  = -1;

                        try
                        {
                            pConfig.GetStreamNumber(out wStreamNum);
                        }
                        catch { }
                        try
                        {
                            pConfig.GetBitrate(out dwBitrate);
                        }
                        catch { }

                        Console.WriteLine("Audio Stream properties:");
                        Console.WriteLine(string.Format("Stream number: {0}", wStreamNum));
                        Console.WriteLine(string.Format("Bitrate: {0} bps", dwBitrate));

                        PrintCodecName(pConfig);
                    }
                    else if (MediaType.ScriptCommand == guid)
                    {
                        short wStreamNum = -1;
                        int   dwBitrate  = -1;

                        try
                        {
                            pConfig.GetStreamNumber(out wStreamNum);
                        }
                        catch { }
                        try
                        {
                            pConfig.GetBitrate(out dwBitrate);
                        }
                        catch { }

                        Console.WriteLine("Script Stream properties:");
                        Console.WriteLine(string.Format("Stream number: {0}", wStreamNum));
                        Console.WriteLine(string.Format("Bitrate: {0} bps\n", dwBitrate));
                    }
                }
                finally
                {
                    Marshal.ReleaseComObject(pConfig);
                }
            }
        }
Example #31
0
        public void SetProfile(IWMProfile profile)
        {
            //
            // assign profile to writer
            //
            _writer.SetProfile(profile);

            Logger.WriteLogMessage("Set profile on writer.");

            profile.GetStreamCount(out _writerStreamCount);

            Logger.WriteLogMessage("Found " + _writerStreamCount + " writer streams.");
        }
Example #32
0
		/// <summary>
		/// Add profile item to the list
		/// </summary>
		/// <param name="avformat"></param>
		/// <param name="profile"></param>
		/// <param name="guid"></param>
		/// <param name="filename"></param>
		/// <returns></returns>
		public bool AddProfileItem(AsfFormatSelection avformat, IWMProfile profile, Guid guid, string filename)
		{

			if(profile == null)
			{
				return false;
			}

			try
			{
				StringBuilder profileName = new StringBuilder(MAXLENPROFNAME);
				StringBuilder profileDescription = new StringBuilder(MAXLENPROFDESC);
				int profileNameLen = MAXLENPROFNAME;
				int profileDescLen = MAXLENPROFDESC;
				int streamCount = 0;
				bool audio = false;
				bool video = false;
				int audioBitrate = 0;
				int videoBitrate = 0;
				profileName.Length = 0;
				profileDescription.Length = 0;

				int hr = profile.GetName(profileName, ref profileNameLen);
#if DEBUG
				if(hr < 0)
				{
					Debug.WriteLine("GetName failed");
				}
#endif
				
				if(hr >= 0)
				{
					hr = profile.GetDescription(profileDescription, ref profileDescLen);
#if DEBUG
					if(hr < 0)
					{
						Debug.WriteLine("GetDescription failed");
					}
#endif
				}

				if(hr >= 0)
				{
					hr = profile.GetStreamCount(out streamCount);
#if DEBUG
					if(hr < 0)
					{
						Debug.WriteLine("GetStreamCount failed");
					}
#endif
				}

				if((streamCount > 0)&&(hr >= 0))
				{
					IWMStreamConfig streamConfig = null;
					Guid streamGuid = Guid.Empty;
					audio = false;
					video = false;
					audioBitrate = 0;
					videoBitrate = 0;

					for(short i = 1;(i <= streamCount)&&(hr >= 0); i++)
					{
						hr = profile.GetStreamByNumber(i, out streamConfig);
						if((hr >= 0)&&(streamConfig != null))
						{
							hr = streamConfig.GetStreamType(out streamGuid);
							if(hr >= 0)
							{
								if(streamGuid == MediaType.Video)
								{
									video = true;
									hr = streamConfig.GetBitrate(out videoBitrate);
									if(hr < 0)
									{
										videoBitrate = 0;
									}
								} 
								else
									if(streamGuid == MediaType.Audio)
								{
									audio = true;
									hr = streamConfig.GetBitrate(out audioBitrate);
									if(hr < 0)
									{
										audioBitrate = 0;
									}
								}
								hr = 0; // Allow possible unreadable bitrates
							}
#if DEBUG
							else
							{
								Debug.WriteLine("GetStreamByNumber failed");
							}
#endif
						} // for i
					}
					// Create profile format item
					if(hr >= 0)
					{
						WMProfileData profileInfo = new WMProfileData(
							guid, profileName.ToString(), profileDescription.ToString(), audioBitrate, videoBitrate, audio, video);

						bool StoreInfo = false;

						// Check if all profiles are allowed
						switch(avformat)
						{
							case AsfFormatSelection.AllFormats:
								StoreInfo = true;
								break;
							case AsfFormatSelection.AudioOnly:
								if((profileInfo.Audio)&&(!profileInfo.Video))
								{
									StoreInfo = true;
								}
								break;
							case AsfFormatSelection.Video:
								if(profileInfo.Video)
								{
									StoreInfo = true;
								}
								break;
							case AsfFormatSelection.VideoOnly:
								if((profileInfo.Video)&&(!profileInfo.Audio))
								{
									StoreInfo = true;
								}
								break;
							default:
								break;
						}

						if(StoreInfo)
						{

							if((guid == Guid.Empty)&&(filename != null)&&(filename.Length > 0))
							{
								// Store filename
								profileInfo.Filename = filename;
							} 
							else
								if(guid != Guid.Empty)
							{
								profileInfo.Filename = "";
							}
							else
							{
								// Either a filename or guid must be supplied
								profileInfo.Dispose();
								return false;
							}

							this.InnerList.Add(profileInfo);
							return true;
						}
					}
				}
			}
			catch
			{
				// Fatal error occured ...
			}
			return false;
		}
Example #33
0
		public WMProfile(IWMProfile profile)
		{
			_profile = profile;
		}
Example #34
0
        private bool AddWmAsfWriter(string fileName, Quality quality, Standard standard)
        {
            //add asf file writer
            IPin pinOut0, pinOut1;
            IPin pinIn0, pinIn1;

            Log.Info("DVRMS2WMV: add WM ASF Writer to graph");
            string monikerAsfWriter =
                @"@device:sw:{083863F1-70DE-11D0-BD40-00A0C911CE86}\{7C23220E-55BB-11D3-8B16-00C04FB6BD3D}";

            fileWriterbase = Marshal.BindToMoniker(monikerAsfWriter) as IBaseFilter;
            if (fileWriterbase == null)
            {
                Log.Error("DVRMS2WMV:FAILED:Unable to create ASF WM Writer");
                Cleanup();
                return(false);
            }

            int hr = graphBuilder.AddFilter(fileWriterbase, "WM ASF Writer");

            if (hr != 0)
            {
                Log.Error("DVRMS2WMV:FAILED:Add ASF WM Writer to filtergraph :0x{0:X}", hr);
                Cleanup();
                return(false);
            }
            IFileSinkFilter2 fileWriterFilter = fileWriterbase as IFileSinkFilter2;

            if (fileWriterFilter == null)
            {
                Log.Error("DVR2XVID:FAILED:Add unable to get IFileSinkFilter for filewriter");
                Cleanup();
                return(false);
            }
            hr = fileWriterFilter.SetFileName(fileName, null);
            hr = fileWriterFilter.SetMode(AMFileSinkFlags.OverWrite);
            Log.Info("DVRMS2WMV: connect audio/video codecs outputs -> ASF WM Writer");
            //connect output #0 of videocodec->asf writer pin 1
            //connect output #0 of audiocodec->asf writer pin 0
            pinOut0 = DsFindPin.ByDirection((IBaseFilter)Mpeg2AudioCodec, PinDirection.Output, 0);
            pinOut1 = DsFindPin.ByDirection((IBaseFilter)Mpeg2VideoCodec, PinDirection.Output, 0);
            if (pinOut0 == null || pinOut1 == null)
            {
                Log.Error("DVRMS2WMV:FAILED:unable to get outpins of video codec");
                Cleanup();
                return(false);
            }
            pinIn0 = DsFindPin.ByDirection(fileWriterbase, PinDirection.Input, 0);
            if (pinIn0 == null)
            {
                Log.Error("DVRMS2WMV:FAILED:unable to get pins of asf wm writer");
                Cleanup();
                return(false);
            }
            hr = graphBuilder.Connect(pinOut0, pinIn0);
            if (hr != 0)
            {
                Log.Error("DVRMS2WMV:FAILED:unable to connect audio pins :0x{0:X}", hr);
                Cleanup();
                return(false);
            }
            pinIn1 = DsFindPin.ByDirection(fileWriterbase, PinDirection.Input, 1);
            if (pinIn1 == null)
            {
                Log.Error("DVRMS2WMV:FAILED:unable to get pins of asf wm writer");
                Cleanup();
                return(false);
            }
            hr = graphBuilder.Connect(pinOut1, pinIn1);
            if (hr != 0)
            {
                Log.Error("DVRMS2WMV:FAILED:unable to connect video pins :0x{0:X}", hr);
                Cleanup();
                return(false);
            }

            IConfigAsfWriter   config          = fileWriterbase as IConfigAsfWriter;
            IWMProfileManager  profileManager  = null;
            IWMProfileManager2 profileManager2 = null;
            IWMProfile         profile         = null;

            hr = WMLib.WMCreateProfileManager(out profileManager);
            string strprofileType = "";

            switch (quality)
            {
            case Quality.HiDef:
                //hr = WMLib.WMCreateProfileManager(out profileManager);
                if (standard == Standard.Film)
                {
                    strprofileType = Config.GetFile(Config.Dir.Base, @"Profiles\MPHiDef-FILM.prx");
                }
                if (standard == Standard.NTSC)
                {
                    strprofileType = Config.GetFile(Config.Dir.Base, @"Profiles\MPHiDef-NTSC.prx");
                }
                if (standard == Standard.PAL)
                {
                    strprofileType = Config.GetFile(Config.Dir.Base, @"Profiles\MPHiDef-PAL.prx");
                }
                Log.Info("DVRMS2WMV: set WMV HiDef quality profile {0}", strprofileType);
                break;

            case Quality.VeryHigh:
                if (standard == Standard.Film)
                {
                    strprofileType = Config.GetFile(Config.Dir.Base, @"Profiles\MPVeryHigh-FILM.prx");
                }
                if (standard == Standard.NTSC)
                {
                    strprofileType = Config.GetFile(Config.Dir.Base, @"Profiles\MPVeryHigh-NTSC.prx");
                }
                if (standard == Standard.PAL)
                {
                    strprofileType = Config.GetFile(Config.Dir.Base, @"Profiles\MPVeryHigh-PAL.prx");
                }
                Log.Info("DVRMS2WMV: set WMV Very High quality profile {0}", strprofileType);
                break;

            case Quality.High:
                if (standard == Standard.Film)
                {
                    strprofileType = Config.GetFile(Config.Dir.Base, @"Profiles\MPHigh-FILM.prx");
                }
                if (standard == Standard.NTSC)
                {
                    strprofileType = Config.GetFile(Config.Dir.Base, @"Profiles\MPHigh-NTSC.prx");
                }
                if (standard == Standard.PAL)
                {
                    strprofileType = Config.GetFile(Config.Dir.Base, @"Profiles\MPHigh-PAL.prx");
                }
                Log.Info("DVRMS2WMV: set WMV High quality profile {0}", strprofileType);
                break;

            case Quality.Medium:
                if (standard == Standard.Film)
                {
                    strprofileType = Config.GetFile(Config.Dir.Base, @"Profiles\MPMedium-FILM.prx");
                }
                if (standard == Standard.NTSC)
                {
                    strprofileType = Config.GetFile(Config.Dir.Base, @"Profiles\MPMedium-NTSC.prx");
                }
                if (standard == Standard.PAL)
                {
                    strprofileType = Config.GetFile(Config.Dir.Base, @"Profiles\MPMedium-PAL.prx");
                }
                Log.Info("DVRMS2WMV: set WMV Medium quality profile {0}", strprofileType);
                break;

            case Quality.Low:
                if (standard == Standard.Film)
                {
                    strprofileType = Config.GetFile(Config.Dir.Base, @"Profiles\MPLow-FILM.prx");
                }
                if (standard == Standard.NTSC)
                {
                    strprofileType = Config.GetFile(Config.Dir.Base, @"Profiles\MPLow-NTSC.prx");
                }
                if (standard == Standard.PAL)
                {
                    strprofileType = Config.GetFile(Config.Dir.Base, @"Profiles\MPLow-PAL.prx");
                }
                Log.Info("DVRMS2WMV: set WMV Low quality profile {0}", strprofileType);
                break;

            case Quality.Portable:
                if (standard == Standard.Film)
                {
                    strprofileType = Config.GetFile(Config.Dir.Base, @"Profiles\MPPortable-FILM.prx");
                }
                if (standard == Standard.NTSC)
                {
                    strprofileType = Config.GetFile(Config.Dir.Base, @"Profiles\MPPortable-NTSC.prx");
                }
                if (standard == Standard.PAL)
                {
                    strprofileType = Config.GetFile(Config.Dir.Base, @"Profiles\MPPortable-PAL.prx");
                }
                Log.Info("DVRMS2WMV: set WMV Portable quality profile {0}", strprofileType);
                break;

            case Quality.Custom:
                //load custom profile
                string customBitrate = "";
                //Adjust the parameters to suit the custom settings the user has selected.
                switch (bitrate)
                {
                case 0:
                    customBitrate = "100Kbs";
                    break;

                case 1:
                    customBitrate = "256Kbs";
                    break;

                case 2:
                    customBitrate = "384Kbs";
                    break;

                case 3:
                    customBitrate = "768Kbs";
                    break;

                case 4:
                    customBitrate = "1536Kbs";
                    break;

                case 5:
                    customBitrate = "3072Kbs";
                    break;

                case 6:
                    customBitrate = "5376Kbs";
                    break;
                }
                Log.Info("DVRMS2WMV: custom bitrate = {0}", customBitrate);
                //TODO: get fps values & frame size
                //TODO: adjust settings required
                //Call the SetCutomPorfile method to load the custom profile, adjust it's params from user settings & then save it.
                //SetCutomProfile(videoBitrate, audioBitrate, videoHeight, videoWidth, videoFps); //based on user inputs
                //We then reload it after as per other quality settings / profiles.
                strprofileType = Config.GetFile(Config.Dir.Base, @"Profiles\MPCustom.prx");
                Log.Info("DVRMS2WMV: set WMV Custom quality profile {0}", strprofileType);
                break;
            }
            //Loads profile from the above quality selection.
            using (StreamReader prx = new StreamReader(strprofileType))
            {
                String profileContents = prx.ReadToEnd();
                profileManager2 = profileManager as IWMProfileManager2;

                hr = profileManager2.LoadProfileByData(profileContents, out profile);
                if (hr != 0)
                {
                    Log.Info("DVRMS2WMV: get WMV profile - FAILED! {0}", hr);
                    Cleanup();
                    return(false);
                }
            }


            Log.Info("DVRMS2WMV: load profile - SUCCESS!");
            //configures the WM ASF Writer to the chosen profile
            hr = config.ConfigureFilterUsingProfile(profile);
            if (hr != 0)
            {
                Log.Info("DVRMS2WMV: configure profile - FAILED! {0}", hr);
                Cleanup();
                return(false);
            }
            Log.Info("DVRMS2WMV: configure profile - SUCCESS!");
            //TODO: Add DB recording information into WMV.

            //Release resorces
            if (profile != null)
            {
                Marshal.ReleaseComObject(profile);
                profile = null;
            }
            if (profileManager != null)
            {
                Marshal.ReleaseComObject(profileManager);
                profileManager = null;
            }
            return(true);
        }
Example #35
0
 public void Dispose()
 {
     try
     {
         if (m_Writer != null)
         {
             m_Writer.EndWriting();
             IWMWriterAdvanced wa = (IWMWriterAdvanced)m_Writer;
             wa.RemoveSink((IWMWriterSink)this);
             m_Writer = null;
             m_Profile = null;
         }
     }
     finally
     {
         m_outputStream.Close();
     }
 }
Example #36
0
        public static void CopyWmv(string inputFilePath, string outputFilePath, ulong startTime, long duration)
        {
            IWMWriterAdvanced writerAdvanced = null;
            IWMProfile        profile        = null;
            IWMStreamConfig   streamConfig   = null;
            uint streamCount = 0;
            uint inputCount  = 0;

            ushort[] streamNumbers = null;
            WMT_STREAM_SELECTION[] streamSelections = null;
            ulong      sampleTime, sampleDuration;
            uint       flags, outputNum;
            ushort     streamNum;
            INSSBuffer sample = null;

            IWMSyncReader reader = Helpers.CreateSyncReader(WMT_RIGHTS.WMT_RIGHT_NO_DRM);
            IWMWriter     writer = Helpers.CreateWriter();

            try
            {
                reader.Open(inputFilePath);

                Logger.WriteLogMessage("Opened file [" + inputFilePath + "] for reading.");

                profile = (IWMProfile)reader;

                profile.GetStreamCount(out streamCount);

                streamNumbers = new ushort[streamCount];

                streamSelections = new WMT_STREAM_SELECTION[streamCount];

                for (uint i = 0; i < streamCount; i++)
                {
                    profile.GetStream(i, out streamConfig);

                    streamConfig.GetStreamNumber(out streamNumbers[i]);

                    streamSelections[i] = WMT_STREAM_SELECTION.WMT_ON;

                    //
                    // Read compressed samples
                    //
                    reader.SetReadStreamSamples(streamNumbers[i], true);
                }

                //
                // select all streams
                //
                reader.SetStreamsSelected((ushort)streamCount, streamNumbers, streamSelections);

                writer.SetProfile(profile);

                writer.GetInputCount(out inputCount);

                for (uint i = 0; i < inputCount; i++)
                {
                    writer.SetInputProps(i, null);                     // write compressed samples
                }

                writer.SetOutputFilename(outputFilePath);

                Logger.WriteLogMessage("Set output filename [" + outputFilePath + "] for writing.");

                writerAdvanced = (IWMWriterAdvanced)writer;

                // Copy attributes avoided
                // Copy Codec Info avoided
                // Copy all scripts in the header avoided

                writer.BeginWriting();

                //
                // startTime, duration are in 100-nsec ticks
                //
                reader.SetRange(startTime, duration);                 // seek

                Logger.WriteLogMessage("Set range on reader, startTime [" + startTime + "], duration [" + duration + "].");

                for (uint streamsRead = 0; streamsRead < streamCount;)
                {
                    try
                    {
                        streamNum = 0;

                        reader.GetNextSample(0, out sample, out sampleTime, out sampleDuration, out flags, out outputNum, out streamNum);

                        Logger.WriteLogMessage("Grabbed next video sample, sampleTime [" + sampleTime + "], duration [" + sampleDuration + "], flags [" + flags + "], outputNum [" + outputNum + "], streamNum [" + streamNum + "].");

                        writerAdvanced.WriteStreamSample(streamNum, sampleTime, 0, sampleDuration, flags, sample);

                        Logger.WriteLogMessage("Wrote sample, sampleTime [" + sampleTime + "], duration [" + sampleDuration + "], flags [" + flags + "], outputNum [" + outputNum + "], streamNum [" + streamNum + "].");
                    }
                    catch (COMException e)
                    {
                        if (e.ErrorCode == Constants.NS_E_NO_MORE_SAMPLES)
                        {
                            streamsRead++;
                        }
                        else
                        {
                            throw;
                        }
                    }
                }

                writer.EndWriting();
            }
            finally
            {
                reader.Close();
            }
        }
Example #37
0
 public WMProfile(IWMProfile profile)
 {
     _profile = profile;
 }
        private bool Initialize(string destinationFileName, VideoQuality videoQuality)
        {
            IWMProfileManager profileManagerTemp = null;
            IWMProfile        profile            = null;

            int  inputCount = 0;
            Guid inputTypeId;
            bool success = false;

            try
            {
                #region Initialize Properties

                CurrentSampleIndex     = 0;
                CurrentSampleTimeStamp = 0;
                VideoChannelIndex      = -1;
                MediaWriterConfigured  = false;
                MediaWriterIsWriting   = false;

                #endregion

                #region Create ProfileManager

                WMUtils.WMCreateProfileManager(out profileManagerTemp);
                IWMProfileManager2 profileManager = (IWMProfileManager2)profileManagerTemp;

                #endregion

                #region Configure ProfileManager

                profileManager.SetSystemProfileVersion(WMVersion.V8_0);

                #endregion

                #region Load Profile

                switch (videoQuality)
                {
                case VideoQuality.Kbps128:
                    profileManager.LoadProfileByData(Wilke.Interactive.Drone.Control.Properties.Resources.VideoProfile128kbps, out profile);
                    break;

                case VideoQuality.Kbps256:
                    profileManager.LoadProfileByData(Wilke.Interactive.Drone.Control.Properties.Resources.VideoProfile256kbps, out profile);
                    break;
                }

                #endregion

                #region Create Writer

                WMUtils.WMCreateWriter(IntPtr.Zero, out mediaWriter);

                #endregion

                #region Configure Writer

                MediaWriter.SetProfile(profile);

                MediaWriter.GetInputCount(out inputCount);

                // Find the first video input on the writer
                for (int index = 0; index < inputCount; index++)
                {
                    // Get the properties of channel #index
                    MediaWriter.GetInputProps(index, out mediaProperties);

                    // Read the type of the channel
                    MediaProperties.GetType(out inputTypeId);

                    // If it is video, we are done
                    if (inputTypeId == MediaType.Video)
                    {
                        VideoChannelIndex = index;
                        break;
                    }
                }

                // Didn't find a video channel
                if (VideoChannelIndex == -1)
                {
                    throw new Exception("Profile does not accept video input");
                }

                MediaWriter.SetOutputFilename(destinationFileName);

                #endregion

                success = true;
            }
            catch
            {
                throw;
            }

            return(success);
        }
Example #39
0
 /// <summary>
 /// WMProfile constructor
 /// </summary>
 /// <param name="profile">Profile object to wrap</param>
 public WMProfile(IWMProfile profile)
 {
     m_Profile = profile;
 }
Example #40
0
 public override void Close()
 {
     try
     {
         if (m_Writer != null)
         {
             m_Writer.EndWriting();
             var wa = (IWMWriterAdvanced)m_Writer;
             wa.RemoveSink((IWMWriterSink)this);
             Marshal.ReleaseComObject(m_Writer);
             m_Writer = null;
             m_Profile = null;
         }
     }
     finally
     {
         //Purposefully leaving the stream open since it gets passed in,
         //its the responsibility of the calling class to manage its own resources.
         base.Flush();
     }
 }
Example #41
0
        private void SetCutomProfile(int vidbitrate, int audbitrate, int vidheight, int vidwidth, double fps)
        {
            //seperate method atm braindump for adjusting an existing profile (prx file)
            //method call is not enabled yet
            IWMProfileManager  profileManager  = null;
            IWMProfileManager2 profileManager2 = null;
            IWMProfile         profile         = null;
            IWMStreamConfig    streamConfig;
            //IWMInputMediaProps inputProps = null;
            IWMProfileManagerLanguage profileManagerLanguage = null;
            WMVersion     wmversion   = WMVersion.V8_0;
            int           nbrProfiles = 0;
            short         langID;
            StringBuilder profileName        = new StringBuilder(MAXLENPROFNAME);
            StringBuilder profileDescription = new StringBuilder(MAXLENPROFDESC);
            int           profileNameLen     = MAXLENPROFNAME;
            int           profileDescLen     = MAXLENPROFDESC;

            profileName.Length        = 0;
            profileDescription.Length = 0;
            double videoFps          = fps;
            long   singleFramePeriod = (long)((10000000L / fps));
            //Guid guidInputType;
            //int dwInputCount = 0;
            int           hr;
            int           videoBitrate        = vidbitrate;
            int           audioBitrate        = audbitrate;
            int           videoHeight         = vidheight;
            int           videoWidth          = vidwidth;
            double        videofps            = fps;
            int           streamCount         = 0;
            IWMMediaProps streamMediaProps    = null;
            IntPtr        mediaTypeBufferPtr  = IntPtr.Zero;
            uint          mediaTypeBufferSize = 0;
            Guid          streamType          = Guid.Empty;
            WmMediaType   videoMediaType      = new WmMediaType();
            //Set WMVIDEOHEADER
            WMVIDEOINFOHEADER videoInfoHeader = new WMVIDEOINFOHEADER();

            //Setup the profile manager
            hr = WMLib.WMCreateProfileManager(out profileManager);
            profileManager2 = (IWMProfileManager2)profileManager;
            //Set profile version - possibly not needed in this case.
            profileManager2.SetSystemProfileVersion(WMVersion.V8_0);
            //get the profile to modify
            string strprofileType = Config.GetFile(Config.Dir.Base, @"Profiles\MPCustom.prx");
            //read the profile contents
            string profileContents = "";

            using (StreamReader prx = new StreamReader(strprofileType))
            {
                profileContents = prx.ReadToEnd();
            }

            profileManager2        = profileManager as IWMProfileManager2;
            profileManagerLanguage = profileManager as IWMProfileManagerLanguage;
            hr = profileManager2.GetSystemProfileVersion(out wmversion);
            Log.Info("DVRMS2WMV: WM version=" + wmversion.ToString());
            hr = profileManagerLanguage.GetUserLanguageID(out langID);
            Log.Info("DVRMS2WMV: WM language ID=" + langID.ToString());
            hr = profileManager2.SetSystemProfileVersion(DefaultWMversion);
            hr = profileManager2.GetSystemProfileCount(out nbrProfiles);
            Log.Info("DVRMS2WMV: ProfileCount=" + nbrProfiles.ToString());
            //load the profile contents
            hr = profileManager.LoadProfileByData(profileContents, out profile);
            //get the profile name
            hr = profile.GetName(profileName, ref profileNameLen);
            Log.Info("DVRMS2WMV: profile name {0}", profileName.ToString());
            //get the profile description
            hr = profile.GetDescription(profileDescription, ref profileDescLen);
            Log.Info("DVRMS2WMV: profile description {0}", profileDescription.ToString());
            //get the stream count
            hr = profile.GetStreamCount(out streamCount);
            for (int i = 0; i < streamCount; i++)
            {
                profile.GetStream(i, out streamConfig);
                streamMediaProps = (IWMMediaProps)streamConfig;
                streamConfig.GetStreamType(out streamType);
                if (streamType == MediaType.Video)
                {
                    //adjust the video details based on the user input values.
                    streamConfig.SetBitrate(videoBitrate);
                    streamConfig.SetBufferWindow(-1); //3 or 5 seconds ???
                    streamMediaProps.GetMediaType(IntPtr.Zero, ref mediaTypeBufferSize);
                    mediaTypeBufferPtr = Marshal.AllocHGlobal((int)mediaTypeBufferSize);
                    streamMediaProps.GetMediaType(mediaTypeBufferPtr, ref mediaTypeBufferSize);
                    Marshal.PtrToStructure(mediaTypeBufferPtr, videoMediaType);
                    Marshal.FreeHGlobal(mediaTypeBufferPtr);
                    Marshal.PtrToStructure(videoMediaType.pbFormat, videoInfoHeader);
                    videoInfoHeader.TargetRect.right  = 0; // set to zero to take source size
                    videoInfoHeader.TargetRect.bottom = 0; // set to zero to take source size
                    videoInfoHeader.BmiHeader.Width   = videoWidth;
                    videoInfoHeader.BmiHeader.Height  = videoHeight;
                    videoInfoHeader.BitRate           = videoBitrate;
                    videoInfoHeader.AvgTimePerFrame   = singleFramePeriod; //Need to check how this is to be calculated
                    IntPtr vidInfoPtr = Marshal.AllocHGlobal(Marshal.SizeOf(typeof(WMVIDEOINFOHEADER)));
                    Marshal.StructureToPtr(videoInfoHeader, vidInfoPtr, false);
                    videoMediaType.pbFormat = vidInfoPtr;
                    hr = streamMediaProps.SetMediaType(videoMediaType);
                    Marshal.FreeHGlobal(vidInfoPtr);
                }
                if (streamType == MediaType.Audio)
                {
                    //adjust the audio details based on the user input
                    //audio is determined from bitrate selection and thus effects audio profile.
                    hr = streamConfig.SetBitrate(audioBitrate);
                    hr = streamConfig.SetBufferWindow(-1); //3 or 5 seconds ???
                    //TODO: set the WaveformatEx profile info etc
                }
                //recofigures the stream ready for saving
                hr = profile.ReconfigStream(streamConfig);
            }
            //save the profile
            //You should make two calls to SaveProfile.
            //On the first call, pass NULL as pwszProfile.
            int profileLength = 0;

            hr = profileManager2.SaveProfile(profile, null, ref profileLength);
            //On return, the value of pdwLength is set to the length required to hold the profile in string form.
            //TODO: set memory buffer to profileLength
            //Then you can allocate the required amount of memory for the buffer and pass a pointer to it as pwszProfile on the second call.
            hr = profileManager2.SaveProfile(profile, profileContents, ref profileLength);
        }
Example #42
0
        /// <summary>
        ///  Create filename from specified profile using specified framerate
        /// </summary>
        /// <param name="lpszFileName">File name to create</param>
        /// <param name="guidProfileID">WM Profile to use for compression</param>
        /// <param name="iFrameRate">Frames Per Second</param>
        public CwmvFile(string lpszFileName, ref Guid guidProfileID, int iFrameRate)
        {
            Guid guidInputType;
            int  dwInputCount;

            IWMProfileManager pWMProfileManager = null;
            IWMProfile        pWMProfile        = null;

            // Initialize all member variables
            m_iFrameRate           = iFrameRate;
            m_dwVideoInput         = -1;
            m_dwCurrentVideoSample = 0;
            m_msVideoTime          = 0;

            m_pWMWriter   = null;
            m_pInputProps = null;
            m_Init        = false;

            try
            {
                // Open the profile manager
                WMUtils.WMCreateProfileManager(out pWMProfileManager);

                // Convert pWMProfileManager to a IWMProfileManager2
                IWMProfileManager2 pProfileManager2 = (IWMProfileManager2)pWMProfileManager;

                // Specify the version number of the profiles to use
                pProfileManager2.SetSystemProfileVersion(WMVersion.V8_0);

                // Load the profile specified by the caller
                pProfileManager2.LoadProfileByID(guidProfileID, out pWMProfile);

                // Create a writer.  This is the interface we actually write with
                WMUtils.WMCreateWriter(IntPtr.Zero, out m_pWMWriter);

                // Set the profile we got into the writer.  This controls compression, video
                // size, # of video channels, # of audio channels, etc
                m_pWMWriter.SetProfile(pWMProfile);

                // Find out how many inputs are in the current profile
                m_pWMWriter.GetInputCount(out dwInputCount);

                // Assume we won't find any video pins
                m_dwVideoInput = -1;

                // Find the first video input on the writer
                for (int i = 0; i < dwInputCount; i++)
                {
                    // Get the properties of channel #i
                    m_pWMWriter.GetInputProps(i, out m_pInputProps);

                    // Read the type of the channel
                    m_pInputProps.GetType(out guidInputType);

                    // If it is video, we are done
                    if (guidInputType == MediaType.Video)
                    {
                        m_dwVideoInput = i;
                        break;
                    }
                }

                // Didn't find a video channel
                if (m_dwVideoInput == -1)
                {
                    throw new Exception("Profile does not accept video input");
                }

                // Specify the file name for the output
                m_pWMWriter.SetOutputFilename(lpszFileName);
            }
            catch
            {
                Close();
                throw;
            }
            finally
            {
                // Release the locals
                if (pWMProfile != null)
                {
                    Marshal.ReleaseComObject(pWMProfile);
                    pWMProfile = null;
                }
                if (pWMProfileManager != null)
                {
                    Marshal.ReleaseComObject(pWMProfileManager);
                    pWMProfileManager = null;
                }
            }
        }