Beispiel #1
0
        internal List <WMAFormatInfo> GetFormats(IWMProfileManager pProfileManager)
        {
            var formats = new List <WMAFormatInfo>(this.EnumerateFormatInfo(pProfileManager));

            formats.RemoveAll(fmt => formats.Exists(fmt2 => fmt2.pcm.BitsPerSample < fmt.pcm.BitsPerSample && fmt2.pcm.ChannelCount == fmt.pcm.ChannelCount && fmt2.pcm.SampleRate == fmt.pcm.SampleRate));
            if (formats.Count < 2)
            {
                return(formats);
            }
            int prefixLen = 0, suffixLen = 0;

            while (formats.TrueForAll(s => s.formatName.Length > prefixLen &&
                                      s.formatName.Substring(0, prefixLen + 1) ==
                                      formats[0].formatName.Substring(0, prefixLen + 1)))
            {
                prefixLen++;
            }
            while (formats.TrueForAll(s => s.formatName.Length > suffixLen &&
                                      s.formatName.Substring(s.formatName.Length - suffixLen - 1) ==
                                      formats[0].formatName.Substring(formats[0].formatName.Length - suffixLen - 1)))
            {
                suffixLen++;
            }
            formats.ForEach(s => s.modeName = s.formatName.Substring(prefixLen, s.formatName.Length - suffixLen - prefixLen).Trim().Replace(' ', '_'));
            int ix, iy;

            formats.Sort((Comparison <WMAFormatInfo>)((x, y) => int.TryParse(x.modeName, out ix) && int.TryParse(y.modeName, out iy) ? ix - iy : x.modeName.CompareTo(y.modeName)));
            return(formats);
        }
        /// <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;
        }
Beispiel #4
0
        public static IBaseFilter RenderAsfWriterWithProfile(DisposalCleanup dc, IGraphBuilder graph, string profileData,
                                                             string outputFile)
        {
            int hr = 0;

            IBaseFilter asfWriterFilter = (IBaseFilter) new WMAsfWriter();

            dc.Add(asfWriterFilter);
            hr = graph.AddFilter(asfWriterFilter, "ASF Writer");
            DsError.ThrowExceptionForHR(hr);

            // Create an appropriate IWMProfile from the data
            IWMProfileManager profileManager = ProfileManager.CreateInstance();

            dc.Add(profileManager);

            IntPtr wmProfile = profileManager.LoadProfileByData(profileData);

            dc.Add(wmProfile);

            // Set the profile on the writer
            IConfigAsfWriter2 configWriter = (IConfigAsfWriter2)asfWriterFilter;

            configWriter.ConfigureFilterUsingProfile(wmProfile);

            hr = ((IFileSinkFilter)asfWriterFilter).SetFileName(outputFile, null);
            DsError.ThrowExceptionForHR(hr);

            return(asfWriterFilter);
        }
Beispiel #5
0
        /// <summary>
        /// Wraps the WMCreateProfileManger function
        /// </summary>
        /// <returns>The profile manager object</returns>
        public static IWMProfileManager CreateProfileManager()
        {
            IWMProfileManager res = null;

            Marshal.ThrowExceptionForHR(WMCreateProfileManager(out res));
            return(res);
        }
Beispiel #6
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);
        }
Beispiel #7
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);
        }
Beispiel #8
0
 /// <summary>
 /// Dispose of everything that may need disposing.
 /// </summary>
 public void Cleanup()
 {
     scriptBitrate      = 0;
     writerAdvanced     = null;
     writer             = null;
     netSink            = null;
     fileSink           = null;
     audioProps         = null;
     videoProps         = null;
     audioInput         = 0;
     videoInput         = 0;
     scriptStreamNumber = 0;
     profileManager     = null;
 }
Beispiel #9
0
        public static IBaseFilter RenderAsfWriterWithProfile(DisposalCleanup dc, IGraphBuilder graph, string profileData,
                                                             string outputFile)
        {
            if (dc == null)
            {
                throw new ArgumentNullException("dc");
            }
            if (graph == null)
            {
                throw new ArgumentNullException("graph");
            }
            if (string.IsNullOrEmpty(profileData))
            {
                throw new ArgumentNullException("profileData");
            }
            if (string.IsNullOrEmpty(outputFile))
            {
                throw new ArgumentNullException("outputFile");
            }

            int hr = 0;

            var asfWriterFilter = (IBaseFilter) new WMAsfWriter();

            dc.Add(asfWriterFilter);
            hr = graph.AddFilter(asfWriterFilter, Resources.DefaultAsfWriterName);
            DsError.ThrowExceptionForHR(hr);

            // Create an appropriate IWMProfile from the data
            IWMProfileManager profileManager = ProfileManager.CreateInstance();

            dc.Add(profileManager);

            IntPtr wmProfile = profileManager.LoadProfileByData(profileData);

            dc.Add(wmProfile);

            // Set the profile on the writer
            var configWriter = (IConfigAsfWriter2)asfWriterFilter;

            configWriter.ConfigureFilterUsingProfile(wmProfile);

            hr = ((IFileSinkFilter)asfWriterFilter).SetFileName(outputFile, null);
            DsError.ThrowExceptionForHR(hr);

            return(asfWriterFilter);
        }
Beispiel #10
0
        /// <summary>Do the conversion from DVR-MS to WAV.</summary>
        /// <returns>Null; ignored.</returns>
        protected override object DoWork()
        {
            // Get the filter graph
            object filterGraph = ClassId.CoCreateInstance(ClassId.FilterGraph);

            DisposalCleanup.Add(filterGraph);
            IGraphBuilder graph = (IGraphBuilder)filterGraph;

            // Add the ASF writer and set the output name
            IBaseFilter asfWriterFilter = (IBaseFilter)ClassId.CoCreateInstance(ClassId.WMAsfWriter);

            DisposalCleanup.Add(asfWriterFilter);
            graph.AddFilter(asfWriterFilter, null);
            IFileSinkFilter sinkFilter = (IFileSinkFilter)asfWriterFilter;

            sinkFilter.SetFileName(OutputFilePath, null);

            // Set the profile to be used for conversion
            if (_profilePath != null && _profilePath.Trim().Length > 0)
            {
                // Load the profile XML contents
                string profileData;
                using (StreamReader reader = new StreamReader(File.OpenRead(_profilePath)))
                {
                    profileData = reader.ReadToEnd();
                }

                // Create an appropriate IWMProfile from the data
                IWMProfileManager profileManager = ProfileManager.CreateInstance();
                DisposalCleanup.Add(profileManager);
                IntPtr wmProfile = profileManager.LoadProfileByData(profileData);
                DisposalCleanup.Add(wmProfile);

                // Set the profile on the writer
                IConfigAsfWriter2 configWriter = (IConfigAsfWriter2)asfWriterFilter;
                configWriter.ConfigureFilterUsingProfile(wmProfile);
            }

            // Add the source filter; should connect automatically through the appropriate transform filters
            graph.RenderFile(InputFilePath, null);

            // Run the graph to completion
            RunGraph(graph, asfWriterFilter);

            return(null);
        }
Beispiel #11
0
 public WMWriter(MediaBuffer mb)
 {
     eventLog           = new EventLog("WMG", ".", "WMGCore");
     mb.OnSampleReady  += new MediaBuffer.sampleReadyHandler(ReceiveSample);
     scriptBitrate      = 0;
     writerAdvanced     = null;
     writer             = null;
     netSink            = null;
     fileSink           = null;
     audioProps         = null;
     videoProps         = null;
     audioInput         = 0;
     videoInput         = 0;
     scriptStreamNumber = 0;
     lastWriteTime      = 0;
     profileManager     = null;
     writeFailed        = false;
 }
        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);
        }
Beispiel #13
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;
                }
            }
        }
Beispiel #14
0
		public static extern int WMCreateProfileManager(out IWMProfileManager ppProfileManager);
Beispiel #15
0
 private static extern int WMCreateProfileManager([Out, MarshalAs(UnmanagedType.Interface)] out IWMProfileManager ppProfileManager);
Beispiel #16
0
        internal IEnumerable <WMAFormatInfo> EnumerateFormatInfo(IWMProfileManager pProfileManager2)
        {
            IWMProfileManager pProfileManager = null;

            try
            {
                if (pProfileManager2 == null)
                {
                    WMUtils.WMCreateProfileManager(out pProfileManager);
                }
                var pCodecInfo3 = (pProfileManager2 ?? pProfileManager) as IWMCodecInfo3;
                int cCodecs;
                pCodecInfo3.GetCodecInfoCount(MediaType.Audio, out cCodecs);
                for (int iCodec = 0; iCodec < cCodecs; iCodec++)
                {
                    int szCodecName = 0;
                    pCodecInfo3.GetCodecName(MediaType.Audio, iCodec, null, ref szCodecName);
                    var codecName = new StringBuilder(szCodecName);
                    pCodecInfo3.GetCodecName(MediaType.Audio, iCodec, codecName, ref szCodecName);
                    var    attrDataType = new AttrDataType();
                    int    dwAttrSize   = 0;
                    byte[] pAttrValue   = new byte[4];
                    pCodecInfo3.GetCodecProp(MediaType.Audio, iCodec, Constants.g_wszIsVBRSupported, out attrDataType, pAttrValue, ref dwAttrSize);
                    if (pAttrValue[0] != 1)
                    {
                        continue;
                    }
                    if (m_vbr)
                    {
                        pCodecInfo3.SetCodecEnumerationSetting(MediaType.Audio, iCodec, Constants.g_wszVBREnabled, AttrDataType.BOOL, new byte[] { 1, 0, 0, 0 }, 4);
                        pCodecInfo3.SetCodecEnumerationSetting(MediaType.Audio, iCodec, Constants.g_wszNumPasses, AttrDataType.DWORD, new byte[] { 1, 0, 0, 0 }, 4);
                    }
                    else
                    {
                        pCodecInfo3.SetCodecEnumerationSetting(MediaType.Audio, iCodec, Constants.g_wszVBREnabled, AttrDataType.BOOL, new byte[] { 0, 0, 0, 0 }, 4);
                    }

                    int cFormat;
                    pCodecInfo3.GetCodecFormatCount(MediaType.Audio, iCodec, out cFormat);
                    for (int iFormat = 0; iFormat < cFormat; iFormat++)
                    {
                        IWMStreamConfig pStreamConfig;
                        int             cchDesc = 1024;
                        StringBuilder   szDesc  = new StringBuilder(cchDesc);
                        pCodecInfo3.GetCodecFormatDesc(MediaType.Audio, iCodec, iFormat, out pStreamConfig, szDesc, ref cchDesc);
                        if (szDesc.ToString().Contains("(A/V)"))
                        {
                            continue;
                        }
                        try
                        {
                            var         pProps     = pStreamConfig as IWMMediaProps;
                            int         cbType     = 0;
                            AMMediaType pMediaType = null;
                            pProps.GetMediaType(pMediaType, ref cbType);
                            pMediaType            = new AMMediaType();
                            pMediaType.formatSize = cbType - Marshal.SizeOf(typeof(AMMediaType));
                            pProps.GetMediaType(pMediaType, ref cbType);
                            try
                            {
                                if (pMediaType.majorType == MediaType.Audio && pMediaType.formatType == FormatType.WaveEx && pMediaType.subType == m_subType)
                                {
                                    var pcm = WaveFormatExtensible.FromMediaType(pMediaType).GetConfig();
                                    if (PCM == null || (pcm.ChannelCount == PCM.ChannelCount && pcm.SampleRate == PCM.SampleRate && pcm.BitsPerSample >= PCM.BitsPerSample))
                                    {
                                        yield return new WMAFormatInfo()
                                               {
                                                   codec      = iCodec,
                                                   codecName  = codecName.ToString(),
                                                   format     = iFormat,
                                                   formatName = szDesc.ToString(),
                                                   subType    = pMediaType.subType,
                                                   pcm        = pcm
                                               }
                                    }
                                    ;
                                }
                            }
                            finally
                            {
                                WMUtils.FreeWMMediaType(pMediaType);
                            }
                        }
                        finally
                        {
                            Marshal.ReleaseComObject(pStreamConfig);
                        }
                    }
                }
            }
            finally
            {
                if (pProfileManager != null)
                {
                    Marshal.ReleaseComObject(pProfileManager);
                }
            }
        }
Beispiel #17
0
        public IWMWriter GetWriter()
        {
            IWMProfileManager pProfileManager = null;

            try
            {
                WMUtils.WMCreateProfileManager(out pProfileManager);
                var pCodecInfo3 = pProfileManager as IWMCodecInfo3;
                // We have to use the same pProfileManager for enumeration,
                // because it calls SetCodecEnumerationSetting, so chosenFormat.format
                // would not point to the same format for a pProfileManager
                // with different (default) settings, and GetCodecFormat
                // would return the wrong stream config.
                var formats = GetFormats(pProfileManager);
                if (this.EncoderMode != "")
                {
                    formats.RemoveAll(fmt => fmt.modeName != this.EncoderMode);
                }
                if (formats.Count < 1)
                {
                    throw new NotSupportedException("codec/format not found");
                }
                if (formats.Count > 1)
                {
                    throw new NotSupportedException("codec/format ambiguous");
                }
                var             chosenFormat = formats[0];
                IWMStreamConfig pStreamConfig1;
                pCodecInfo3.GetCodecFormat(MediaType.Audio, chosenFormat.codec, chosenFormat.format, out pStreamConfig1);
                try
                {
                    pStreamConfig1.SetStreamNumber(1);
                    IWMProfile pProfile;
                    pProfileManager.CreateEmptyProfile(WMVersion.V9_0, out pProfile);
                    try
                    {
                        pProfile.AddStream(pStreamConfig1);
                        IWMWriter pWriter;
                        WMUtils.WMCreateWriter(IntPtr.Zero, out pWriter);
                        try
                        {
                            pWriter.SetProfile(pProfile);
                        }
                        catch (Exception ex)
                        {
                            Marshal.ReleaseComObject(pWriter);
                            throw ex;
                        }
                        return(pWriter);
                    }
                    finally
                    {
                        Marshal.ReleaseComObject(pProfile);
                    }
                }
                finally
                {
                    Marshal.ReleaseComObject(pStreamConfig1);
                }
            }
            finally
            {
                Marshal.ReleaseComObject(pProfileManager);
            }
        }
Beispiel #18
0
        /// <summary>
        /// Get asf profile information
        /// </summary>
        /// <returns></returns>
        public bool GetProfileFormatInfo(AsfFormatSelection avformat)
        {
            IWMProfileManager profileManager = null;
            IWMProfile        profile        = null;

            if (InnerList.Count > 0)
            {
                // Profile information already loaded
                return(true);
            }

#if DEBUG
            Debug.WriteLine("Look for Windows Media profile information: " + avformat);
#endif
            try
            {
                IWMProfileManager2        profileManager2;
                IWMProfileManagerLanguage profileManagerLanguage;
                int   nbrProfiles;
                int   totalItems = 0;
                short langID;

                // Open the profile manager
                var hr = WMLib.WMCreateProfileManager(out profileManager);
                if (hr >= 0)
                {
                    // Convert pWMProfileManager to a IWMProfileManager2
                    profileManager2        = profileManager as IWMProfileManager2;
                    profileManagerLanguage = (IWMProfileManagerLanguage)profileManager;

                    profileManager2.GetSystemProfileVersion(out var wmversion);
#if DEBUG
                    Debug.WriteLine("WM version=" + wmversion);
#endif

                    profileManagerLanguage.GetUserLanguageID(out langID);
#if DEBUG
                    Debug.WriteLine("WM language ID=" + langID);
#endif

                    //IWMProfileManagerLanguage
                    // Specify the version number of the profiles to use
                    hr = profileManager2.SetSystemProfileVersion(DefaultWMversion);
                    // Marshal.ThrowExceptionForHR(hr);

                    if (hr >= 0)
                    {
                        hr = profileManager2.GetSystemProfileCount(out nbrProfiles);
                        if (hr < 0)
                        {
                            // No profiles available, so nothing to do
                            return(false);
                        }
#if DEBUG
                        Debug.WriteLine("ProfileCount=" + nbrProfiles);
#endif
                    }
                    else
                    {
                        // Error occured when setting profile version
                        return(false);
                    }
                }
                else
                {
                    // Error occured when creating profile manager
                    return(false);
                }

                // There are profiles to look for!
                for (int p = 0; (p < nbrProfiles) && (hr >= 0); p++)
                {
                    Guid guid = Guid.Empty;
                    // Load the profile specified by the caller
                    //hr = profileManager2.LoadProfileByID(guid, out profile);
                    // Marshal.ThrowExceptionForHR(hr);
                    hr = profileManager2.LoadSystemProfile(p, out profile);
                    if (hr >= 0)
                    {
                        IWMProfile2 profile2 = profile as IWMProfile2;
                        if (profile2 != null)
                        {
                            hr = profile2.GetProfileID(out guid);
                        }
#if DEBUG
                        if (hr < 0)
                        {
                            Debug.WriteLine("GetProfileID failed for item " + p);
                        }
#endif
                    }
#if DEBUG
                    else
                    {
                        Debug.WriteLine("LoadSystemProfile failed for item " + p);
                    }
#endif
                    if (hr >= 0)
                    {
                        // Add item to list
                        if (AddProfileItem(avformat, profile, guid, null))
                        {
                            totalItems++;
                        }
                    }
                }                 // for p


                // Start of NEW
                // Look for profile (*.prx) files in the current directory.
                // If found, then add the profile(s) to the list
                string profileData;
                string pathProfile   = Directory.GetCurrentDirectory();
                string filterProfile = "*.prx";

                // Obtain the file system entries in the directory path.
                string[] directoryEntries =
                    Directory.GetFileSystemEntries(pathProfile, filterProfile);

                foreach (string filename in directoryEntries)
                {
                    Debug.WriteLine(filename);
                    if (GetProfileDataFromFile(filename, out profileData))
                    {
                        hr = profileManager.LoadProfileByData(profileData, out profile);
                        if (hr >= 0)
                        {
                            if (AddProfileItem(avformat, profile, Guid.Empty, filename))
                            {
                                totalItems++;
                            }
                        }
                    }
                }
                // End of NEW
            }
            finally
            {
                FindDefaultAsfItem(avformat);

                // Release the locals
                if (profile != null)
                {
                    Marshal.ReleaseComObject(profile);
                    profile = null;
                }
                if (profileManager != null)
                {
                    Marshal.ReleaseComObject(profileManager);
                    profileManager = null;
                }
            }
            return(false);
        }
        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);
        }
Beispiel #20
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);
        }
Beispiel #21
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);
        }
Beispiel #22
0
 public static extern int WMCreateProfileManager(out IWMProfileManager ppProfileManager);