Example #1
1
        public void CaptureScreen()
        {
            Encoder = new WMEncoder();

            outputPath= @strFolderPath+@"C:\MyData\Captures\MyCaptures.wmv";
            IWMEncSourceGroup2 SrcGrp;
            IWMEncSourceGroupCollection SrcGrpColl;
            SrcGrpColl = Encoder.SourceGroupCollection;
            SrcGrp = (IWMEncSourceGroup2)SrcGrpColl.Add ("SG_1");
            IWMEncVideoSource2 SrcVid;
            //IWMEncAudioSource SrcAud;
            IWMEncSource SrcAud;
            SrcVid = (IWMEncVideoSource2)SrcGrp.AddSource(WMENC_SOURCE_TYPE.WMENC_VIDEO);
            SrcAud = (IWMEncSource) SrcGrp.AddSource(WMENC_SOURCE_TYPE.WMENC_AUDIO);
            SrcVid.SetInput("ScreenCapture1","ScreenCap","");
            SrcAud.SetInput("Default_Audio_Device","Device", "");

            IWMEncProfileCollection ProColl;
            IWMEncProfile Pro;
            int i;
            long lLength;
            ProColl = Encoder.ProfileCollection;
            lLength = ProColl.Count;
              for( i = 0 ; i < lLength - 1; i++)
            Console.WriteLine (ProColl.Item(i).Name);

            for (i = 0; i <= lLength - 1; i++)
            {
                Pro = ProColl.Item(i);
                if (Pro.Name == "Screen Video/Audio High (CBR)")
                {
                    SrcGrp.set_Profile((IWMEncProfile) Pro);
                    break;
                }
            }
            IWMEncDisplayInfo Descr;
            Descr = Encoder.DisplayInfo;
            Descr.Author = "Stein.Jin";
            Descr.Copyright = "Copyright information";
            Descr.Description = "Text description of encoded content";
            Descr.Rating = "Rating information";
            Descr.Title = "Title of encoded content";
            IWMEncAttributes Attr;
            Attr = Encoder.Attributes;
            Attr.Add("URL", "www.google.com");
            IWMEncFile File;
            File = Encoder.File;
            File.LocalFileName = outputPath;
            SrcVid.CroppingBottomMargin = 2;
            SrcVid.CroppingTopMargin = 2;
            SrcVid.CroppingLeftMargin = 2;
            SrcVid.CroppingRightMargin = 2;
            Encoder.PrepareToEncode(true);
            Encoder.Start();
        }
Example #2
0
        public static int GetSecondsTilDone(WMEncoder encoder, DateTime startTime)
        {
            int secsleft = -1;

            IWMEncStatistics stats = encoder.Statistics;
            IWMEncSourceGroup grp = encoder.SourceGroupCollection.Item("SG_1");
            IWMEncAudioSource audsrc = (IWMEncAudioSource)grp.get_Source(WMENC_SOURCE_TYPE.WMENC_AUDIO, 0);

            double durationSecs = (double)GetAudioSourceDuration(audsrc) / 1000F;
            double encodingTimeSecs = (double)(stats.EncodingTime * 10);

            double percentDone = encodingTimeSecs / durationSecs;

            TimeSpan ts = DateTime.UtcNow.Subtract(startTime);

            double estimatedTime = (ts.TotalSeconds / percentDone);

            secsleft = (int)(estimatedTime - ts.TotalSeconds);

            if (secsleft < 0)
                secsleft = -1;

            Logger.WriteLogMessage("Duration: " + durationSecs.ToString("G4") + " seconds, encoding source elapsed time: " + encodingTimeSecs.ToString("G4") + " seconds.");
            Logger.WriteLogMessage("Percent done: " + String.Format("{0:P}", percentDone) + ", encoding time left: " + secsleft + " seconds, estimated encoding time: " + estimatedTime.ToString("G4") + " seconds, elapsed time: " + ts.TotalSeconds.ToString("G4") + " seconds.");

            return secsleft;
        }
Example #3
0
        public static int GetSecondsTilDone(WMEncoder encoder, DateTime startTime)
        {
            int secsleft = -1;

            IWMEncStatistics  stats  = encoder.Statistics;
            IWMEncSourceGroup grp    = encoder.SourceGroupCollection.Item("SG_1");
            IWMEncAudioSource audsrc = (IWMEncAudioSource)grp.get_Source(WMENC_SOURCE_TYPE.WMENC_AUDIO, 0);

            double durationSecs     = (double)GetAudioSourceDuration(audsrc) / 1000F;
            double encodingTimeSecs = (double)(stats.EncodingTime * 10);

            double percentDone = encodingTimeSecs / durationSecs;

            TimeSpan ts = DateTime.UtcNow.Subtract(startTime);

            double estimatedTime = (ts.TotalSeconds / percentDone);

            secsleft = (int)(estimatedTime - ts.TotalSeconds);

            if (secsleft < 0)
            {
                secsleft = -1;
            }

            Logger.WriteLogMessage("Duration: " + durationSecs.ToString("G4") + " seconds, encoding source elapsed time: " + encodingTimeSecs.ToString("G4") + " seconds.");
            Logger.WriteLogMessage("Percent done: " + String.Format("{0:P}", percentDone) + ", encoding time left: " + secsleft + " seconds, estimated encoding time: " + estimatedTime.ToString("G4") + " seconds, elapsed time: " + ts.TotalSeconds.ToString("G4") + " seconds.");

            return(secsleft);
        }
Example #4
0
        private void Page_Load(object sender, System.EventArgs e)
        {
            WMEncoder encoder = new WMEncoder();

            WMEncProfile2 profile = new WMEncProfile2();

            profile.LoadFromFile(Server.MapPath("~/scmeda.prx"));

            IWMEncSourceGroupCollection srcGrpColl = encoder.SourceGroupCollection;
            IWMEncSourceGroup           srcGrp     = srcGrpColl.Add("SingleEncode");

            srcGrp.set_Profile(profile);

            IWMEncAudioSource audio = (WMEncoderLib.IWMEncAudioSource)srcGrp.AddSource(WMENC_SOURCE_TYPE.WMENC_AUDIO);

            audio.SetInput(Server.MapPath("~/cabeloEncolheu.wma"), "", "");
            audio.PreProcessPass = 0;

            IWMEncFile2 file = (IWMEncFile2)encoder.File;

            file.LocalFileName = Server.MapPath("~/cabeloEncolheu.mp3");

            encoder.PrepareToEncode(true);
            encoder.Start();
        }
Example #5
0
        /// <summary>
        /// Saves the video.
        /// </summary>
        /// <param name="fileName">Name of the file.</param>
        /// <param name="profileFileName">Name of the profile file.</param>
        /// <param name="framesPerSecond">Frames per second.</param>
        /// <param name="bitmaps">Bitmaps.</param>
        public WmvEncoder(string profileFileName, ulong framesPerSecond)
        {
            try
            {
                WMEncoder      encoder = new WMEncoder();
                IWMEncProfile2 profile = WMEncProfile.LoadEncodingProfile(encoder, profileFileName);
                WMEncProfile.ReleaseEncoder(ref encoder);

                writer = new WmvWriter();
                writer.SetProfile((IWMProfile)profile.SaveToIWMProfile());

                viHeader = new VideoInfoHeader();
                bool bret = writer.FindVideoInputFormat(0, MediaSubTypes.WMMEDIASUBTYPE_RGB24, ref viHeader, false);
                if (!bret)
                {
                    throw new Exception("FindVideoInputFormat error");
                }
                ;
                frame = new Bitmap((int)viHeader.bmiHeader.biWidth, (int)viHeader.bmiHeader.biHeight, PixelFormat.Format24bppRgb);

                fps = framesPerSecond;
            }
            catch (Exception)
            {
                // error handle
                throw;
            }
        }
Example #6
0
        private void sEnumDRMProfiles()
        {
            if (ComboBox_DRMProfile.Items.Count > 0)
            {
                return;
            }
            try
            {
                WMEncoder               tempEncoder = new WMEncoder();
                IWMDRMContentAuthor     DRM         = tempEncoder.EncoderDRMContentAuthor;
                IWMDRMProfileCollection DRMProColl  = DRM.DRMProfileCollection;
                int i;

                ComboBox_DRMProfile.Items.Add("None");
                for (i = 0; i < DRMProColl.Count; i++)
                {
                    ComboBox_DRMProfile.Items.Add(DRMProColl.Item(i).Name);
                }
                ComboBox_DRMProfile.SelectedIndex = 0;
                tempEncoder = null;
            }
            catch (System.Runtime.InteropServices.COMException ex)
            {
                InstallEncoderQuery(ex);
            }
            catch (Exception ex)
            {
                string strError = ex.ToString();
            }
        }
 private void sReportPercentComplete(WMEncoder glbEncoder)
 {
     if (glbEncoder.RunState == WMENC_ENCODER_STATE.WMENC_ENCODER_RUNNING)
     {
         IWMEncStatistics       Stats     = glbEncoder.Statistics;
         IWMEncFileArchiveStats FileStats = (IWMEncFileArchiveStats)Stats.FileArchiveStats;
         int intCurrentFileDuration;
         int intPercentComplete;
         intCurrentFileDuration = System.Convert.ToInt32(FileStats.FileDuration * 10);
         try
         {
             intPercentComplete = 100 * intCurrentFileDuration / glbintSourceDuration;
             _backgroundWorker.ReportProgress(intPercentComplete, intPercentComplete.ToString() + "% Complete");
         }
         catch (Exception ex)
         {
             string strError = ex.ToString();
             sDisplayErrMessage(strError);
         }
         finally
         {
             FileStats = null;
             Stats     = null;
         }
     }
 }
Example #8
0
        private void EncodingCompleted()
        {
            m_EncodingDone = true;
            Debug.WriteLine("Completed pass " + m_Profile.ToString() +
                            " WMENC_ENCODER_STATE.WMENC_ENCODER_STOPPED");
            lblStatus.Text           = " Finished encoding " + m_Profile.ToString();
            m_Encoder.OnStateChange -= new _IWMEncoderEvents_OnStateChangeEventHandler(
                OnStateChange);
            m_Encoder = null;

            switch (m_Profile)
            {
            case EncodingProfileEnum.LOW:
                m_Profile = EncodingProfileEnum.HIGH;
                EncodeFile(m_Profile);
                break;

            case EncodingProfileEnum.HIGH:
                m_Profile = EncodingProfileEnum.LOSSLESS;
                EncodeFile(m_Profile);
                break;

            case EncodingProfileEnum.LOSSLESS:
                break;
            }
        }
Example #9
0
        public static IWMEncProfile2 LoadEncodingProfile(WMEncoder encoder, string profileFilePath)
        {
            if (encoder == null)
                throw new ArgumentNullException("encoder", "Invalid WMEncoder parameter.");
        
            WMEncProfile2 profile2 = new WMEncProfile2();
            profile2.LoadFromFile(profileFilePath);

            return (IWMEncProfile2)profile2;
        }
Example #10
0
 private void btnStop_Click(object sender, EventArgs e)
 {
     if (enc != null)
     {
         // 停止编码
         enc.Stop();
         enc = null;
         btnStart.Enabled = true;
         btnStop.Enabled  = false;
     }
 }
Example #11
0
        public bool EnumerateAudioSources()
        {
            try
            {
                WMEncoder Encoder = new WMEncoder();

                // Retrieve source and device plug-in info manager objects from WMEncoder.
                IWMEncSourcePluginInfoManager        SrcPlugMgr = Encoder.SourcePluginInfoManager;
                IWMEncDeviceControlPluginInfoManager DCPlugMgr  = Encoder.DeviceControlPluginInfoManager;

                // Loop through all the audio and video devices on the system.
                IWMEncPluginInfo PlugInfo;
                for (int i = 0; i < SrcPlugMgr.Count; i++)
                {
                    // Set the IWMEncPluginInfo object to the current plug-in.
                    PlugInfo = SrcPlugMgr.Item(i);

                    // Find the device plug-ins that support resources.
                    if (PlugInfo.SchemeType == "DEVICE" && PlugInfo.Resources == true)
                    {
                        // Loop through the resources in the current plug-in.
                        for (int j = 0; j < PlugInfo.Count; j++)
                        {
                            //if(frm_Rec.chkAudio.Checked==true)

                            {
                                // Add audio resources to the cboAudioSource combo box.
                                if (PlugInfo.MediaType == WMENC_SOURCE_TYPE.WMENC_AUDIO)
                                {
                                    m_sourceEnumDlg.audioSources.Items.Add(PlugInfo.Item(j));
                                }
                            }
                        }
                    }
                }
            }
            catch (Exception exp)
            {
                WebMeeting.Client.ClientUI.getInstance().ShowExceptionMessage("Video Recordong Module ===>Screen Capture.cs line==> 147", exp, "Error Enumeration Audio Resources: " + exp.Message.ToString(), true);
                //WebMeeting.Client.ClientUI.getInstance().ShowExceptionMessage("Error Stoping encoder: " + exp.Message.ToString());
                //Trace.WriteLine(exp.ToString()+"---"+exp.Message+"---"+exp.Source+exp.StackTrace+"---"+exp.TargetSite+"---"+exp.InnerException);
            }

            //DialogResult ret = m_sourceEnumDlg.ShowDialog();
            //if( ret == DialogResult.Cancel)
            //	return false;

            //m_szAudioSource = m_sourceEnumDlg.selectedItem;

            m_szAudioSource = config.Read("Driver");

            return(true);
        }
Example #12
0
        /// <summary>
        /// Saves the video.
        /// </summary>
        /// <param name="fileName">Name of the file.</param>
        /// <param name="profileFileName">Name of the profile file.</param>
        /// <param name="files">Files.</param>
        public static void SaveVideo(string fileName, string profileFileName, ulong framesPerSecond, string [] files)
        {
            WMEncoder      encoder = new WMEncoder();
            IWMEncProfile2 profile = WMEncProfile.LoadEncodingProfile(encoder, profileFileName);

            WMEncProfile.ReleaseEncoder(ref encoder);

            using (WmvWriter writer = new WmvWriter())
            {
                writer.Initialize((IWMProfile)profile.SaveToIWMProfile(), fileName);

                VideoInfoHeader viHeader = new VideoInfoHeader();
                writer.FindVideoInputFormat(0, MediaSubTypes.WMMEDIASUBTYPE_RGB24, ref viHeader, false);
                writer.Start();

                INSSBuffer sample  = null;
                int        bmcount = 0;
                Bitmap     frame   = new Bitmap((int)viHeader.bmiHeader.biWidth, (int)viHeader.bmiHeader.biHeight, PixelFormat.Format24bppRgb);;
                ulong      fps     = framesPerSecond;

                for (int i = 0; i < files.Length; i++)
                {
                    if (files[i] != null)
                    {
                        Bitmap bmp = new Bitmap(files[i]);
                        using (Graphics g = Graphics.FromImage(frame))
                        {
                            g.InterpolationMode  = InterpolationMode.HighQualityBicubic;
                            g.CompositingQuality = CompositingQuality.HighQuality;
                            g.SmoothingMode      = SmoothingMode.HighQuality;
                            g.PixelOffsetMode    = PixelOffsetMode.HighQuality;
                            g.DrawImage(bmp, 0, 0, frame.Width, frame.Height);
                            Console.Out.Write(".");
                        }

                        // Now render to the movie
                        try
                        {
                            ulong time = ((ulong)bmcount++ *TimeSpan.TicksPerSecond) / fps;
                            sample = writer.GetSampleFromBitmap(frame);
                            writer.Writer.WriteSample(0, time, (uint)WMT_STREAM_SAMPLE_TYPE.WM_SF_CLEANPOINT, sample);
                        }
                        finally
                        {
                            Marshal.ReleaseComObject(sample);
                            sample = null;
                            bmp    = null;
                            GC.Collect();
                        }
                    }
                }
            }
        }
Example #13
0
 public VideoRecorder()
 {
     try
     {
         m_Encoder = new WMEncoder();
     }
     catch (System.Exception ex)
     {
         System.Windows.Forms.MessageBox.Show("视频解码器启动失败,视频录制功能将不能正常使用!\r\n" + ex.Message, "视频解码器启动失败",
                                              System.Windows.Forms.MessageBoxButtons.OK, System.Windows.Forms.MessageBoxIcon.Warning);
     }
 }
Example #14
0
        public static IWMEncProfile2 LoadEncodingProfile(WMEncoder encoder, string profileFilePath)
        {
            if (encoder == null)
            {
                throw new ArgumentNullException("encoder", "Invalid WMEncoder parameter.");
            }

            WMEncProfile2 profile2 = new WMEncProfile2();

            profile2.LoadFromFile(profileFilePath);

            return((IWMEncProfile2)profile2);
        }
Example #15
0
        public void InitializeEncoder()
        {
            try
            {
                frm_Rec        = new WebMeeting.Client.Screen_Capture.frm_Rec();
                config         = new Config();
                config.cfgFile = "WebMeeting.exe.config";

                // create encoder object
                m_encoder = new WMEncoder();
                m_encoder.DisplayInfo.Author      = "Zaeem";
                m_encoder.DisplayInfo.Copyright   = "Uraan Software Solutions";
                m_encoder.DisplayInfo.Description = "Uraan Generated Media File for Screen Recording";
                m_encoder.DisplayInfo.Title       = "Recorded Screen";
                m_encoder.DisplayInfo.Title       = "Recorded Screen";
                m_encoder.DisplayInfo.Rating      = "1";
                m_encoder.DisplayInfo.Description = "This file is Generated through CampusNav developed by Uraan Software Solution";



                // retrive source group collection
                m_sourceGroupCollection = m_encoder.SourceGroupCollection;

                // add a source group to collection
                m_srcGrp = m_sourceGroupCollection.Add("SG_1");

                m_sourceEnumDlg = new SourceEnum();

                // add a screen source
                if (EnumerateAudioSources())
                {
                    m_audSource = m_srcGrp.AddSource(WMENC_SOURCE_TYPE.WMENC_AUDIO);
                    m_audSource.SetInput(m_szAudioSource, "Device", "");
                }

                // set screen as source
                m_screenSource = (IWMEncVideoSource2)m_srcGrp.AddSource(WMENC_SOURCE_TYPE.WMENC_VIDEO);
                m_screenSource.SetInput("ScreenCapture1", "ScreenCap", "");
            }
            catch (Exception exp)
            {
                WebMeeting.Client.ClientUI.getInstance().ShowExceptionMessage("Video Recordong Module ===>Screen Capture.cs line==> 99", exp, "Error Loading Encoder: " + exp.Message.ToString(), false);
                if (MessageBox.Show("Either You do not have required components of Windows Media Encoder or they are corrupted on your Machine: " + /*+exp.Message.ToString() + */ ". Do you want to download now?", "WebMeeting", MessageBoxButtons.YesNo, MessageBoxIcon.Information) == DialogResult.Yes)
                {
                    Win32.Shell32.ShellExecute(0, "Open", WebMeeting.Client.Info.getInstance().WebsiteName + "/wmencoder.exe", "", "", 1);
                }

                //WebMeeting.Client.ClientUI.getInstance().ShowExceptionMessage("Error Stoping encoder: " + exp.Message.ToString());
                //Trace.WriteLine(exp.ToString()+"---"+exp.Message+"---"+exp.Source+exp.StackTrace+"---"+exp.TargetSite+"---"+exp.InnerException);
            }
        }
        private void EncodeFile(EncodingProfileEnum Profile, EncoderInfo Info)
        {
            try
            {
                m_CurrentInfo = Info;
                DateTime Now = DateTime.Now;
                lblStatus.Text = " Starting to encode " + m_CurrentProfile.ToString() +
                                 " Starting time = " + Now.ToLongTimeString();
                m_EncodingDone = false;
                // Create a WMEncoder object.
                m_Encoder = new WMEncoder();
                m_Encoder.OnStateChange += new _IWMEncoderEvents_OnStateChangeEventHandler(
                    OnStateChange);

                // Retrieve the source group collection.
                IWMEncSourceGroupCollection SrcGrpColl = m_Encoder.SourceGroupCollection;

                // Add a source group to the collection.
                IWMEncSourceGroup SrcGrp = SrcGrpColl.Add("SG_1");

                // Add a video and audio source to the source group.
                IWMEncSource SrcAud = SrcGrp.AddSource(WMENC_SOURCE_TYPE.WMENC_AUDIO);
                SrcAud.SetInput(Info.FileNameAndPath, "", "");
                // Specify a file object in which to save encoded content.
                SetOutputFileName(Info.FileNameNoExtension);
                SelectProfile(SrcGrp);

                // Fill in the description object members.
                IWMEncDisplayInfo Descr = m_Encoder.DisplayInfo;
                Descr.Author      = Info.Author;
                Descr.Copyright   = "Valley Bible Church @2005";
                Descr.Description = Info.Description;
                Descr.Rating      = "All Audiences";
                Descr.Title       = Info.MessageTitle;

                // Add an attribute to the collection.
                IWMEncAttributes Attr = m_Encoder.Attributes;
                Attr.Add("URL", "IP address");

                // Start the encoding process.
                // Wait until the encoding process stops before exiting the application.
                m_Encoder.PrepareToEncode(true);
                m_Encoder.Start();
            }
            catch (Exception e)
            {
                lblError.Text = e.ToString();
                Debug.WriteLine(e.ToString());
                m_CurrentInfo = null;
            }
        }
Example #17
0
		/// <summary>
		/// Saves the video.
		/// </summary>
		/// <param name="fileName">Name of the file.</param>
		/// <param name="profileFileName">Name of the profile file.</param>
		/// <param name="dr">Dr.</param>
		public static void SaveVideo(string fileName, string profileFileName, ulong framesPerSecond, SqlDataReader dr)
		{
			WMEncoder encoder = new WMEncoder();
			IWMEncProfile2 profile = WMEncProfile.LoadEncodingProfile(encoder, profileFileName);
			WMEncProfile.ReleaseEncoder(ref encoder);
			
			using(WmvWriter writer = new WmvWriter())
			{
				
				writer.Initialize((IWMProfile)profile.SaveToIWMProfile(), fileName);
				
				VideoInfoHeader viHeader = new VideoInfoHeader();
				writer.FindVideoInputFormat(0, MediaSubTypes.WMMEDIASUBTYPE_RGB24, ref viHeader, false);
				writer.Start();

				
				INSSBuffer sample = null;
				int bmcount = 0;
				Bitmap c = new Bitmap((int)viHeader.bmiHeader.biWidth, (int)viHeader.bmiHeader.biHeight, PixelFormat.Format24bppRgb);;
				ulong fps = viHeader.AvgTimePerFrame / 100000;

				while(dr.Read())
				{
					Bitmap b = Image.FromStream(new MemoryStream(dr.GetValue(1) as byte[])) as Bitmap;
					
					using (Graphics g = Graphics.FromImage(c))
					{
						g.InterpolationMode = InterpolationMode.HighQualityBicubic;
						g.CompositingQuality = CompositingQuality.HighQuality;
						g.SmoothingMode = SmoothingMode.HighQuality;
						g.PixelOffsetMode = PixelOffsetMode.HighQuality;
						g.DrawImage(b, 0, 0, c.Width, c.Height);
					}

					try
					{	
						ulong time = ((ulong)bmcount++ * TimeSpan.TicksPerSecond)/fps;
						sample = writer.GetSampleFromBitmap(c);
						writer.Writer.WriteSample(0, time, (uint)WMT_STREAM_SAMPLE_TYPE.WM_SF_CLEANPOINT, sample);
					}
					finally
					{
						Marshal.ReleaseComObject(sample);
						sample = null;
						b = null;
						GC.Collect();
					}
				}
			}
		}
Example #18
0
        public MediaPusher()
        {
            this.app = new WMEncoderAppClass();

            //WMEncoderAppClass から取得しなければ
            //ブロードキャストが実行できない
            this.enc = (WMEncoder)(this.app.Encoder);

            this.InitDevice();
            this.InitEncodeProfile();
            this.InitBroadCast();

            this.InitEvent();
        }
Example #19
0
        public Encoder(int iChannel, string WMVDirectory)
        {
            if (iChannel < 1 || iChannel > 4)
            {
                Logger.LogError("OysterEncoder.Encoder.Encoder:" + " Invalid channel number specified: " + iChannel);
                throw (new ArgumentOutOfRangeException("iChannel", iChannel, "iChannel can only be between 1 and 4"));
            }
            m_iChannel = iChannel;
            m_bIsEncoderStreaming = false;
            m_bIsEncoderArchiving = false;
            m_sWMVDirectory = WMVDirectory;
            m_sWMVDefaultDirectory = m_sWMVDirectory;
            m_sProfileDirectory = MyPath + PROFILEDIRECTORY;
            if (!Directory.Exists(m_sProfileDirectory))
            {
                throw (new ApplicationException("Profiles directory does not exist in " + m_sProfileDirectory + "."));
            }
            m_encoder = new WMEncoderClass();

            #region sleep code 2/16/2008

            //m_encoder.OnError += m_encoder_OnError;
            //m_encoder.OnClientConnect += m_encoder_OnClientConnect;
            //m_encoder.OnClientDisconnect += m_encoder_OnClientDisconnect;

            #endregion
            #region dead code 2/16/2008

            //try
            //{
            //    _uploadServer =
            //        ConfigurationSettings.AppSettings["UploadServer"];
            //    _uploadPort = Convert.ToInt32(
            //        ConfigurationSettings.AppSettings["UploadPort"]);
            //    _uploadUser =
            //        ConfigurationSettings.AppSettings["UploadUser"];
            //    _uploadPassword =
            //        ConfigurationSettings.AppSettings["UploadPassword"];
            //}
            //catch (Exception e)
            //{
            //    Logger.LogError("AppConfig is invalid. Exiting. Error: " + e.Message);
            //    throw new ApplicationException("AppConfig file information is invalid. Parts may be missing or the wrong type.");
            //}

            #endregion

            Logger.LogInformation("Upload Server set at: " + _uploadServer);
            Logger.LogInformation("Upload Port set at:" + _uploadPort);
        }
Example #20
0
        public MediaPusher()
        {
            this.app = new WMEncoderAppClass();

            //WMEncoderAppClass ����擾���Ȃ����
            //�u���[�h�L���X�g�����s�ł��Ȃ�
            this.enc = (WMEncoder)(this.app.Encoder);

            this.InitDevice();
            this.InitEncodeProfile();
            this.InitBroadCast();

            this.InitEvent();
        }
Example #21
0
        /// <summary>
        /// Saves the video.
        /// </summary>
        /// <param name="fileName">Name of the file.</param>
        /// <param name="profileFileName">Name of the profile file.</param>
        /// <param name="dr">Dr.</param>
        public static void SaveVideo(string fileName, string profileFileName, ulong framesPerSecond, SqlDataReader dr)
        {
            WMEncoder      encoder = new WMEncoder();
            IWMEncProfile2 profile = WMEncProfile.LoadEncodingProfile(encoder, profileFileName);

            WMEncProfile.ReleaseEncoder(ref encoder);

            using (WmvWriter writer = new WmvWriter())
            {
                writer.Initialize((IWMProfile)profile.SaveToIWMProfile(), fileName);

                VideoInfoHeader viHeader = new VideoInfoHeader();
                writer.FindVideoInputFormat(0, MediaSubTypes.WMMEDIASUBTYPE_RGB24, ref viHeader, false);
                writer.Start();


                INSSBuffer sample  = null;
                int        bmcount = 0;
                Bitmap     c       = new Bitmap((int)viHeader.bmiHeader.biWidth, (int)viHeader.bmiHeader.biHeight, PixelFormat.Format24bppRgb);;
                ulong      fps     = viHeader.AvgTimePerFrame / 100000;

                while (dr.Read())
                {
                    Bitmap b = Image.FromStream(new MemoryStream(dr.GetValue(1) as byte[])) as Bitmap;

                    using (Graphics g = Graphics.FromImage(c))
                    {
                        g.InterpolationMode  = InterpolationMode.HighQualityBicubic;
                        g.CompositingQuality = CompositingQuality.HighQuality;
                        g.SmoothingMode      = SmoothingMode.HighQuality;
                        g.PixelOffsetMode    = PixelOffsetMode.HighQuality;
                        g.DrawImage(b, 0, 0, c.Width, c.Height);
                    }

                    try
                    {
                        ulong time = ((ulong)bmcount++ *TimeSpan.TicksPerSecond) / fps;
                        sample = writer.GetSampleFromBitmap(c);
                        writer.Writer.WriteSample(0, time, (uint)WMT_STREAM_SAMPLE_TYPE.WM_SF_CLEANPOINT, sample);
                    }
                    finally
                    {
                        Marshal.ReleaseComObject(sample);
                        sample = null;
                        b      = null;
                        GC.Collect();
                    }
                }
            }
        }
Example #22
0
        public frm_AudioConfig()
        {
            //
            // Required for Windows Form Designer support
            //
            InitializeComponent();
            btn_Previous.Enabled = false;
            btn_Finish.Enabled   = false;

            // Create a WMEncoder object.
            WMEncoder Encoder = new WMEncoder();



            // Retrieve source and device plug-in info manager objects from WMEncoder.
            IWMEncSourcePluginInfoManager        SrcPlugMgr = Encoder.SourcePluginInfoManager;
            IWMEncDeviceControlPluginInfoManager DCPlugMgr  = Encoder.DeviceControlPluginInfoManager;

            // Loop through all the audio and video devices on the system.
            for (int i = 0; i < SrcPlugMgr.Count; i++)
            {
                // Set the IWMEncPluginInfo object to the current plug-in.
                PlugInfo = SrcPlugMgr.Item(i);

                // Find the device plug-ins that support resources.
                if (PlugInfo.SchemeType == "DEVICE" && PlugInfo.Resources == true)
                {
                    // Loop through the resources in the current plug-in.
                    for (int j = 0; j < PlugInfo.Count; j++)
                    {
                        // Add audio resources to the cboAudioSource combo box.
                        if (PlugInfo.MediaType == WMENC_SOURCE_TYPE.WMENC_AUDIO)
                        {
                            cboAudioSource.Items.Add(PlugInfo.Item(j));
                        }
                    }
                }
            }

            cboAudioSource.SelectedIndex = 0;

            //
            // TODO: Add any constructor code after InitializeComponent call
            //
        }
Example #23
0
        public VideoHelper(string saveToPath)
        {
            if (string.IsNullOrEmpty(saveToPath))
            {
                _savetoPath = string.Format(@"{0}\{1}.wmv", Environment.CurrentDirectory, TextHelper.RandomString(10));
            }
            else
            {
                _savetoPath = saveToPath;
            }

            try
            {
                encoder = new WMEncoder();

                IWMEncSourceGroup2          SrcGrp;
                IWMEncSourceGroupCollection SrcGrpColl;
                SrcGrpColl = encoder.SourceGroupCollection;
                SrcGrp     = (IWMEncSourceGroup2)SrcGrpColl.Add("SG_1");
                IWMEncVideoSource2 SrcVid;
                SrcVid = (IWMEncVideoSource2)SrcGrp.AddSource(WMENC_SOURCE_TYPE.WMENC_VIDEO);
                SrcVid.SetInput("ScreenCapture1", "ScreenCap", "");
                IWMEncProfileCollection ProColl;
                IWMEncProfile           Pro;
                int  i;
                long lLength;
                ProColl = encoder.ProfileCollection;
                lLength = ProColl.Count;

                for (i = 0; i < lLength; i++)
                {
                    Pro = ProColl.Item(i);
                    if (Pro.Name == "Screen Video High (CBR)")
                    {
                        SrcGrp.set_Profile((IWMEncProfile)Pro);
                        break;
                    }
                }
            }
            catch (Exception ex)
            {
                throw new Exception(string.Format("{0}\r\nPlease install WMEncoder.exe http://www.microsoft.com/en-us/download/details.aspx?id=17792. \r\n And install WMEncoder Patch http://download.microsoft.com/download/0/3/D/03D35C05-67DA-40E0-9E45-3EA0CA6329A4/WindowsMedia9-KB929182-INTL.exe.", ex.Message));
            }
        }
        private void EncodingCompleted()
        {
            m_EncodingDone = true;
            Debug.WriteLine("Completed pass " + m_CurrentProfile.ToString() +
                            " WMENC_ENCODER_STATE.WMENC_ENCODER_STOPPED");
            lblStatus.Text           = " Finished encoding " + m_CurrentProfile.ToString();
            m_Encoder.OnStateChange -= new _IWMEncoderEvents_OnStateChangeEventHandler(
                OnStateChange);
            m_Encoder = null;
            if (m_AbortRequested == true)
            {
                this.Cursor      = Cursors.Arrow;
                m_CurrentProfile = m_StartingProfile;
                m_CurrentIndex   = 0;
                m_AbortRequested = false;
                return;
            }

            switch (m_CurrentProfile)
            {
            case EncodingProfileEnum.LOW:
                m_CurrentProfile = EncodingProfileEnum.HIGH;
                EncodeFile(m_CurrentProfile, this.m_CurrentInfo);
                break;

            case EncodingProfileEnum.HIGH:
                m_CurrentProfile = EncodingProfileEnum.LOSSLESS;
                EncodeFile(m_CurrentProfile, this.m_CurrentInfo);
                break;

            case EncodingProfileEnum.LOSSLESS:
                m_CurrentIndex++;
                if (m_CurrentIndex >= m_EncodingSourceInfo.Length)
                {
                    this.Cursor = Cursors.Arrow;
                }
                else
                {
                    m_CurrentProfile = m_StartingProfile;
                    EncodeFile(m_CurrentProfile, m_EncodingSourceInfo[m_CurrentIndex]);
                }
                break;
            }
        }
Example #25
0
//        private static void ConfigureAudioProfile(IWMEncProfile2 encProfile, IWMEncAudienceObj aud, WmaStreamSettings audStream)
//        {
//            Logger.WriteLogMessage("Using audio VBR mode [" + audStream.VbrMode + "], bitrate [" + audStream.Bitrate + "], peak bitrate [" + audStream.PeakBitrate + "].");
//
//            switch (audStream.VbrMode)
//            {
//                case TranscoderSettingsBase.VbrModes.BitrateVBR:
//                    encProfile.set_VBRMode(WMENC_SOURCE_TYPE.WMENC_AUDIO, 0, WMENC_PROFILE_VBR_MODE.WMENC_PVM_BITRATE_BASED);
//                    break;
//                case TranscoderSettingsBase.VbrModes.BitrateVBRPeak:
//                    encProfile.set_VBRMode(WMENC_SOURCE_TYPE.WMENC_AUDIO, 0, WMENC_PROFILE_VBR_MODE.WMENC_PVM_PEAK);
//                    aud.set_AudioPeakBitrate(0, audStream.PeakBitrate ?? audStream.Bitrate);
//                    break;
//                case TranscoderSettingsBase.VbrModes.QualityVBR:
//                    encProfile.set_VBRMode(WMENC_SOURCE_TYPE.WMENC_AUDIO, 0, WMENC_PROFILE_VBR_MODE.WMENC_PVM_UNCONSTRAINED);
//                    break;
//                case TranscoderSettingsBase.VbrModes.CBR:
//                    encProfile.set_VBRMode(WMENC_SOURCE_TYPE.WMENC_AUDIO, 0, WMENC_PROFILE_VBR_MODE.WMENC_PVM_NONE);
//                    break;
//            }
//
//            int codec = -1;
//            object codecName;
//            int fourCC;
//
//            Logger.WriteLogMessage("Attempting to enumerate audio codec [" + audStream.CodecName + "].");
//
//            for (int i = 0; i < encProfile.AudioCodecCount; i++)
//            {
//                fourCC = encProfile.EnumAudioCodec(i, out codecName);
//
//                if (audStream.CodecName == (string)codecName)
//                {
//                    codec = i;
//                    break;
//                }
//            }
//
//            if (codec < 0)
//                throw new Common.InvalidOperationException("Failed to locate audio codec [" + audStream.CodecName + "].");
//
//            Logger.WriteLogMessage("Using audio codec [" + audStream.CodecName + "], index [" + codec + "].");
//
//            aud.set_AudioCodec(0, codec);
//
//            Logger.WriteLogMessage("Using audio sample rate [" + audStream.SampleRate + "], channels [" + audStream.Channels + "], bits per sample [" + audStream.BitsPerSample + "], .");
//
//            aud.SetAudioConfig(0, (short)audStream.Channels, (int)audStream.SampleRate, audStream.Bitrate, (short)audStream.BitsPerSample);
//
//            Logger.WriteLogMessage("Configured audio profile.");
//        }

        public static void ReleaseEncoder(ref WMEncoder encoder)
        {
            if (encoder == null)
            {
                return;
            }

            try
            {
                Logger.WriteLogMessage("Attempting to stop WMEncoder application, state: " + encoder.RunState + ".");

                if (encoder.RunState != WMENC_ENCODER_STATE.WMENC_ENCODER_STOPPED)
                {
                    encoder.Stop();
                }

                encoder.Reset();

                Logger.WriteLogMessage("Successfully stopped WMEncoder application, state: " + encoder.RunState + ".");
            }
            catch (COMException e)
            {
                Logger.WriteLogError("Failed to kill WMEncoder application. HRESULT [" + String.Format("0x{0:x}", e.ErrorCode) + "].", e);
            }
            catch (Exception e)
            {
                Logger.WriteLogError("Failed to kill WMEncoder application.", e);
            }
            finally
            {
                Logger.WriteLogMessage("Releasing runtime callable wrapper.");

                while (Marshal.ReleaseComObject(encoder) > 0)
                {
                    Logger.WriteLogMessage("Releasing runtime callable wrapper again.");
                }

                encoder = null;

                Logger.WriteLogMessage("Successfully killed WMEncoder application.");
            }
        }
Example #26
0
        public frm_AudioConfig()
        {
            //
            // Required for Windows Form Designer support
            //
            InitializeComponent();
            btn_Previous.Enabled=false;
            btn_Finish.Enabled=false;

            // Create a WMEncoder object.
            WMEncoder Encoder = new WMEncoder();

            // Retrieve source and device plug-in info manager objects from WMEncoder.
            IWMEncSourcePluginInfoManager SrcPlugMgr = Encoder.SourcePluginInfoManager;
            IWMEncDeviceControlPluginInfoManager DCPlugMgr = Encoder.DeviceControlPluginInfoManager;

            // Loop through all the audio and video devices on the system.
            for (int i = 0; i < SrcPlugMgr.Count; i++)
            {
                // Set the IWMEncPluginInfo object to the current plug-in.
                PlugInfo = SrcPlugMgr.Item(i);

                // Find the device plug-ins that support resources.
                if (PlugInfo.SchemeType == "DEVICE" && PlugInfo.Resources == true)
                {
                    // Loop through the resources in the current plug-in.
                    for (int j = 0; j<PlugInfo.Count; j++)
                    {
                        // Add audio resources to the cboAudioSource combo box.
                        if (PlugInfo.MediaType == WMENC_SOURCE_TYPE.WMENC_AUDIO)
                            cboAudioSource.Items.Add(PlugInfo.Item(j));

                    }
                }
            }

            cboAudioSource.SelectedIndex=0;

            //
            // TODO: Add any constructor code after InitializeComponent call
            //
        }
Example #27
0
        /**
         * Constructor.
         */
        public Encoder()
        {
            this.enableRecording = false;
            this.chopNumber      = 0;
            this.chopLength      = -1;

            this.choppingTimer                = new System.Timers.Timer();
            this.choppingTimer.Elapsed       += this.OnRecordTimeElapsed;
            this.archiveState                 = WMENC_ARCHIVE_STATE.WMENC_ARCHIVE_STOPPED;
            this.stateChangeWaitHandle        = new System.Threading.EventWaitHandle(false, System.Threading.EventResetMode.ManualReset, string.Empty);
            this.archiveStateChangeWaitHandle = new System.Threading.EventWaitHandle(false, System.Threading.EventResetMode.ManualReset, string.Empty);

            // Audio and video sources
            this.audioSource = null;
            this.videoSource = null;

            // Windows Media Encoder
            this.wmEncoder        = new WMEncoderClass();
            this.sourceGroup      = (IWMEncSourceGroup2)this.wmEncoder.SourceGroupCollection.Add("SG_1");
            this.wmEncoderProfile = new WMEncProfile2();

            // For now, we only listen these events
            this.wmEncoder.OnStateChange        += this.OnStateChange;
            this.wmEncoder.OnError              += this.OnError;
            this.wmEncoder.OnArchiveStateChange += this.OnArchiveStateChange;

            // Set recording props.
            this.wmEncoder.EnableAutoArchive = false;
            this.wmEncoder.AutoIndex         = false;

            // Set default profile values
            this.wmEncoderProfile.ValidateMode = true;
            this.wmEncoderProfile.ProfileName  = "Windows Media Encoder Profile";
            this.wmEncoderProfile.ContentType  = 17;                                        // Audio + Video
            this.wmEncoderAudience             = this.wmEncoderProfile.AddAudience(100000); // Initial bitrate = 100 kbps, will change automatically
            // when user sets video and audio params.
        }
Example #28
0
		/// <summary>
		/// Saves the video.
		/// </summary>
		/// <param name="fileName">Name of the file.</param>
		/// <param name="profileFileName">Name of the profile file.</param>
		/// <param name="framesPerSecond">Frames per second.</param>
		/// <param name="bitmaps">Bitmaps.</param>
        public WmvEncoder(string profileFileName, ulong framesPerSecond)
        {
            try
            {
                WMEncoder encoder = new WMEncoder();
                IWMEncProfile2 profile = WMEncProfile.LoadEncodingProfile(encoder, profileFileName);
                WMEncProfile.ReleaseEncoder(ref encoder);

                writer = new WmvWriter();
                writer.SetProfile((IWMProfile)profile.SaveToIWMProfile());

                viHeader = new VideoInfoHeader();
                bool bret = writer.FindVideoInputFormat(0, MediaSubTypes.WMMEDIASUBTYPE_RGB24, ref viHeader, false);
                if (!bret) throw new Exception("FindVideoInputFormat error"); ;
                frame = new Bitmap((int)viHeader.bmiHeader.biWidth, (int)viHeader.bmiHeader.biHeight, PixelFormat.Format24bppRgb);

                fps = framesPerSecond;
            }
            catch (Exception)
            {
                // error handle
                throw;
            }
        }
Example #29
0
        private void Screencast_Load(object sender, EventArgs e)
        {
            // 实例化Windows Media Encoder编码器
            enc = new WMEncoderClass();
            int index = 0;
            int i     = 0;

            foreach (IWMEncProfile wp in enc.ProfileCollection)
            {// 将编码器Profile名称填充到cmbEncoder下拉框
                i++;
                cmbEncoder.Items.Add(wp.Name);
                // 存在"屏幕视频 - 高(CBR)"这一Profile则选中它
                if (index == 0 && wp.Name.Equals("屏幕视频 - 高(CBR)"))
                {
                    index = i;
                }
            }
            cmbEncoder.SelectedIndex = index;
            enc = null;

            txtFileName.Text = Application.StartupPath + "\\test.wmv";
            btnStart.Enabled = true;
            btnStop.Enabled  = false;
        }
Example #30
0
        /**
         * Constructor.
         */
        public Encoder()
        {
            this.enableRecording = false;
            this.chopNumber = 0;
            this.chopLength = -1;

            this.choppingTimer = new System.Timers.Timer();
            this.choppingTimer.Elapsed += this.OnRecordTimeElapsed;
            this.archiveState = WMENC_ARCHIVE_STATE.WMENC_ARCHIVE_STOPPED;
            this.stateChangeWaitHandle = new System.Threading.EventWaitHandle(false, System.Threading.EventResetMode.ManualReset, string.Empty);
            this.archiveStateChangeWaitHandle = new System.Threading.EventWaitHandle(false, System.Threading.EventResetMode.ManualReset, string.Empty);

            // Audio and video sources
            this.audioSource = null;
            this.videoSource = null;

            // Windows Media Encoder
            this.wmEncoder = new WMEncoderClass();
            this.sourceGroup = (IWMEncSourceGroup2)this.wmEncoder.SourceGroupCollection.Add("SG_1");
            this.wmEncoderProfile = new WMEncProfile2();

            // For now, we only listen these events
            this.wmEncoder.OnStateChange += this.OnStateChange;
            this.wmEncoder.OnError += this.OnError;
            this.wmEncoder.OnArchiveStateChange += this.OnArchiveStateChange;

            // Set recording props.
            this.wmEncoder.EnableAutoArchive = false;
            this.wmEncoder.AutoIndex = false;

            // Set default profile values
            this.wmEncoderProfile.ValidateMode = true;
            this.wmEncoderProfile.ProfileName = "Windows Media Encoder Profile";
            this.wmEncoderProfile.ContentType = 17; // Audio + Video
            this.wmEncoderAudience = this.wmEncoderProfile.AddAudience(100000); // Initial bitrate = 100 kbps, will change automatically
            // when user sets video and audio params.
        }
Example #31
0
        private void btnStart_Click(object sender, EventArgs e)
        {
            // 实例化Windows Media Encoder编码器
            enc = new WMEncoderClass();
            IWMEncSourceGroupCollection SrcGrpColl;
            IWMEncSourceGroup2          SrcGrp;
            // 音频源
            //IWMEncAudioSource SrcAud;
            // 视频源
            IWMEncVideoSource2 SrcVid;

            //IWMEncProfile2 Pro = new WMEncProfile2Class();

            try
            {
                SrcGrpColl = enc.SourceGroupCollection;
                SrcGrp     = (IWMEncSourceGroup2)SrcGrpColl.Add("SG_1");
                SrcVid     = (IWMEncVideoSource2)SrcGrp.AddSource(WMENC_SOURCE_TYPE.WMENC_VIDEO);

                Screen currentScreen;
                if (hWndURWPGSim2D == 0)
                {// 获取当前窗口所在屏幕作为当前屏幕
                    currentScreen = Screen.FromHandle(this.Handle);
                }
                else
                {// 获取待屏幕录像的URWPGSim2D程序主窗口所在屏幕作为当前屏幕
                    currentScreen  = Screen.FromHandle((IntPtr)hWndURWPGSim2D);
                    hWndURWPGSim2D = 0;
                }
                // 以当前屏幕设备作为视频来源设备
                SrcVid.SetInput(currentScreen.DeviceName, "ScreenCap", "");
                //SrcVid.SetInput("ScreenCapture1", "ScreenCap", "");

                // 设置音频来源
                //if (ckbSound.Checked)
                //{
                //    SrcAud = (IWMEncAudioSource)SrcGrp.AddSource(WMENC_SOURCE_TYPE.WMENC_AUDIO);
                //    SrcAud.SetInput("Default_Audio_Device", "DEVICE", "");
                //}

                foreach (IWMEncProfile wp in enc.ProfileCollection)
                {     // 循环检查当前编码器实例中包含的全部配置文件
                    if (wp.Name.Equals(cmbEncoder.SelectedItem.ToString()))
                    { // 如果当前配置文件(Profile)名称与选中的移植
                        // 将当前Profile设为当前视频源的配置文件
                        SrcGrp.set_Profile(wp);
                        break;
                    }
                }

                // 为当前编码器实例设定输出文件名称
                enc.File.LocalFileName = txtFileName.Text;

                // 从界面输入取得待录屏区域左上角坐标/宽度/高度(单位为像素)
                int x = Convert.ToInt32(txtX.Text);
                int y = Convert.ToInt32(txtY.Text);
                int w = Convert.ToInt32(txtWidth.Text);
                int h = Convert.ToInt32(txtHeight.Text);

                // 适应多显示器环境 取得当前系统所有显示器构成的虚拟屏幕区域
                Rectangle screenRect = SystemInformation.VirtualScreen;

                #region
                //// 为当前视频源设定宽度为当前屏幕宽度
                //SrcVid.Width = currentScreen.Bounds.Width;
                //// 为当前视频源设定高度为当前屏幕高度
                //SrcVid.Height = currentScreen.Bounds.Height;

                //// 对当前视频源进行裁剪 裁剪后的视频宽度高度即为待录像区域宽度高度
                //// 左边裁掉待录像区域左上角坐标X值的大小
                //SrcVid.CroppingLeftMargin = x;
                //// 上边裁掉待录像区域左上角坐标Y值的大小
                //SrcVid.CroppingTopMargin = y;
                //// 右边裁掉总宽度和左边裁剪尺寸、待录像区域宽度之差
                //SrcVid.CroppingRightMargin = SrcVid.Width - SrcVid.CroppingLeftMargin - w;
                //// 下边裁掉总高度和上边裁剪尺寸、待录像区域高度之差
                //SrcVid.CroppingBottomMargin = SrcVid.Height - SrcVid.CroppingTopMargin - h;
                #endregion

                #region
                //int wm = SystemInformation.VirtualScreen.Width;
                //int hm = SystemInformation.VirtualScreen.Height;

                //SrcVid.Width = w;
                //SrcVid.Height = h;

                //float rx = (float)wm / (float)SrcVid.Width;
                //float ry = (float)hm / (float)SrcVid.Height;

                //SrcVid.CroppingLeftMargin = (int)(x / rx);
                //SrcVid.CroppingTopMargin = (int)(y / ry);
                //SrcVid.CroppingRightMargin = (int)((wm - x - w) / rx);
                //SrcVid.CroppingBottomMargin = (int)((hm - y - h) / ry);
                #endregion

                #region
                // 为当前视频源设定宽度为整个虚拟屏幕宽度
                SrcVid.Width = screenRect.Width;
                // 为当前视频源设定高度为整个虚拟屏幕高度
                SrcVid.Height = screenRect.Height;

                // 对当前视频源进行裁剪 裁剪后的视频宽度高度即为待录像区域宽度高度
                // 左边裁掉待录像区域左上角坐标X值与虚拟屏幕左上角坐标X值之差
                SrcVid.CroppingLeftMargin = x - screenRect.Left;
                // 上边裁掉待录像区域左上角坐标Y值与虚拟屏幕左上角坐标Y值之差
                SrcVid.CroppingTopMargin = y - screenRect.Top;
                // 右边裁掉总宽度和左边裁剪尺寸、待录像区域宽度之差
                SrcVid.CroppingRightMargin = SrcVid.Width - SrcVid.CroppingLeftMargin - w;
                // 下边裁掉总高度和上边裁剪尺寸、待录像区域高度之差
                SrcVid.CroppingBottomMargin = SrcVid.Height - SrcVid.CroppingTopMargin - h;
                #endregion

                #region
                //SrcVid.Width = w;
                //SrcVid.Height = h;

                //float rx = (float)screenRect.Width / (float)SrcVid.Width;
                //float ry = (float)screenRect.Height / (float)SrcVid.Height;

                //SrcVid.CroppingLeftMargin = (int)((x - screenRect.Left) / rx);
                //SrcVid.CroppingTopMargin = (int)((y - screenRect.Top) / ry);
                //SrcVid.CroppingRightMargin = (int)((screenRect.Width - (x - screenRect.Left) - w) / rx);
                //SrcVid.CroppingBottomMargin = (int)((screenRect.Height - (y - screenRect.Top) - h) / ry);
                #endregion

                // 最小化Screencast程序主窗口
                this.WindowState = FormWindowState.Minimized;

                // 开始编码
                enc.Start();
                btnStop.Enabled  = true;
                btnStart.Enabled = false;
                this.TopMost     = false;
            }
            catch (Exception e1)
            {
                MessageBox.Show(e1.Message);
            }
        }
Example #32
0
		/// <summary>
		/// Saves the video.
		/// </summary>
		/// <param name="fileName">Name of the file.</param>
		/// <param name="profileFileName">Name of the profile file.</param>
		/// <param name="files">Files.</param>
		public static void SaveVideo(string fileName, string profileFileName, ulong framesPerSecond, string [] files)
		{
			WMEncoder encoder = new WMEncoder();
			IWMEncProfile2 profile = WMEncProfile.LoadEncodingProfile(encoder, profileFileName);
			WMEncProfile.ReleaseEncoder(ref encoder);
			
			using(WmvWriter writer = new WmvWriter())
			{
				
				writer.Initialize((IWMProfile)profile.SaveToIWMProfile(), fileName);
				
				VideoInfoHeader viHeader = new VideoInfoHeader();
				writer.FindVideoInputFormat(0, MediaSubTypes.WMMEDIASUBTYPE_RGB24, ref viHeader, false);
				writer.Start();

				INSSBuffer sample = null;
				int bmcount = 0;
				Bitmap frame = new Bitmap((int)viHeader.bmiHeader.biWidth, (int)viHeader.bmiHeader.biHeight, PixelFormat.Format24bppRgb);;
				ulong fps = framesPerSecond;	
				
				for(int i = 0; i < files.Length; i++)
				{
					if(files[i] != null)
					{		
						Bitmap bmp = new Bitmap(files[i]);
						using (Graphics g = Graphics.FromImage(frame))
						{
							g.InterpolationMode = InterpolationMode.HighQualityBicubic;
							g.CompositingQuality = CompositingQuality.HighQuality;
							g.SmoothingMode = SmoothingMode.HighQuality;
							g.PixelOffsetMode = PixelOffsetMode.HighQuality;
							g.DrawImage(bmp, 0, 0, frame.Width, frame.Height);
							Console.Out.Write(".");
						}

						// Now render to the movie
						try
						{	
							ulong time = ((ulong)bmcount++ * TimeSpan.TicksPerSecond)/fps;
							sample = writer.GetSampleFromBitmap(frame);
							writer.Writer.WriteSample(0, time, (uint)WMT_STREAM_SAMPLE_TYPE.WM_SF_CLEANPOINT, sample);
						}
						finally
						{													
							Marshal.ReleaseComObject(sample);
							sample = null;
							bmp = null;
							GC.Collect();
						}
					}
				}
			}
		}
        private Hashtable profiles     = new Hashtable(); // 压缩方式集

        public WMVEncoder()
        {
            encoder = new WMEncoderClass();
        }
        void _backgroundWorker_DoWork(object sender, DoWorkEventArgs e)
        {
            string                  glbstrErrLocation;
            WMEncoder               Encoder    = null;
            WMEncProfile2           Profile    = null;
            IWMDRMContentAuthor     DRMAuthor  = null;
            IWMDRMProfileCollection DRMProColl = null;
            IWMDRMProfile           DRMPro     = null;
            IWMEncSourceGroup       SrcGrp     = null;
            IWMEncAudioSource       SrcAud     = null;
            IWMEncVideoSource2      SrcVid     = null;

            _TwoPassEncoding = false;


            bool glbboolEncodingContinue = true;;

            DateTime time = DateTime.Now;

            try
            {
                Encoder = new WMEncoder();
                Encoder.OnStateChange += new _IWMEncoderEvents_OnStateChangeEventHandler(this.Encoder_OnStateChange);
                _SrcGrpColl            = Encoder.SourceGroupCollection;

                try
                {
                    DRMAuthor  = Encoder.EncoderDRMContentAuthor;
                    DRMProColl = DRMAuthor.DRMProfileCollection;
                    DRMPro     = null;

                    object vKeyID = null;
                    if (_encodeInfo.DRMProfile != "None")
                    {
                        int intDRMProCount = 0;
                        for (intDRMProCount = 0; intDRMProCount <= DRMProColl.Count - 1; intDRMProCount++)
                        {
                            if (DRMProColl.Item(intDRMProCount).Name == _encodeInfo.DRMProfile)
                            {
                                DRMPro = DRMProColl.Item(intDRMProCount);
                                break;
                            }
                        }
                        DRMAuthor.SetSessionDRMProfile(DRMPro.ID, ref vKeyID);
                    }
                    else
                    {
                        DRMAuthor.SetSessionDRMProfile(System.DBNull.Value.ToString(), ref vKeyID);
                        DRMAuthor  = null;
                        DRMProColl = null;
                        DRMPro     = null;
                        vKeyID     = null;
                    }
                }
                catch (Exception ex)
                {
                    glbstrErrLocation = "Specify DRM Profile - " + ex.Message.ToString();
                    throw new ApplicationException(glbstrErrLocation, ex);
                }
                Profile = new WMEncProfile2();
                Int32 intProContentType  = 0;
                int   intProVBRModeAudio = 0;
                int   intProVBRModeVideo = 0;
                try
                {
                    Profile.LoadFromFile(_encodeInfo.Profile);
                    intProContentType  = Profile.ContentType;
                    intProVBRModeAudio = (int)Profile.get_VBRMode(WMENC_SOURCE_TYPE.WMENC_AUDIO, 0);
                    intProVBRModeVideo = (int)Profile.get_VBRMode(WMENC_SOURCE_TYPE.WMENC_VIDEO, 0);
                }
                catch (Exception ex)
                {
                    glbstrErrLocation = "Load Profile - " + ex.Message.ToString();
                    throw new ApplicationException(glbstrErrLocation, ex);
                }

                try
                {
                    SrcGrp = _SrcGrpColl.Add("BatchEncode");
                }
                catch (Exception ex)
                {
                    glbstrErrLocation = "Source Group - " + ex.Message.ToString();
                    throw new ApplicationException(glbstrErrLocation, ex);
                }
                string strDestExtension = System.IO.Path.GetExtension(_encodeInfo.Destination);

                try
                {
                    if (intProContentType == 1)
                    {
                        SrcAud = (WMEncoderLib.IWMEncAudioSource)SrcGrp.AddSource(WMENC_SOURCE_TYPE.WMENC_AUDIO);
                        SrcAud.SetInput(_encodeInfo.Source, "", "");
                    }
                    else if (intProContentType == 16)
                    {
                        SrcVid = (WMEncoderLib.IWMEncVideoSource2)SrcGrp.AddSource(WMENC_SOURCE_TYPE.WMENC_VIDEO);
                        SrcVid.SetInput(_encodeInfo.Source, "", "");
                    }
                    else if (intProContentType == 17)
                    {
                        SrcAud = (WMEncoderLib.IWMEncAudioSource)SrcGrp.AddSource(WMENC_SOURCE_TYPE.WMENC_AUDIO);
                        SrcAud.SetInput(_encodeInfo.Source, "", "");
                        SrcVid = (WMEncoderLib.IWMEncVideoSource2)SrcGrp.AddSource(WMENC_SOURCE_TYPE.WMENC_VIDEO);
                        SrcVid.SetInput(_encodeInfo.Source, "", "");
                    }
                    else
                    {
                        _backgroundWorker.ReportProgress(0, "BatchEncode does not support this type of profile");
                    }
                }
                catch (Exception ex)
                {
                    glbstrErrLocation = "Video / Audio Source - " + ex.Message.ToString();
                    throw new ApplicationException(glbstrErrLocation, ex);
                }
                try
                {
                    SrcGrp.set_Profile(Profile);
                }
                catch (Exception ex)
                {
                    glbstrErrLocation = "Encoding Profile - " + ex.Message.ToString();

                    throw new ApplicationException(glbstrErrLocation, ex);
                }
                IWMEncDisplayInfo Descr = Encoder.DisplayInfo;
                try
                {
                    if (_encodeInfo.Title != "")
                    {
                        Descr.Title = _encodeInfo.Title;
                    }
                    if (_encodeInfo.Description != "")
                    {
                        Descr.Description = _encodeInfo.Description;
                    }
                    if (_encodeInfo.Author != "")
                    {
                        Descr.Author = _encodeInfo.Author;
                    }
                    if (_encodeInfo.Copyright != "")
                    {
                        Descr.Copyright = _encodeInfo.Copyright;
                    }
                }
                catch (Exception ex)
                {
                    glbstrErrLocation = "Display Information - " + ex.Message.ToString();
                    throw new ApplicationException(glbstrErrLocation, ex);
                }
                try
                {
                    if (intProContentType == 16 || intProContentType == 17)
                    {
                        if (_encodeInfo.Crop == true)
                        {
                            SrcVid.CroppingBottomMargin = (int)_encodeInfo.CropBottom;
                            SrcVid.CroppingTopMargin    = (int)_encodeInfo.CropTop;
                            SrcVid.CroppingLeftMargin   = (int)_encodeInfo.CropLeft;
                            SrcVid.CroppingRightMargin  = (int)_encodeInfo.CropRight;
                        }
                    }
                }
                catch (Exception ex)
                {
                    glbstrErrLocation = "Cropping - " + ex.Message.ToString();
                    throw new ApplicationException(glbstrErrLocation, ex);
                }
                try
                {
                    if (intProContentType == 16 || intProContentType == 17)
                    {
                        SrcVid.Optimization = _encodeInfo.Preproc;
                    }
                }
                catch (Exception ex)
                {
                    glbstrErrLocation = "Video Optimization - " + ex.Message.ToString();
                    throw new ApplicationException(glbstrErrLocation, ex);
                }

                try
                {
                    if (intProContentType == 1)
                    {
                        if (_encodeInfo.TwoPass == false)
                        {
                            SrcAud.PreProcessPass = 0;
                            _TwoPassEncoding      = false;
                        }
                        else
                        {
                            SrcAud.PreProcessPass = 1;
                            _TwoPassEncoding      = true;
                            glbPassNumber         = 1;
                        }
                    }
                    else if (intProContentType == 16)
                    {
                        if (_encodeInfo.TwoPass == false)
                        {
                            SrcVid.PreProcessPass = 0;
                            _TwoPassEncoding      = false;
                        }
                        else
                        {
                            SrcVid.PreProcessPass = 1;
                            _TwoPassEncoding      = true;
                            glbPassNumber         = 1;
                        }
                    }
                    else if (intProContentType == 17)
                    {
                        if (_encodeInfo.TwoPass == false)
                        {
                            SrcAud.PreProcessPass = 0;
                            SrcVid.PreProcessPass = 0;
                            _TwoPassEncoding      = false;
                        }
                        else
                        {
                            switch (intProVBRModeAudio)
                            {
                            case 1:
                                SrcAud.PreProcessPass = 1;
                                break;

                            case 2:
                                SrcAud.PreProcessPass = 1;
                                break;

                            case 3:
                                SrcAud.PreProcessPass = 0;
                                break;

                            case 4:
                                SrcAud.PreProcessPass = 1;
                                break;
                            }
                            switch (intProVBRModeVideo)
                            {
                            case 1:
                                SrcVid.PreProcessPass = 1;
                                break;

                            case 2:
                                SrcVid.PreProcessPass = 1;
                                break;

                            case 3:
                                SrcVid.PreProcessPass = 0;
                                break;

                            case 4:
                                SrcVid.PreProcessPass = 1;
                                break;
                            }
                            _TwoPassEncoding = true;
                            glbPassNumber    = 1;
                        }
                    }
                    else
                    {
                        _backgroundWorker.ReportProgress(0, "BatchEncode does not support this type of profile");
                    }
                }
                catch (Exception ex)
                {
                    glbstrErrLocation = "Passes - " + ex.Message.ToString();
                    throw new ApplicationException(glbstrErrLocation, ex);
                }
                IWMEncFile2 File = (IWMEncFile2)Encoder.File;
                try
                {
                    File.LocalFileName = _encodeInfo.Destination;
                }
                catch (Exception ex)
                {
                    glbstrErrLocation = "Output File - " + ex.Message.ToString();
                    throw new ApplicationException(glbstrErrLocation, ex);
                }
                int intDurationAudio = 0;
                int intDurationVideo = 0;
                int intDurationFinal;
                try
                {
                    _backgroundWorker.ReportProgress(0, "Preparing to encode");
                    Encoder.PrepareToEncode(true);
                }
                catch (Exception ex)
                {
                    glbstrErrLocation = "Encoder Prepare - " + ex.Message.ToString();


                    throw new ApplicationException(glbstrErrLocation, ex);
                }
                try
                {
                    if (SrcAud != null)
                    {
                        intDurationAudio = System.Convert.ToInt32(SrcAud.Duration / 1000);
                    }
                }
                catch (Exception)
                {
                }
                try
                {
                    if (SrcVid != null)
                    {
                        intDurationVideo = System.Convert.ToInt32(SrcVid.Duration / 1000);
                    }
                }
                catch (Exception)
                {
                }
                if (intDurationAudio == 0)
                {
                    intDurationFinal = intDurationVideo;
                }
                else if (intDurationVideo == 0)
                {
                    intDurationFinal = intDurationAudio;
                }
                else
                {
                    if (intDurationVideo >= intDurationAudio)
                    {
                        intDurationFinal = intDurationVideo;
                    }
                    else
                    {
                        intDurationFinal = intDurationAudio;
                    }
                }
                glbintSourceDuration = intDurationFinal;
                try
                {
                    if (glbboolEncodingContinue == true)
                    {
                        Encoder.Start();
                        do
                        {
                            if (_backgroundWorker.CancellationPending)
                            {
                                Encoder.Stop();
                                e.Cancel = true;
                                _ev.Set();
                            }

                            sReportPercentComplete(Encoder);
                        }while (!_ev.WaitOne(1000));
                    }
                }
                catch (Exception ex)
                {
                    glbstrErrLocation = "Encoder Start - " + ex.Message.ToString();
                    throw new ApplicationException(glbstrErrLocation, ex);
                }
                if (e.Cancel)
                {
                    return;
                }
                else
                {
                    _backgroundWorker.ReportProgress(0, "Encoding Complete");
                    return;
                }
            }
            finally
            {
                if (_SrcGrpColl != null)
                {
                    try
                    {
                        Encoder.Stop();
                        _SrcGrpColl.Remove(0);
                    }
                    catch
                    {
                    }
                    Marshal.ReleaseComObject(_SrcGrpColl);
                    _SrcGrpColl = null;
                }
                if (Profile != null)
                {
                    Marshal.ReleaseComObject(Profile);
                    Profile = null;
                }
                if (Encoder != null)
                {
                    Encoder.OnStateChange -= new _IWMEncoderEvents_OnStateChangeEventHandler(this.Encoder_OnStateChange);
                    Marshal.ReleaseComObject(Encoder);
                    Encoder = null;
                }
                e.Result = DateTime.Now - time;
            }
        }
Example #35
0
//        private static void ConfigureAudioProfile(IWMEncProfile2 encProfile, IWMEncAudienceObj aud, WmaStreamSettings audStream)
//        {
//            Logger.WriteLogMessage("Using audio VBR mode [" + audStream.VbrMode + "], bitrate [" + audStream.Bitrate + "], peak bitrate [" + audStream.PeakBitrate + "].");
//
//            switch (audStream.VbrMode)
//            {
//                case TranscoderSettingsBase.VbrModes.BitrateVBR:
//                    encProfile.set_VBRMode(WMENC_SOURCE_TYPE.WMENC_AUDIO, 0, WMENC_PROFILE_VBR_MODE.WMENC_PVM_BITRATE_BASED);
//                    break;
//                case TranscoderSettingsBase.VbrModes.BitrateVBRPeak:
//                    encProfile.set_VBRMode(WMENC_SOURCE_TYPE.WMENC_AUDIO, 0, WMENC_PROFILE_VBR_MODE.WMENC_PVM_PEAK);
//                    aud.set_AudioPeakBitrate(0, audStream.PeakBitrate ?? audStream.Bitrate);
//                    break;
//                case TranscoderSettingsBase.VbrModes.QualityVBR:
//                    encProfile.set_VBRMode(WMENC_SOURCE_TYPE.WMENC_AUDIO, 0, WMENC_PROFILE_VBR_MODE.WMENC_PVM_UNCONSTRAINED);
//                    break;
//                case TranscoderSettingsBase.VbrModes.CBR:
//                    encProfile.set_VBRMode(WMENC_SOURCE_TYPE.WMENC_AUDIO, 0, WMENC_PROFILE_VBR_MODE.WMENC_PVM_NONE);
//                    break;
//            }
//
//            int codec = -1;
//            object codecName;
//            int fourCC;
//
//            Logger.WriteLogMessage("Attempting to enumerate audio codec [" + audStream.CodecName + "].");
//
//            for (int i = 0; i < encProfile.AudioCodecCount; i++)
//            {
//                fourCC = encProfile.EnumAudioCodec(i, out codecName);
//
//                if (audStream.CodecName == (string)codecName)
//                {
//                    codec = i;
//                    break;
//                }
//            }
//
//            if (codec < 0)
//                throw new Common.InvalidOperationException("Failed to locate audio codec [" + audStream.CodecName + "].");
//
//            Logger.WriteLogMessage("Using audio codec [" + audStream.CodecName + "], index [" + codec + "].");
//
//            aud.set_AudioCodec(0, codec);
//
//            Logger.WriteLogMessage("Using audio sample rate [" + audStream.SampleRate + "], channels [" + audStream.Channels + "], bits per sample [" + audStream.BitsPerSample + "], .");
//
//            aud.SetAudioConfig(0, (short)audStream.Channels, (int)audStream.SampleRate, audStream.Bitrate, (short)audStream.BitsPerSample);
//
//            Logger.WriteLogMessage("Configured audio profile.");
//        }

        public static void ReleaseEncoder(ref WMEncoder encoder)
		{
			if (encoder == null)
				return;

			try
			{
				Logger.WriteLogMessage("Attempting to stop WMEncoder application, state: " + encoder.RunState + ".");

				if (encoder.RunState != WMENC_ENCODER_STATE.WMENC_ENCODER_STOPPED)
					encoder.Stop();

				encoder.Reset();

				Logger.WriteLogMessage("Successfully stopped WMEncoder application, state: " + encoder.RunState + ".");
			}
			catch (COMException e)
			{
				Logger.WriteLogError("Failed to kill WMEncoder application. HRESULT [" + String.Format("0x{0:x}", e.ErrorCode) + "].", e);
			}
			catch (Exception e)
			{
				Logger.WriteLogError("Failed to kill WMEncoder application.", e);
			}
			finally
			{
				Logger.WriteLogMessage("Releasing runtime callable wrapper.");

				while (Marshal.ReleaseComObject(encoder) > 0)
				{
					Logger.WriteLogMessage("Releasing runtime callable wrapper again.");
				}

				encoder = null;

				Logger.WriteLogMessage("Successfully killed WMEncoder application.");
			}
		}
Example #36
0
    static void Main()
    {
        try
        {
            // Create a WMEncoder object.
            WMEncoder Encoder = new WMEncoder();

            // Retrieve the source group collection.
            IWMEncSourceGroupCollection SrcGrpColl = Encoder.SourceGroupCollection;

            // Add a source group to the collection.
            IWMEncSourceGroup SrcGrp = SrcGrpColl.Add("SG_1");

            // Add a video and audio source to the source group.
            IWMEncSource SrcAud = SrcGrp.AddSource(WMENC_SOURCE_TYPE.WMENC_AUDIO);
            SrcAud.SetInput("C:\\Inputfile.mpg", "", "");

            IWMEncVideoSource2 SrcVid = (IWMEncVideoSource2)SrcGrp.AddSource(WMENC_SOURCE_TYPE.WMENC_VIDEO);
            SrcVid.SetInput("C:\\Inputfile.mpg", "", "");

            // Crop 2 pixels from each edge of the video image.
            SrcVid.CroppingBottomMargin = 2;
            SrcVid.CroppingTopMargin    = 2;
            SrcVid.CroppingLeftMargin   = 2;
            SrcVid.CroppingRightMargin  = 2;

            // Specify a file object in which to save encoded content.
            IWMEncFile File = Encoder.File;
            File.LocalFileName = "C:\\OutputFile.wmv";

            // Choose a profile from the collection.
            IWMEncProfileCollection ProColl = Encoder.ProfileCollection;
            IWMEncProfile           Pro;
            for (int i = 0; i < ProColl.Count; i++)
            {
                Pro = ProColl.Item(i);
                if (Pro.Name == "Windows Media Video 8 for Local Area Network (384 Kbps)")
                {
                    SrcGrp.set_Profile(Pro);
                    break;
                }
            }

            // Fill in the description object members.
            IWMEncDisplayInfo Descr = Encoder.DisplayInfo;
            Descr.Author      = "Author name";
            Descr.Copyright   = "Copyright information";
            Descr.Description = "Text description of encoded content";
            Descr.Rating      = "Rating information";
            Descr.Title       = "Title of encoded content";

            // Add an attribute to the collection.
            IWMEncAttributes Attr = Encoder.Attributes;
            Attr.Add("URL", "IP address");

            // Start the encoding process.
            // Wait until the encoding process stops before exiting the application.
            Encoder.PrepareToEncode(true);
            Encoder.Start();
            Console.WriteLine("Press Enter when the file has been encoded.");
            Console.ReadLine();     // Press Enter after the file has been encoded.
        }
        catch (Exception e)
        {
            // TODO: Handle exceptions.
        }
    }
        private void button1_Click(object sender, EventArgs e)
        {
            try
            {
                Encoder = new WMEncoder();

                IWMEncSourceGroup SrcGrp;

                IWMEncSourceGroupCollection SrcGrpColl;

                SrcGrpColl = Encoder.SourceGroupCollection;

                SrcGrp = SrcGrpColl.Add("SG_1");

                IWMEncSource SrcVid = null;

                IWMEncSource SrcAud = null;

                SrcVid = SrcGrp.AddSource(WMENC_SOURCE_TYPE.WMENC_VIDEO);

                SrcAud = SrcGrp.AddSource(WMENC_SOURCE_TYPE.WMENC_AUDIO);

                SrcAud.SetInput("Default_Audio_Device", "Device", "");

                SrcVid.SetInput("ScreenCapture1", "ScreenCap", "");

                IWMEncProfileCollection ProColl;

                IWMEncProfile Pro;

                int i;

                long lLength;

                ProColl = Encoder.ProfileCollection;

                lLength = ProColl.Count;

                for (i = 0; i < lLength - 1; i++)
                {
                    Pro = ProColl.Item(i);

                    Console.WriteLine("<><>>" + Pro.Name);

                    if (Pro.Name == "屏幕视频/音频 - 高(CBR)")
                    {
                        SrcGrp.set_Profile(Pro);

                        break;
                    }
                }
                IWMEncDisplayInfo Descr;

                Descr = Encoder.DisplayInfo;

                Descr.Author = "";

                Descr.Copyright = "";

                Descr.Description = "";

                Descr.Rating = "";

                Descr.Title = "";

                IWMEncAttributes Attr;

                Attr = Encoder.Attributes;

                IWMEncFile File;

                File = Encoder.File;

                //if (label1.Text != string.Empty)
                //{
                //    File.LocalFileName = @"C:\1.WMA"; //保存路径
                //}
                //else
                //{
                //    MessageBox.Show("请先选择路径!");
                //    return;
                //}

                File.LocalFileName = @"C:\1.WMA"; //保存路径

                Encoder.Start();
            }
            catch (Exception ex)
            {
                Encoder.Stop();
            }
        }
Example #38
0
        public void InitializeEncoder()
        {
            try
            {
                frm_Rec=new WebMeeting.Client.Screen_Capture.frm_Rec();
                config=new Config();
                config.cfgFile = "WebMeeting.exe.config";

                // create encoder object
                m_encoder = new WMEncoder();
                m_encoder.DisplayInfo.Author="Zaeem";
                m_encoder.DisplayInfo.Copyright="Uraan Software Solutions";
                m_encoder.DisplayInfo.Description="Uraan Generated Media File for Screen Recording";
                m_encoder.DisplayInfo.Title="Recorded Screen";
                m_encoder.DisplayInfo.Title="Recorded Screen";
                m_encoder.DisplayInfo.Rating="1";
                m_encoder.DisplayInfo.Description="This file is Generated through CampusNav developed by Uraan Software Solution";

                // retrive source group collection
                m_sourceGroupCollection = m_encoder.SourceGroupCollection;

                // add a source group to collection
                m_srcGrp = m_sourceGroupCollection.Add("SG_1");

                m_sourceEnumDlg= new SourceEnum();

                // add a screen source
                if(EnumerateAudioSources())
                {
                    m_audSource = m_srcGrp.AddSource(WMENC_SOURCE_TYPE.WMENC_AUDIO);
                    m_audSource.SetInput(m_szAudioSource, "Device", "");
                }

                // set screen as source
                m_screenSource = (IWMEncVideoSource2)m_srcGrp.AddSource(WMENC_SOURCE_TYPE.WMENC_VIDEO);
                m_screenSource.SetInput("ScreenCapture1", "ScreenCap", "");

            }
            catch(Exception  exp)
            {

                WebMeeting.Client.ClientUI.getInstance().ShowExceptionMessage("Video Recordong Module ===>Screen Capture.cs line==> 99",exp,"Error Loading Encoder: " + exp.Message.ToString(),false);
                if( MessageBox.Show("Either You do not have required components of Windows Media Encoder or they are corrupted on your Machine: "+ /*+exp.Message.ToString() + */". Do you want to download now?","WebMeeting",MessageBoxButtons.YesNo,MessageBoxIcon.Information) == DialogResult.Yes)
                {
                    Win32.Shell32.ShellExecute(0,"Open",WebMeeting.Client.Info.getInstance().WebsiteName + "/wmencoder.exe","","",1);
                }

                //WebMeeting.Client.ClientUI.getInstance().ShowExceptionMessage("Error Stoping encoder: " + exp.Message.ToString());
                //Trace.WriteLine(exp.ToString()+"---"+exp.Message+"---"+exp.Source+exp.StackTrace+"---"+exp.TargetSite+"---"+exp.InnerException);

            }
        }
Example #39
0
        public bool EnumerateAudioSources()
        {
            try
            {
                WMEncoder Encoder = new WMEncoder();

                // Retrieve source and device plug-in info manager objects from WMEncoder.
                IWMEncSourcePluginInfoManager SrcPlugMgr = Encoder.SourcePluginInfoManager;
                IWMEncDeviceControlPluginInfoManager DCPlugMgr = Encoder.DeviceControlPluginInfoManager;

                // Loop through all the audio and video devices on the system.
                IWMEncPluginInfo PlugInfo;
                for (int i = 0; i < SrcPlugMgr.Count; i++)
                {
                    // Set the IWMEncPluginInfo object to the current plug-in.
                    PlugInfo = SrcPlugMgr.Item(i);

                    // Find the device plug-ins that support resources.
                    if (PlugInfo.SchemeType == "DEVICE" && PlugInfo.Resources == true)
                    {
                        // Loop through the resources in the current plug-in.
                        for (int j = 0; j<PlugInfo.Count; j++)
                        {

                            //if(frm_Rec.chkAudio.Checked==true)

                            {
                            // Add audio resources to the cboAudioSource combo box.
                            if (PlugInfo.MediaType == WMENC_SOURCE_TYPE.WMENC_AUDIO)
                                m_sourceEnumDlg.audioSources.Items.Add(PlugInfo.Item(j));

                            }
                        }
                    }
                }
            }
            catch(Exception exp)
            {
                WebMeeting.Client.ClientUI.getInstance().ShowExceptionMessage("Video Recordong Module ===>Screen Capture.cs line==> 147",exp,"Error Enumeration Audio Resources: " + exp.Message.ToString(),true);
                //WebMeeting.Client.ClientUI.getInstance().ShowExceptionMessage("Error Stoping encoder: " + exp.Message.ToString());
                //Trace.WriteLine(exp.ToString()+"---"+exp.Message+"---"+exp.Source+exp.StackTrace+"---"+exp.TargetSite+"---"+exp.InnerException);
            }

            //DialogResult ret = m_sourceEnumDlg.ShowDialog();
            //if( ret == DialogResult.Cancel)
            //	return false;

            //m_szAudioSource = m_sourceEnumDlg.selectedItem;

            m_szAudioSource = config.Read("Driver");

            return true;
        }