public VideoEncoder()
 {
     _mhandler=new MediaHandler();
     RootPath = HttpContext.Current.Server.MapPath(HttpContext.Current.Request.ApplicationPath);
     _mhandler.FFMPEGPath = HttpContext.Current.Server.MapPath("~\\MediaTools\\ffmpeg.exe");
    
 }
        private string CreatImg(HttpContext context, string _mediaName, string strname)
        {
            string ret = "";
            //   string filenameIMG = _mediaName;
            MediaHandler _mediahandler = new MediaHandler();

            string rootpath    = context.Server.MapPath(context.Request.ApplicationPath);
            string inputpath   = context.Server.MapPath("~/lib/up/v/");
            string outputpath  = context.Server.MapPath("~/lib/up/v/"); // +"\\up\\v";
            string _ffmpegpath = HttpContext.Current.Server.MapPath("~\\lib\\ffmpeg\\ffmpeg.dll");
            string filenameIMG = Guid.NewGuid().ToString().Substring(0, 10) + ".jpg";

            _mediahandler.FFMPEGPath   = _ffmpegpath;
            _mediahandler.InputPath    = inputpath;
            _mediahandler.OutputPath   = outputpath;
            _mediahandler.Width        = 180;
            _mediahandler.Height       = 130;
            _mediahandler.Frame_Time   = "3";
            _mediahandler.Image_Format = "jpg";
            _mediahandler.FileName     = _mediaName;
            _mediahandler.ImageName    = filenameIMG;
            VideoInfo info = _mediahandler.Grab_Thumb();


            if (info.ErrorCode > 0 && info.ErrorCode != 121)
            {
                return("");
            }
            ret = filenameIMG;
            return(filenameIMG);
        }
 public CopyStorageVideo(CosmosClient cosmosClient, StorageHandler storageHandler, MediaHandler mediaHandler)
 {
     _cosmosClient   = cosmosClient ?? throw new ArgumentNullException(nameof(cosmosClient));
     _storageHandler = storageHandler ?? throw new ArgumentNullException(nameof(storageHandler));
     _mediaHandler   = mediaHandler ?? throw new ArgumentNullException(nameof(mediaHandler));
     repoResource    = new ResourceRepository(_cosmosClient, "MigrationMedia");
 }
 /// <summary>
 /// Initiates the window with media that should be played
 /// </summary>
 /// <param name="playlistContent">Media to be played</param>
 /// <param name="secondsBetweenImages">Seconds between images in playing</param>
 public PlaylistPlayWindow(string titleOfPlaylist, List <MediaFile> playlistContent, int secondsBetweenImages)
 {
     InitializeComponent();
     Title = $"Playing playlist: {titleOfPlaylist}";
     playlistContentToPlay = playlistContent;
     playlistPlaybackDelayBetweenMediaSec = secondsBetweenImages;
     mediaHandler = new MediaHandler();
 }
        public int UploadMedia(IFormCollection data, IFormFile file)
        {
            System.Console.WriteLine(data["name"]);
            var m = new MediaHandler();

            m.UploadMediaFile(file, data["roomId"]);
            return(0);
        }
 public MigrationUpdaterMain(CosmosClient cosmosClient, StorageHandler storageHandler, MediaHandler mediaHandler, HttpHandler httpHandler)
 {
     _cosmosClient   = cosmosClient ?? throw new ArgumentNullException(nameof(cosmosClient));
     _storageHandler = storageHandler ?? throw new ArgumentNullException(nameof(storageHandler));
     _mediaHandler   = mediaHandler ?? throw new ArgumentNullException(nameof(mediaHandler));
     _httpHandler    = httpHandler ?? throw new ArgumentNullException(nameof(httpHandler));
     repoResource    = new ResourceRepository(_cosmosClient, "MigrationMedia");
 }
示例#7
0
        public void CreateVideoObjectTest_WithIncurrectInput_ExceptionThrown()
        {
            // Arrange
            MediaHandler mediaHandlerToTest = new MediaHandler();
            string       pathToVideoPreview = Path.Combine(Environment.CurrentDirectory, "Images\\video_icons8.png");

            // Act
            IMediaFile actualResult = mediaHandlerToTest.CreateVideoObject(null, pathToVideoPreview, null, "WIN_20200921_15_43_07_Pro.mp4");
        }
示例#8
0
        public MediaDetails(Media media)
        {
            InitializeComponent();

            this.Refresh();

            MediaToEdit = media;

            populateForm(media, MediaHandler.GetAllCategories(media.MediaType), MediaHandler.GetAllMediaTypes());
        }
    // Use this for initialization
    void Start()
    {
        //foreach(Transform child in glitches.transform) {
        //    child.gameObject.SetActive(false);
        //}

        //sliderHints = new GameObject[8];
        myMediaHandler = this.GetComponent <MediaHandler>();
        recordButtonHighlight.SetActive(false);

        NextState();
    }
示例#10
0
        public void IsMediaVideoTest_WithVideoObject_True()
        {
            // Arrange
            Video        testVideo          = new Video("WIN_20200921_15_43_07_Pro.mp4", "./VideoForTest/WIN_20200921_15_43_07_Pro.mp4", "./Images/video_icons8.png", "mp4", 5);
            MediaHandler mediaHandlerToTest = new MediaHandler();
            bool         expected           = true;

            // Act
            bool actualResult = mediaHandlerToTest.IsMediaVideo(testVideo);

            // Assert
            Assert.AreEqual(expected, actualResult);
        }
示例#11
0
        private const int AW_BLEND        = 0x80000; //使用淡入淡出效果

        private void FrmPopup_Load(object sender, EventArgs e)
        {
            try
            {
                MediaHandler.ASyncPlayWAV("msg.wav");
            }
            catch { }
            int x = Screen.PrimaryScreen.WorkingArea.Right - this.Width;
            int y = Screen.PrimaryScreen.WorkingArea.Bottom - this.Height;

            this.Location = new Point(x, y);//设置窗体在屏幕右下角显示
            AnimateWindow(this.Handle, 1000, AW_SLIDE | AW_ACTIVE | AW_VER_NEGATIVE);
        }
示例#12
0
        public void IsMediaVideoTest_WithImageObject_False()
        {
            // Arrange
            MultiMediaClassesAndManagers.MediaSubClasses.Image testVideo = new MultiMediaClassesAndManagers.MediaSubClasses.Image("TestImg", "C:\\Users\\obern\\OneDrive\\SkyDrive camera roll\\TestImg.jpg", "C:\\Users\\obern\\OneDrive\\SkyDrive camera roll\\TestImg.jpg", "jpg", 100, 400);
            MediaHandler mediaHandlerToTest = new MediaHandler();
            bool         expected           = false;

            // Act
            bool actualResult = mediaHandlerToTest.IsMediaVideo(testVideo);

            // Assert
            Assert.AreEqual(expected, actualResult);
        }
示例#13
0
    public void activateAttentionPanel()
    {
        // Debug.Log("toggle true or false = =?==" +Drive.GetComponent<Toggle>().isOn);
        if (ButtonGames.GetComponent <Button>().IsInteractable() == true)

        {
            TakeControlPanel.SetActive(true);
            MediaHandler.playThisAttention();
        }

        else if (ButtonGames.GetComponent <Button>().IsInteractable() == false)
        {
            GiveControlPanel.SetActive(true);
        }
    }
示例#14
0
        private void btnAutoUpdate_Click(object sender, EventArgs e)
        {
            Cursor = Cursors.WaitCursor;

            if (txtTitleResult.Text.Trim().Length > 0 || txtImdbNumResult.Text.Trim().Length > 0)
            {
                IMDBScraper imdb = new IMDBScraper();

                string textToSearch = txtTitleResult.Text.Replace("_", " ");

                Media foundMedia;

                if (txtImdbNumResult.Text.Trim().Length > 1)//search by imdb number
                {
                    foundMedia = imdb.getInfoByNumber(txtImdbNumResult.Text);
                }
                else//search by title
                {
                    foundMedia = imdb.getInfoByTitle(textToSearch, false);
                }

                if (foundMedia != null)
                {
                    populateForm(foundMedia, MediaHandler.GetAllCategories(foundMedia.MediaType), MediaHandler.GetAllMediaTypes());

                    //txtTitleResult.Text = foundMedia.Title;
                    //txtDirectorResult.Text = foundMedia.Director;
                    //txtGenreResult.Text = foundMedia.category;
                    //txtReleaseYearResult.Text = foundMedia.ReleaseYear;
                    //txtTaglineResult.Text = foundMedia.Description;
                    //txtImdbNumResult.Text = foundMedia.IMDBNum;
                    //txtRatingResult.Text = foundMedia.Rating;
                    //txtRatingReasonResult.Text = foundMedia.RatingDescription;

                    //thumbnailPictureBox.ImageLocation = foundMedia.coverImage;
                }
                else
                {
                    txtTitleResult.Text = "No Results";
                }
            }
            else
            {
                MessageBox.Show("You must enter something to search for");
            }

            Cursor = Cursors.Default;
        }
示例#15
0
        protected override void Initialize()
        {
            ContentLoader.onLoad(Content);
            base.Initialize();
            spriteBatch = new SpriteBatch(GraphicsDevice);

            MediaHandler.registerBGM(bgm);
            MediaHandler.registerSFX(sfx);
            StateHandler.initialize();

            IsMouseVisible        = false;
            graphics.IsFullScreen = true;
            graphics.SynchronizeWithVerticalRetrace = true;

            graphics.ApplyChanges();
        }
示例#16
0
        private void btnSave_Click(object sender, EventArgs e)
        {
            string selectedCategories = "";
            string selectedMediaTypes = "";

            mediaToEdit.Title    = txtTitleResult.Text;
            mediaToEdit.Director = txtDirectorResult.Text;

            foreach (string category in lbCurrentGenres.Items)
            {
                if (category.Trim().Length > 0)
                {
                    selectedCategories += category.Trim() + " | ";
                }
            }

            mediaToEdit.category          = selectedCategories;
            mediaToEdit.ReleaseYear       = txtReleaseYearResult.Text;
            mediaToEdit.Description       = txtTaglineResult.Text;
            mediaToEdit.IMDBNum           = txtImdbNumResult.Text;
            mediaToEdit.Rating            = txtRatingReasonResult.Text;
            mediaToEdit.RatingDescription = txtRatingReasonResult.Text;

            foreach (string category in lbSelectedCategories.Items)
            {
                if (category.Trim().Length > 0)
                {
                    selectedMediaTypes += category.Trim() + " | ";
                }
            }

            mediaToEdit.MediaType = selectedMediaTypes;

            mediaToEdit.Goofs      = txtGoofs.Text;
            mediaToEdit.Trivia     = txtTrivia.Text;
            mediaToEdit.coverImage = txtCoverImage.Text;

            //update media file
            MediaHandler.UpdateMediaInfo(mediaToEdit);

            //update in memory dataset
            //MediaHandler.GetMedia();

            this.DialogResult = DialogResult.OK;

            this.Close();
        }
示例#17
0
        /// <inheritdoc />
        public IEnumerable <uSyncAction> Import()
        {
            mediaHandler = new MediaHandler(
                _logger,
                _entityService,
                _mediaService,
                _appCaches,
                _shortStringHelper,
                _uSyncFileService,
                _uSyncEventService,
                _uSyncConfigService,
                _syncItemFactory);

            var importResults = mediaHandler.ImportAll(uSyncDirectoryPaths.Media, new HandlerSettings(), default);

            return(importResults);
        }
示例#18
0
        public void CreateVideoObjectTest_WithCurrectVideoData_CurrectObjectReturned()
        {
            // Arrange
            MediaHandler       mediaHandlerToTest = new MediaHandler();
            WindowsMediaPlayer wmp                = new WindowsMediaPlayer();
            string             pathToVideo        = Path.Combine(Environment.CurrentDirectory, "VideoForTest\\WIN_20200921_15_43_07_Pro.mp4");
            string             pathToVideoPreview = Path.Combine(Environment.CurrentDirectory, "Images\\video_icons8.png");

            Video expected = new Video("WIN_20200921_15_43_07_Pro.mp4", pathToVideo, pathToVideoPreview, "mp4", 14);
            // Act
            Video actualResult = (Video)mediaHandlerToTest.CreateVideoObject(pathToVideo, pathToVideoPreview, wmp.newMedia(pathToVideo), "WIN_20200921_15_43_07_Pro.mp4");

            // Assert
            Assert.AreEqual(expected.Id, actualResult.Id);
            Assert.AreEqual(expected.Name, actualResult.Name);
            Assert.AreEqual(expected.LengthInSeconds, actualResult.LengthInSeconds);
            Assert.AreEqual(expected.PreviewUrl, actualResult.PreviewUrl);
            Assert.AreEqual(expected.SourceUrl, actualResult.SourceUrl);
            Assert.AreEqual(expected.SortInPlaylist, actualResult.SortInPlaylist);
        }
示例#19
0
    public void activateButtons()
    {
        if (ButtonGames.GetComponent <Button>().IsInteractable() == true)
        {
            Debug.Log("ist true button");

            ButtonGames.GetComponent <Button>().interactable        = false;
            ButtonMovies.GetComponent <Button>().interactable       = false;
            ButtonDownThePanel.GetComponent <Button>().interactable = false;

            MediaHandler.playThisAttention();

            checkIfScrollPanelAktive();
        }
        else //Else make it interactable
        {
            ButtonGames.GetComponent <Button>().interactable        = true;
            ButtonMovies.GetComponent <Button>().interactable       = true;
            ButtonDownThePanel.GetComponent <Button>().interactable = true;

            GiveControlPanel.SetActive(true);
        }
    }
示例#20
0
        private static MediaHandler ConfigMediaHandler()
        {
            try
            {
                MediaHandler _mhandler = new MediaHandler();
                if (!MediaConfigPath.CheckBasicIsFills())
                {
                    throw new Exception("Required Executable Files Not Found. Please Check MediaConfigPath Class.");
                }
                _mhandler.FFMPEGPath    = MediaConfigPath.PathFFMPEG;
                _mhandler.InputPath     = MediaConfigPath.PathInputs;
                _mhandler.OutputPath    = MediaConfigPath.PathOutputs;
                _mhandler.WaterMarkPath = MediaConfigPath.PathWatermarks;
                _mhandler.FLVToolPath   = MediaConfigPath.PathFLVTOOL;
                _mhandler.MP4BoxPath    = MediaConfigPath.PathMP4Box;

                return(_mhandler);
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }
示例#21
0
        private void GenerateThumbNails(DataObjectVideo video, string format, VideoVersion videoVersion)
        {
            FileInfo  sourceVideoFileInfo = new FileInfo(video.OriginalLocation);
            VideoInfo encodedVideoInfo    = new VideoInfo();

            MediaHandler mediaHandler = new MediaHandler();

            mediaHandler.FFMPEGPath = ffmpegExecutable;
            mediaHandler.InputPath  = sourceVideoFileInfo.DirectoryName;
            mediaHandler.OutputPath = temporaryConversionFolder;
            mediaHandler.FileName   = sourceVideoFileInfo.Name;


            mediaHandler.OutputFileName = string.Format("{2}{0}.{1}", video.ObjectID, format, videoVersion);
            VideoInfo sourceVideoInfo = mediaHandler.Get_Info();

            MediaHandler thumbnailMediaHandler = new MediaHandler();

            thumbnailMediaHandler.FFMPEGPath   = ffmpegExecutable;
            thumbnailMediaHandler.InputPath    = temporaryConversionFolder;
            thumbnailMediaHandler.OutputPath   = temporaryConversionFolder;
            thumbnailMediaHandler.FileName     = string.Format("{2}{0}.{1}", video.ObjectID, format, videoVersion);
            thumbnailMediaHandler.Image_Format = "jpg";

            // The exit process timeout probably doesn't work
            if (maxThumbnailGenerationTime.HasValue)
            {
                thumbnailMediaHandler.ExitProcess = maxThumbnailGenerationTime.Value;
            }

            if (generateMultipleThumbnails) // TODO: Check how many files have been written
            {
                thumbnailMediaHandler.Multiple_Thumbs      = true;
                thumbnailMediaHandler.ImageName            = video.ObjectID + "_";
                thumbnailMediaHandler.Auto_Transition_Time = true;
                thumbnailMediaHandler.No_Of_Thumbs         = numberThumbnails.Value;
                thumbnailMediaHandler.Thumb_Start_Position = (int)(sourceVideoInfo.Duration_Sec / numberThumbnails);
            }
            else
            {
                thumbnailMediaHandler.ImageName = video.ObjectID.ToString();
                TimeSpan frameTime;
                if (video.VideoPreviewPictureTimepointSec > 0 && video.VideoPreviewPictureTimepointSec < sourceVideoInfo.Duration_Sec)
                {
                    frameTime = new TimeSpan(0, 0, (int)(video.VideoPreviewPictureTimepointSec));
                }
                else
                {
                    frameTime = new TimeSpan(0, 0, (int)(sourceVideoInfo.Duration_Sec * 0.3));
                }
                thumbnailMediaHandler.Frame_Time = frameTime.ToString();
            }

            VideoInfo thumbnailInfo = thumbnailMediaHandler.Grab_Thumb();

            if (thumbnailInfo.ErrorCode == 0)
            {
                string videoThumbnail = string.Format(@"{0}\{1}.jpg", temporaryConversionFolder, video.ObjectID);
                _4screen.CSB.ImageHandler.Business.ImageHandler imgHandler = new _4screen.CSB.ImageHandler.Business.ImageHandler(ConfigurationManager.AppSettings["MediaDomainName"], ConfigurationManager.AppSettings["ConverterRootPath"], video.UserID.ToString(), video.ObjectID.ToString(), true, Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location) + "\\configurations");

                Size largePreview = new Size();
                try
                {
                    imgHandler.DoConvert(videoThumbnail, "ExtraSmallJpg", _4screen.CSB.ImageHandler.Business.ImageHandler.ReturnPath.Url);
                    imgHandler.DoConvert(videoThumbnail, "SmallJpg", _4screen.CSB.ImageHandler.Business.ImageHandler.ReturnPath.Url);
                    imgHandler.DoConvert(videoThumbnail, "MediumJpg", _4screen.CSB.ImageHandler.Business.ImageHandler.ReturnPath.Url);
                    imgHandler.DoConvert(videoThumbnail, "LargeJpg", _4screen.CSB.ImageHandler.Business.ImageHandler.ReturnPath.Url);
                    largePreview.Width  = imgHandler.ImageInfo.Width;
                    largePreview.Height = imgHandler.ImageInfo.Height;
                }
                catch (Exception e)
                {
                    EventLog.WriteEntry("CSBooster Video Encoding Error - generate Thumnails: " + e.Message + " " + e.StackTrace, System.Diagnostics.EventLogEntryType.Warning);
                }

                string encodedVideoFile = string.Format(@"{0}\{3}{1}.{2}", temporaryConversionFolder, video.ObjectID, format, videoVersion);

                if (archiveUpload)
                {
                    UploadToArchiveFolder(sourceVideoFileInfo.FullName, video.ObjectID.Value, video.UserID.Value);
                }

                UpdateDataObject(video, sourceVideoInfo, largePreview, format, videoVersion);

                DeleteFile(videoThumbnail);
                DeleteFile(encodedVideoFile);
                if (watermarkFileInfo != null)
                {
                    DeleteFile(watermarkFileInfo.FullName);
                }
            }
            else
            {
                throw new Exception("Video thumbnail generation failed: Error code " + thumbnailInfo.ErrorCode + " " + thumbnailInfo.ErrorMessage);
            }
        }
示例#22
0
        private int EncodeVideo(DataObjectVideo video, string format, VideoVersion videoVersion, Dictionary <string, string> defaultSettings, Dictionary <string, string> actionSettings, bool deleteEncodedVideo)
        {
            //Console.WriteLine("Encoding '" + video.Title + "' -> " + video.OriginalLocation);

            FileInfo  sourceVideoFileInfo = new FileInfo(video.OriginalLocation);
            VideoInfo encodedVideoInfo    = new VideoInfo();

            MediaHandler mediaHandler = new MediaHandler();

            mediaHandler.FFMPEGPath     = ffmpegExecutable;
            mediaHandler.InputPath      = sourceVideoFileInfo.DirectoryName;
            mediaHandler.OutputPath     = temporaryConversionFolder;
            mediaHandler.FileName       = sourceVideoFileInfo.Name;
            mediaHandler.OutputFileName = string.Format("{2}{0}.{1}", video.ObjectID, format, videoVersion);

            VideoInfo sourceVideoInfo = mediaHandler.Get_Info();

            if (!video.OriginalLocation.ToLower().EndsWith(string.Format(".{0}", format)))
            {
                try
                {
                    if (actionSettings.ContainsKey("VideoWidth"))
                    {
                        //An empty VideoWidth overides the default setting width
                        if (!string.IsNullOrEmpty(actionSettings["VideoWidth"]))
                        {
                            mediaHandler.Width = Convert.ToInt32(actionSettings["VideoWidth"]);
                            if (actionSettings.ContainsKey("VideoHeight") && !string.IsNullOrEmpty(actionSettings["VideoHeight"]) && actionSettings["VideoHeight"] != "auto")
                            {
                                mediaHandler.Height = Convert.ToInt32(actionSettings["VideoHeight"]);
                            }
                            else
                            {
                                int calculatedHeight = (int)(mediaHandler.Width * (double)sourceVideoInfo.Height / (double)sourceVideoInfo.Width);
                                if (calculatedHeight % 2 != 0)
                                {
                                    calculatedHeight += 1;
                                }
                                mediaHandler.Height = calculatedHeight;
                            }
                        }
                    }
                    else if (defaultSettings.ContainsKey("VideoWidth") && !string.IsNullOrEmpty(defaultSettings["VideoWidth"]))
                    {
                        mediaHandler.Width = Convert.ToInt32(defaultSettings["VideoWidth"]);
                        if (defaultSettings.ContainsKey("VideoHeight") && !string.IsNullOrEmpty(defaultSettings["VideoHeight"]) && defaultSettings["VideoHeight"] != "auto")
                        {
                            mediaHandler.Height = Convert.ToInt32(defaultSettings["VideoHeight"]);
                        }
                        else
                        {
                            int calculatedHeight = (int)(mediaHandler.Width * (double)sourceVideoInfo.Height / (double)sourceVideoInfo.Width);
                            if (calculatedHeight % 2 != 0)
                            {
                                calculatedHeight += 1;
                            }
                            mediaHandler.Height = calculatedHeight;
                        }
                    }
                }
                catch
                {
                }
                try
                {
                    if (actionSettings.ContainsKey("VideoFrameRate"))
                    {
                        if (!string.IsNullOrEmpty(actionSettings["VideoFrameRate"]) && actionSettings["VideoFrameRate"] != "auto")
                        {
                            mediaHandler.FrameRate = Convert.ToDouble(actionSettings["VideoFrameRate"]);
                        }
                    }
                    else if (defaultSettings.ContainsKey("VideoFrameRate") && !string.IsNullOrEmpty(defaultSettings["VideoFrameRate"]) && defaultSettings["VideoFrameRate"] != "auto")
                    {
                        mediaHandler.FrameRate = Convert.ToInt32(defaultSettings["VideoFrameRate"]);
                    }
                }
                catch
                {
                }
                try
                {
                    if (actionSettings.ContainsKey("StartPosition"))
                    {
                        if (!string.IsNullOrEmpty(actionSettings["StartPosition"]))
                        {
                            mediaHandler.Start_Position = actionSettings["StartPosition"];
                        }
                    }
                    else if (defaultSettings.ContainsKey("StartPosition") && !string.IsNullOrEmpty(defaultSettings["StartPosition"]))
                    {
                        mediaHandler.Start_Position = defaultSettings["StartPosition"];
                    }
                }
                catch
                {
                }
                try
                {
                    if (actionSettings.ContainsKey("Duration"))
                    {
                        if (!string.IsNullOrEmpty(actionSettings["Duration"]))
                        {
                            mediaHandler.Duration = actionSettings["Duration"];
                        }
                    }
                    else if (defaultSettings.ContainsKey("Duration") && !string.IsNullOrEmpty(defaultSettings["Duration"]))
                    {
                        mediaHandler.Duration = defaultSettings["Duration"];
                    }
                }
                catch
                {
                }
                try
                {
                    double sourceVideoBitrate;
                    double.TryParse(sourceVideoInfo.Video_Bitrate.Replace(" kb/s", ""), out sourceVideoBitrate);
                    mediaHandler.Video_Bitrate = sourceVideoBitrate;
                    if (actionSettings.ContainsKey("VideoBitrate"))
                    {
                        if (!string.IsNullOrEmpty(actionSettings["VideoBitrate"]) && actionSettings["VideoBitrate"] != "auto")
                        {
                            if (sourceVideoBitrate > Convert.ToDouble(actionSettings["VideoBitrate"]) || sourceVideoBitrate == 0)
                            {
                                mediaHandler.Video_Bitrate = Convert.ToDouble(actionSettings["VideoBitrate"]);
                            }
                        }
                    }
                    else if (defaultSettings.ContainsKey("VideoBitrate") && !string.IsNullOrEmpty(defaultSettings["VideoBitrate"]) && defaultSettings["VideoBitrate"] != "auto")
                    {
                        if (sourceVideoBitrate > Convert.ToDouble(defaultSettings["VideoBitrate"]) || sourceVideoBitrate == 0)
                        {
                            mediaHandler.Video_Bitrate = Convert.ToInt32(defaultSettings["VideoBitrate"]);
                        }
                    }
                }
                catch
                {
                }
                try
                {
                    double sourceAudioBitrate;
                    double.TryParse(sourceVideoInfo.Audio_Bitrate.Replace(" kb/s", ""), out sourceAudioBitrate);
                    mediaHandler.Audio_Bitrate = sourceAudioBitrate;
                    if (actionSettings.ContainsKey("AudioBitrate"))
                    {
                        if (!string.IsNullOrEmpty(actionSettings["AudioBitrate"]) && actionSettings["AudioBitrate"] != "auto")
                        {
                            if (sourceAudioBitrate > Convert.ToDouble(actionSettings["AudioBitrate"]) || sourceAudioBitrate == 0)
                            {
                                mediaHandler.Audio_Bitrate = Convert.ToDouble(actionSettings["AudioBitrate"]);
                            }
                        }
                    }
                    else if (defaultSettings.ContainsKey("AudioBitrate") && !string.IsNullOrEmpty(defaultSettings["AudioBitrate"]) && defaultSettings["AudioBitrate"] != "auto")
                    {
                        if (sourceAudioBitrate > Convert.ToDouble(defaultSettings["VideoBitrate"]) || sourceAudioBitrate == 0)
                        {
                            mediaHandler.Audio_Bitrate = Convert.ToInt32(defaultSettings["AudioBitrate"]);
                        }
                    }
                }
                catch
                {
                }
                try
                {
                    int sourceAudioSamplingRate;
                    int.TryParse(sourceVideoInfo.SamplingRate.Replace(" kb/s", ""), out sourceAudioSamplingRate);
                    mediaHandler.Audio_SamplingRate = sourceAudioSamplingRate == 32000 ? 44100 : sourceAudioSamplingRate;
                    if (actionSettings.ContainsKey("AudioSamplingRate"))
                    {
                        if (!string.IsNullOrEmpty(actionSettings["AudioSamplingRate"]) && actionSettings["AudioSamplingRate"] != "auto")
                        {
                            if (sourceAudioSamplingRate > Convert.ToDouble(actionSettings["AudioSamplingRate"]) || sourceAudioSamplingRate == 0)
                            {
                                mediaHandler.Audio_SamplingRate = Convert.ToInt32(actionSettings["AudioSamplingRate"]);
                            }
                        }
                    }
                    else if (defaultSettings.ContainsKey("AudioSamplingRate") && !string.IsNullOrEmpty(defaultSettings["AudioSamplingRate"]) && defaultSettings["AudioSamplingRate"] != "auto")
                    {
                        if (sourceAudioSamplingRate > Convert.ToDouble(defaultSettings["VideoBitrate"]) || sourceAudioSamplingRate == 0)
                        {
                            mediaHandler.Audio_SamplingRate = Convert.ToInt32(defaultSettings["AudioSamplingRate"]);
                        }
                    }
                }
                catch
                {
                }

                // Force mono or stereo, no 5:1 supported
                mediaHandler.Channel = sourceVideoInfo.Channel.Contains("mono") ? 1 : 2;

                mediaHandler.ExitProcess = 100000;
                try
                {
                    if (actionSettings.ContainsKey("MaxDecodingTime"))
                    {
                        if (!string.IsNullOrEmpty(actionSettings["MaxDecodingTime"]))
                        {
                            mediaHandler.ExitProcess = Convert.ToInt32(actionSettings["MaxDecodingTime"]);
                        }
                    }
                    else if (defaultSettings.ContainsKey("MaxDecodingTime"))
                    {
                        mediaHandler.ExitProcess = Convert.ToInt32(defaultSettings["MaxDecodingTime"]);
                    }
                }
                catch
                {
                }
                try
                {
                    bool embeddedWatermark = false;
                    if (actionSettings.ContainsKey("EmbeddedWatermark"))
                    {
                        embeddedWatermark = bool.Parse(actionSettings["EmbeddedWatermark"]);
                    }
                    else if (defaultSettings.ContainsKey("EmbeddedWatermark"))
                    {
                        embeddedWatermark = bool.Parse(defaultSettings["EmbeddedWatermark"]);
                    }

                    if (embeddedWatermark)
                    {
                        string watermarkImage = string.Empty;
                        if (actionSettings.ContainsKey("WatermarkImage"))
                        {
                            watermarkImage = actionSettings["WatermarkImage"];
                        }
                        else if (defaultSettings.ContainsKey("WatermarkImage"))
                        {
                            watermarkImage = defaultSettings["WatermarkImage"];
                        }

                        watermarkFileInfo = CreateWatermarkFrame(video, sourceVideoInfo, mediaHandler, watermarkImage);
                        if (watermarkFileInfo != null)
                        {
                            mediaHandler.WaterMarkPath  = watermarkFileInfo.DirectoryName;
                            mediaHandler.WaterMarkImage = watermarkFileInfo.Name;
                        }
                    }
                }
                catch
                {
                }
                switch (format)
                {
                case "wmv":
                    encodedVideoInfo = mediaHandler.Encode_WMV();
                    break;

                case "mpg":
                    encodedVideoInfo = mediaHandler.Encode_MPG();
                    break;

                case "mp4":
                    encodedVideoInfo = mediaHandler.Encode_MP4();
                    break;

                case "mov":
                    encodedVideoInfo = mediaHandler.Encode_MOV();
                    break;

                case "m4v":
                    encodedVideoInfo = mediaHandler.Encode_M4V();
                    break;

                case "flv":
                    encodedVideoInfo = mediaHandler.Encode_FLV();
                    break;

                case "avi":
                    encodedVideoInfo = mediaHandler.Encode_AVI();
                    break;

                case "3gp":
                    encodedVideoInfo = mediaHandler.Encode_3GP();
                    break;
                }

                if (encodedVideoInfo.ErrorCode == 0)
                {
                    FileInfo encodedVideoFileInfo = new FileInfo(string.Format(@"{0}\{3}{1}.{2}", temporaryConversionFolder, video.ObjectID, format, videoVersion));
                    if (encodedVideoFileInfo.Length == 0)
                    {
                        throw new Exception("Video processing failed: Filesize 0 bytes");
                    }
                }
            }
            else // Already a video in the given format
            {
                File.Copy(video.OriginalLocation, string.Format(@"{0}\{3}{1}.{2}", temporaryConversionFolder, video.ObjectID, format, videoVersion));
            }
            //Move generated Video

            string encodedVideoFile = string.Format(@"{0}\{3}{1}.{2}", temporaryConversionFolder, video.ObjectID, format, videoVersion);

            if (useAmazoneS3)
            {
                UploadToAmazonS3(encodedVideoFile, video.ObjectID.Value, video.UserID.Value, format, videoVersion);
            }
            else
            {
                UploadToMediaFolder(encodedVideoFile, video.ObjectID.Value, video.UserID.Value, format, videoVersion);
            }
            if (deleteEncodedVideo)
            {
                DeleteFile(string.Format(@"{0}\{3}{1}.{2}", temporaryConversionFolder, video.ObjectID, format, videoVersion));
            }
            return(encodedVideoInfo.ErrorCode);
        }
示例#23
0
        protected override void Draw(GameTime gameTime)
        {
            if (height != Window.ClientBounds.Height)
            {
                height       = Window.ClientBounds.Height;
                Globals.hmod = height / 768f;
            }
            if (width != Window.ClientBounds.Width)
            {
                width        = Window.ClientBounds.Width;
                Globals.wmod = width / 1024f;
            }

            GraphicsDevice.Clear(Color.Transparent);
            SpriteBatch sBatch = new SpriteBatch(GraphicsDevice);
            SpriteFont  font;

            font = Content.Load <SpriteFont>("Old London");

            sBatch.Begin();
            Texture2D background = Content.Load <Texture2D>(MediaHandler.getBackground());

            sBatch.Draw(background, Window.ClientBounds, Color.White);
            sBatch.End();

            GraphicsDevice.DepthStencilState = DepthStencilState.Default;

            GraphicsDevice.BlendState       = BlendState.Opaque;
            GraphicsDevice.RasterizerState  = RasterizerState.CullCounterClockwise;
            GraphicsDevice.SamplerStates[0] = SamplerState.LinearWrap;

            if (StateHandler.GetSceneList() != null)
            {
                foreach (Actor actor in StateHandler.GetSceneList())
                {
                    if (actor != null)
                    {
                        actor.draw(gameTime.ElapsedGameTime);
                    }
                }
            }

            sBatch.Begin();
            MessageBoxInterface[] messageboxes = StateHandler.GetMessageBoxes();
            if (messageboxes != null)
            {
                foreach (MessageBoxInterface message in messageboxes)
                {
                    if (message == null)
                    {
                        continue;
                    }

                    Texture2D messageBoxBackground;
                    if (message.IsChildMessage())
                    {
                        messageBoxBackground = Content.Load <Texture2D>("messagebox2.jpg");
                    }
                    else
                    {
                        messageBoxBackground = Content.Load <Texture2D>("messagebox.png");
                    }

                    if (!message.Scaling())
                    {
                        sBatch.Draw(messageBoxBackground, new Rectangle((int)(message.X() * Globals.wmod), (int)(message.Y() * Globals.hmod), message.Width(), message.Height()), Color.Blue);
                    }
                    else
                    {
                        sBatch.Draw(messageBoxBackground, new Rectangle((int)(message.X() * Globals.wmod), (int)(message.Y() * Globals.hmod), (int)(message.Width() * Globals.wmod), (int)(message.Height() * Globals.hmod)), Color.Blue);
                    }
                    for (int i = 0; i < message.stringToDisplay().Length; i++)
                    {
                        sBatch.DrawString(font, message.stringToDisplay()[i], new Vector2((float)(message.X() * Globals.wmod) + 10, (float)(message.Y() * Globals.hmod) + 10 + (i * Globals.FONT_HEIGHT)), message.Color()[i]);
                    }
                }
            }

            if (StateHandler.Paused)
            {
                sBatch.DrawString(font, "P A U S E D", new Vector2(Window.ClientBounds.Width / 2 - 65, Window.ClientBounds.Height / 2), Color.NavajoWhite);
            }

            //  sBatch.DrawString(font, "X : " + StateHandler.X + " Y: " + StateHandler.Y + " Z: " + StateHandler.Z + " TX: " + StateHandler.TargetX + " TY: " + StateHandler.TargetY + " TZ: " + StateHandler.TargetZ, new Vector2(100, 100), Color.NavajoWhite);

            sBatch.End();

            base.Draw(gameTime);
        }
示例#24
0
        private string CreatImg(HttpContext context, string _mediaName, string strname)
        {
            string ret = "";
            //   string filenameIMG = _mediaName;
            MediaHandler _mediahandler = new MediaHandler();

            string rootpath = context.Server.MapPath(context.Request.ApplicationPath);
            string inputpath = context.Server.MapPath("~/lib/up/v/");
            string outputpath = context.Server.MapPath("~/lib/up/v/"); // +"\\up\\v";
            string _ffmpegpath = HttpContext.Current.Server.MapPath("~\\lib\\ffmpeg\\ffmpeg.dll");
            string filenameIMG = Guid.NewGuid().ToString().Substring(0, 10) + ".jpg";

            _mediahandler.FFMPEGPath = _ffmpegpath;
            _mediahandler.InputPath = inputpath;
            _mediahandler.OutputPath = outputpath;
            _mediahandler.Width = 180;
            _mediahandler.Height = 130;
            _mediahandler.Frame_Time = "3";
            _mediahandler.Image_Format = "jpg";
            _mediahandler.FileName = _mediaName;
            _mediahandler.ImageName = filenameIMG;
            VideoInfo info = _mediahandler.Grab_Thumb();

            if (info.ErrorCode > 0 && info.ErrorCode != 121)
            {
                return "";
            }
            ret = filenameIMG;
            return filenameIMG;
        }
示例#25
0
    private string convWMV(string _mediaName)
    {
        string ret = "";
        // Sample code for encoding any format video to wmv format.
        MediaHandler _mhandler = new MediaHandler();

        // required properties

        string rootpath = Server.MapPath(Request.ApplicationPath);
        string inputpath = Server.MapPath("~/lib/up/v/");
        string outputpath = Server.MapPath("~/lib/up/v/");
        string _ffmpegpath = HttpContext.Current.Server.MapPath("~\\ffmpeg\\ffmpeg.dll");

        string filenameWMV = Guid.NewGuid().ToString().Substring(0, 10) + ".wmv";
        _mhandler.FFMPEGPath = _ffmpegpath;
        _mhandler.InputPath = inputpath;
        _mhandler.OutputPath = outputpath;
        _mhandler.FileName = _mediaName;

        // optional output filename

        _mhandler.OutputFileName = filenameWMV;

        // setting video related properties

        //_mhandler.Video_Bitrate = 786;
        //_mhandler.Audio_Bitrate = 64;
        //_mhandler.Audio_SamplingRate = 44100;

        // generate highest quality mp4 video, note by making this option true, video bitrate will no longer work.

        _mhandler.MaxQuality = true;

        // optional video width and height settings

        _mhandler.Width = 538;
        _mhandler.Height = 400;

        // Optional parameters for setting audio and video codec for wmv video
        _mhandler.VCodec = "wmv2";
        _mhandler.ACodec = "wmav2";
        _mhandler.Audio_Bitrate = 64;
        _mhandler.Video_Bitrate = 1000;

        // posting watermark on wmv video, view detail in watermark section
        //  _mhandler.WaterMarkPath = RootPath + "\\contents\\watermark";
        //  _mhandler.WaterMarkImage = "watermark.gif";

        // view more options in component documentation.

        // Encode WMV Video using Media Handler Pro version 3.0

        //  string output = _mhandler.Encode_WMV();

        // Encode WMV Video using Media Handler Pro version 4.0 or later

        VideoInfo info = _mhandler.Encode_WMV();

        // Check for errors
        if (info.ErrorCode > 0)
        {
            Response.Write("Video processing failed, Error code " + info.ErrorCode + " generated");
            return "";
        }
        ret = filenameWMV;
        return filenameWMV;
    }
示例#26
0
 public VideoUtilities()
 {
     _mhandler = ConfigMediaHandler();
 }
示例#27
0
        private FileInfo CreateWatermarkFrame(DataObjectVideo video, VideoInfo videoInfo, MediaHandler mediaHandler, string watermarkImage)
        {
            try
            {
                Bitmap   watermark           = new Bitmap(watermarkImage);
                int      watermarkFullWidth  = mediaHandler.Width != 0 ? mediaHandler.Width : videoInfo.Width;
                int      watermarkFullHeight = mediaHandler.Height != 0 ? mediaHandler.Height : videoInfo.Height;
                Bitmap   watermarkFullframe  = new Bitmap(watermarkFullWidth, watermarkFullHeight);
                Graphics g = Graphics.FromImage(watermarkFullframe);
                g.FillRectangle(new SolidBrush(Color.FromArgb(128, 128, 128)), 0, 0, watermarkFullWidth, watermarkFullHeight);

                // Check if the watermark is larger than the video
                if (watermark.Width > watermarkFullWidth && watermark.Height > watermarkFullHeight)
                {
                    g.DrawImage(watermark, 0, 0, watermarkFullWidth, watermarkFullHeight);
                }
                else if (watermark.Width > watermarkFullWidth)
                {
                    g.DrawImage(watermark, 0, watermarkFullHeight - watermark.Height, watermarkFullWidth, watermark.Height);
                }
                else if (watermark.Height > watermarkFullHeight)
                {
                    g.DrawImage(watermark, watermarkFullWidth - watermark.Width, 0, watermark.Width, watermarkFullHeight);
                }
                else
                {
                    g.DrawImage(watermark, watermarkFullWidth - watermark.Width, watermarkFullHeight - watermark.Height, watermark.Width, watermark.Height);
                }
                g.Dispose();

                string watermarkFrame = string.Format(@"{0}\watermark_{1}.png", temporaryConversionFolder, video.ObjectID);
                watermarkFullframe.Save(watermarkFrame, System.Drawing.Imaging.ImageFormat.Png);

                return(new FileInfo(watermarkFrame));
            }
            catch
            {
                return(null);
            }
        }
示例#28
0
 public VideoEncoder()
 {
     _mhandler            = new MediaHandler();
     RootPath             = HttpContext.Current.Server.MapPath(HttpContext.Current.Request.ApplicationPath);
     _mhandler.FFMPEGPath = HttpContext.Current.Server.MapPath("~\\MediaTools\\ffmpeg.exe");
 }
示例#29
0
        /// <summary>
        /// Retrieve fields from IMDB, run this sub before using the properites
        /// </summary>
        /// <remarks></remarks>
        public Media getInfo(Media media, bool bestMatch)
        {
            Media mediaResult = media;

            try
            {
                string    matchContent  = "";
                ArrayList searchResults = new ArrayList();

                //scrape the movie title
                _MovieTitle = getTitle(_FileContent);

                if (_MovieTitle == "IMDb Search" || _MovieTitle == "Find - IMDb")//there were multiple results
                {
                    if (bestMatch)
                    {
                        ArrayList matches = getMultipleMatchTitles(_FileContent);

                        if (matches.Count > 0)
                        {
                            string searchTitle = MediaHandler.FormatNameString(media.Title).ToLower();
                            searchTitle = searchTitle.Replace(" ", "");

                            foreach (Media foundMedia in matches)
                            {
                                //try to match the title with search string
                                string tempTitle = MediaHandler.FormatNameString(foundMedia.Title).ToLower();
                                tempTitle = tempTitle.Replace(" ", "");

                                //look for the entire title
                                if (tempTitle.Contains(searchTitle))
                                {
                                    mediaResult = foundMedia;
                                    break;
                                }
                            }

                            //didn't find match - look for half the title
                            if (mediaResult == null)
                            {
                                foreach (Media foundMedia in matches)
                                {
                                    string tempTitle = MediaHandler.FormatNameString(foundMedia.Title).ToLower();
                                    tempTitle = tempTitle.Replace(" ", "");

                                    if (tempTitle.Contains(searchTitle.Substring(0, searchTitle.Length / 2)))
                                    {
                                        mediaResult = foundMedia;
                                        break;
                                    }
                                }
                            }

                            //pick the first one since we didn't find a match
                            if (mediaResult == null)
                            {
                                mediaResult = (Media)matches[0];
                            }

                            mediaResult = getInfoByNumber(mediaResult);
                        }
                    }
                    else
                    {
                        searchResults = getMultipleMatchTitles(_FileContent);

                        //display results
                        MultipleMatches multipleMatches = new MultipleMatches(searchResults);
                        DialogResult    result          = multipleMatches.ShowDialog();
                        multipleMatches.BringToFront();

                        if (result == DialogResult.OK)
                        {
                            mediaResult = multipleMatches.MediaResult;
                        }
                    }

                    ////get exact matches
                    //string exactMatchPattern = @"Titles\ \(Exact\ Matches\).*?</p>";
                    ////string exactMatchPattern = @"title_exact.*?</td>";
                    //Regex R1 = new Regex(exactMatchPattern,
                    //    RegexOptions.IgnoreCase | RegexOptions.IgnorePatternWhitespace);

                    ////get popular titles
                    //string popularMatchPattern = @"Popular\ Titles.*?</p>";
                    //Regex R2 = new Regex(popularMatchPattern,
                    //    RegexOptions.IgnoreCase | RegexOptions.IgnorePatternWhitespace);

                    ////if(R2.Matches(_FileContent).Count > 0)
                    ////    matchContent = R2.Matches(_FileContent)[0].Value;

                    //if (R2.Matches(_FileContent).Count > 0)
                    //    searchResults.AddRange(getMultipleMatchTitles(R2.Matches(_FileContent)[0].Value,0));

                    ////if (R1.Matches(_FileContent).Count > 0)
                    ////    matchContent += R1.Matches(_FileContent)[0].Value;

                    //for (int x = 0; x < R1.Matches(_FileContent).Count; x++)
                    //    searchResults.AddRange(getMultipleMatchTitles(R1.Matches(_FileContent)[x].Value, x));



                    //if (matchContent.Trim().Length > 0)
                    //{
                    //    //display matches
                    //    mediaResult = displayMultipleMatches(matchContent, bestMatch);//the first one is the popular match
                    //}
                    //else //if (mediaResult == null)// || mediaResult.filePath == null || mediaResult.filePath.Length == 0)
                    //{
                    //    //find the results and their movie number and let user choose which is correct
                    //    string paragraphPattern = "<p>.*</p>";
                    //    R1 = new Regex(paragraphPattern,
                    //        RegexOptions.IgnoreCase | RegexOptions.IgnorePatternWhitespace);

                    //    if (R1.Matches(_FileContent).Count > 0)
                    //    {
                    //        //display matches
                    //        mediaResult = displayMultipleMatches(R1.Matches(_FileContent)[0].Value, bestMatch);//the first one is the popular match
                    //    }
                    //    else
                    //        _MovieTitle = "No Results";
                    //}
                }
                else
                {
                    mediaResult       = new Media();
                    mediaResult.Title = _MovieTitle;

                    //scrape the director
                    _Director            = getDirectors(_FileContent);
                    mediaResult.Director = HttpUtility.UrlDecode(HttpUtility.UrlEncode(_Director).Replace("%0a", "")).Trim();

                    //scrape release year
                    _ReleaseYear            = getReleaseYear(_FileContent);
                    mediaResult.ReleaseYear = _ReleaseYear;

                    //scrape movie genre
                    _Genre = getGenre(_FileContent);
                    mediaResult.category = _Genre;

                    //scrape movie tagline
                    _TagLine            = getTagline(_FileContent);
                    mediaResult.TagLine = HttpUtility.UrlDecode(HttpUtility.UrlEncode(_TagLine).Replace("%0a", "")).Trim();

                    //scrape movie description
                    _description            = getDescription(_FileContent);
                    mediaResult.Description = System.Web.HttpUtility.UrlDecode(System.Web.HttpUtility.UrlEncode(_description).Replace("%0a", "")).Trim();

                    //scrape rating
                    _rating            = getRating(_FileContent);
                    mediaResult.Rating = _rating;

                    //scrape rating description
                    _ratingDescription            = getRatingDescription(_FileContent);
                    mediaResult.RatingDescription = _ratingDescription;

                    //get mediaType from title
                    mediaResult.MediaType = getMediaType(media.Title);

                    if (_imdbNum != null && _imdbNum.Trim().Length > 0)
                    {
                        mediaResult.IMDBNum = _imdbNum;
                    }
                    else
                    {
                        mediaResult.IMDBNum = getIMDBNum(_FileContent);
                        _imdbNum            = mediaResult.IMDBNum;
                    }

                    mediaResult.Stars = getStars(_FileContent);

                    mediaResult.coverImage = getPhoto(mediaResult);

                    mediaResult.Goofs = HttpUtility.UrlDecode(HttpUtility.UrlEncode(getGoofs(_imdbNum)).Replace("%0a", "|")).Trim();

                    mediaResult.Trivia = HttpUtility.UrlDecode(HttpUtility.UrlEncode(getTrivia(_imdbNum)).Replace("%0a", "|")).Trim();

                    mediaResult.ShortDescription = getShortDescription(_FileContent);

                    _goofs            = mediaResult.Goofs;
                    _trivia           = mediaResult.Trivia;
                    _shortDescription = mediaResult.ShortDescription;
                    _stars            = mediaResult.Stars;
                }
            }
            catch (Exception ex)
            {
                Tools.WriteToFile(ex);
            }

            return(mediaResult);
        }
示例#30
0
        public ActionResult encode()
        {
            var json       = new StreamReader(Request.Body).ReadToEnd();
            var data       = JsonConvert.DeserializeObject <List <EncoderSettings> >(json);
            int ActionType = data[0].tp;
            var _response  = new Dictionary <string, string>();

            _response["encodeoutput"] = "2.0";

            string Source    = "";
            string Published = "";
            string ProcessID = "";

            switch (ActionType)
            {
            case 0:
                // encode video
                Source    = data[0].key;
                Published = Path.GetFileNameWithoutExtension(data[0].key) + data[0].template.prefix;

                if (Source != "" && Published != null)
                {
                    var    _mhandler = new MediaHandler();
                    string RootPath  = SiteConfig.Environment.ContentRootPath;
                    _mhandler.FFMPEGPath           = EncodingSettings.FFMPEGPATH;
                    _mhandler.InputPath            = UrlConfig.Upload_Path("source");
                    _mhandler.OutputPath           = UrlConfig.Upload_Path("published");
                    _mhandler.BackgroundProcessing = true;
                    _mhandler.FileName             = Source;
                    _mhandler.OutputFileName       = Published.Replace(Path.GetExtension(Published), "");
                    _mhandler.Parameters           = EncodingSettings.returnPreset(data[0].template.presetID);          //"-s 640x380 -c:v libx264 -preset medium -crf 22 -b:v 500k -b:a 128k -profile:v baseline -level 3.1"; // Site_Settings.MP4_480p_Settings;
                    _mhandler.OutputExtension      = EncodingSettings.returnOutputExtension(data[0].template.presetID); // ".mp4";
                    _mhandler.vinfo = _mhandler.ProcessMedia();
                    if (_mhandler.vinfo.ErrorCode > 0)
                    {
                        // remove file if failed to publish properly
                        if (System.IO.File.Exists(RootPath + "/" + _mhandler.InputPath))
                        {
                            System.IO.File.Delete(RootPath + "/" + _mhandler.InputPath);
                        }

                        _response["encodeoutput"] = "2.0";
                        _response["ecode"]        = _mhandler.vinfo.ErrorCode.ToString();
                        _response["edesc"]        = _mhandler.vinfo.FFMPEGOutput.ToString();

                        var _message = new System.Text.StringBuilder();
                        _message.Append("<h4>Video Upload Error</h4>");
                        _message.Append("<p>Error:" + _mhandler.vinfo.ErrorCode + " _ _ " + _mhandler.vinfo.ErrorMessage + "</p>");
                        _message.Append("<p>Source FileName: " + Source);
                        _message.Append("<p>Published FileName: " + Published);

                        return(Ok(_response));
                    }
                    else
                    {
                        // _mhandler.vinfo.ProcessID = Guid.NewGuid().ToString(); // unique guid to attach with each process to identify proper object on progress bar and get info request
                        _lst.Add(_mhandler);
                        _response["encodeoutput"] = "2.0";
                        _response["ecode"]        = _mhandler.vinfo.ErrorCode.ToString();
                        _response["procid"]       = _mhandler.vinfo.ProcessID; // _mhandler.vinfo.ProcessID;
                        return(Ok(_response));
                    }
                }
                break;

            case 1:
                // get progress status
                ProcessID = data[0].pid;
                if (ProcessID != "")
                {
                    string completed_process = "0";
                    if (_lst.Count > 0)
                    {
                        int i = 0;
                        for (i = 0; i <= _lst.Count - 1; i++)
                        {
                            if (_lst[i].vinfo.ProcessID == ProcessID)
                            {
                                completed_process = Math.Round(_lst[i].vinfo.ProcessingCompleted, 2).ToString();
                            }
                        }
                    }

                    _response["encodeoutput"] = "2.0";
                    _response["status"]       = completed_process;
                    return(Ok(_response));
                }

                break;

            case 2:
                // get information
                ProcessID = data[0].pid;
                Published = Path.GetFileNameWithoutExtension(data[0].key) + data[0].template.prefix;
                if (ProcessID != "")
                {
                    if (_lst.Count > 0)
                    {
                        int i = 0;
                        for (i = 0; i <= _lst.Count - 1; i++)
                        {
                            if (_lst[i].vinfo.ProcessID == ProcessID)
                            {
                                _response["status"] = "OK";
                                _response["ecode"]  = _lst[i].vinfo.ErrorCode.ToString();
                                _response["fname"]  = Published;

                                _response["dur"]    = _lst[i].vinfo.Duration.ToString();
                                _response["dursec"] = _lst[i].vinfo.Duration_Sec.ToString();


                                // remove from list of corrent processes if processes reach this point
                                // store all information of completed process and remove it from list of concurrent processes
                                // e.g
                                VideoInfo current_uploaded_video_info = _lst[i].vinfo;
                                _lst.Remove(_lst[i]);

                                // Validation
                                int    plength  = 0;
                                var    pub_file = Path.GetFileNameWithoutExtension(data[0].key) + data[0].template.prefix;
                                string path     = UrlConfig.Upload_Path("source") + "\\" + pub_file;
                                if (System.IO.File.Exists(path))
                                {
                                    FileInfo flv_info = new FileInfo(path);
                                    plength = (int)flv_info.Length;
                                }
                                if (plength == 0)
                                {
                                    var _message = new System.Text.StringBuilder();
                                    _message.Append("<h4>Video Publishing Error</h4>");
                                    _message.Append("<p>Error: 0kb file generated</p>");
                                    _message.Append("<p>Source FileName: " + Source);
                                    _message.Append("<p>Published FileName: " + Published);
                                }

                                // ii: add meta information to mp4 video
                                if (data[0].template.applyMeta)
                                {
                                    try
                                    {
                                        var mp4med = new MediaHandler();
                                        mp4med.MP4BoxPath = EncodingSettings.MP4BoxPath;
                                        string _mp4_temp_path = "\"" + UrlConfig.Upload_Path("source") + "/" + pub_file + "\"";
                                        string meta_filename  = data[0].key.Replace(".mp4", "_meta.mp4");
                                        mp4med.Parameters = "-isma -hint -add " + _mp4_temp_path + "";
                                        mp4med.FileName   = meta_filename;
                                        mp4med.InputPath  = UrlConfig.Upload_Path("source");
                                        mp4med.Set_MP4_Buffering();

                                        // check whether file created
                                        string pubPath = UrlConfig.Upload_Path("source");
                                        if (System.IO.File.Exists(pubPath + "\\" + meta_filename))
                                        {
                                            // remove temp mp4 file
                                            if (System.IO.File.Exists(pubPath + "" + pub_file))
                                            {
                                                System.IO.File.Delete(pubPath + "\\" + pub_file);
                                            }

                                            _response["fname"] = meta_filename;
                                        }
                                        else
                                        {
                                            // file not created by mp4box
                                            // rename published mp4 as _meta.mp4
                                            System.IO.File.Move(pubPath + "\\" + pub_file, pubPath + "\\" + meta_filename);
                                            _response["fname"] = meta_filename;
                                        }
                                    }
                                    catch (Exception ex)
                                    {
                                        var _message = new System.Text.StringBuilder();
                                        _message.Append("<h4>Video Meta Information Error</h4>");
                                        _message.Append("<p>Error: " + ex.Message + "</p>");
                                        _message.Append("<p>Source FileName: " + Source);
                                        _message.Append("<p>Published FileName: " + Published);
                                    }
                                }

                                _response["isenable"] = "1";

                                // Thumb Grabbing Script
                                if (data[0].template.generateThumbnails)
                                {
                                    string thumb_start_index = "";
                                    try
                                    {
                                        var med = new MediaHandler();
                                        med.FFMPEGPath           = EncodingSettings.FFMPEGPATH;
                                        med.InputPath            = UrlConfig.Upload_Path("source");     // RootPath + "\\" + SourcePath;
                                        med.OutputPath           = UrlConfig.Upload_Path("thumbnails"); // RootPath + "\\" + PublishedPath;
                                        med.FileName             = data[0].key;                         // source file
                                        thumb_start_index        = med.FileName.Replace(Path.GetExtension(med.FileName), "_");
                                        med.Image_Format         = "jpg";
                                        med.VCodec               = "image2"; //optional
                                        med.ACodec               = "";
                                        med.ImageName            = thumb_start_index;
                                        med.Multiple_Thumbs      = true;
                                        med.ThumbMode            = 0;
                                        med.No_Of_Thumbs         = 15;
                                        med.Thumb_Start_Position = 5;     // start grabbing thumbs from 5th second
                                                                          //if (this.BackgroundProcessing)
                                                                          //    med.BackgroundProcessing = true;
                                        int width = SiteSettings.Width;
                                        if (width > 0)
                                        {
                                            med.Width = width;
                                        }
                                        int height = SiteSettings.Height;
                                        if (height > 0)
                                        {
                                            med.Height = height;
                                        }
                                        var tinfo = med.Grab_Thumb();
                                        if (tinfo.ErrorCode > 0)
                                        {
                                            // Error occured in grabbing thumbs - Rollback process
                                            _response["ecode"] = "1006";
                                            _response["edesc"] = "Grabbing thumbs from video failed";

                                            var _message = new System.Text.StringBuilder();
                                            _message.Append("<h4>Thumb Generation Error</h4>");
                                            _message.Append("<p>Error: " + _response["edesc"] + "</p>");
                                            _message.Append("<p>Source FileName: " + Source);
                                            _message.Append("<p>Published FileName: " + Published);

                                            // call rollback script here
                                            return(Ok(_response));
                                        }

                                        // Validate Thumbs
                                        path = UrlConfig.Upload_Path("thumbnails") + "/" + thumb_start_index;
                                        if (!System.IO.File.Exists(path + "004.jpg") || !System.IO.File.Exists(path + "008.jpg") || !System.IO.File.Exists(path + "011.jpg"))
                                        {
                                            // thumb failed try again grabbing thumbs from published video
                                            med.InputPath = UrlConfig.Upload_Path("published");
                                            med.FileName  = pub_file;    // grab thumb from encoded video
                                            tinfo         = med.Grab_Thumb();
                                            if (tinfo.ErrorCode > 0)
                                            {
                                                // Error occured in grabbing thumbs - Rollback process
                                                _response["ecode"] = "1006";
                                                _response["edesc"] = "Grabbing thumbs from video failed";
                                                // rollback script here
                                                var _message = new System.Text.StringBuilder();
                                                _message.Append("<h4>Thumb Generation Error</h4>");
                                                _message.Append("<p>Error: " + _response["edesc"] + "</p>");
                                                _message.Append("<p>Source FileName: " + Source);
                                                _message.Append("<p>Published FileName: " + Published);
                                                return(Ok(_response));
                                            }
                                            // Disable Video
                                            if (!System.IO.File.Exists(path + "004.jpg") || !System.IO.File.Exists(path + "008.jpg") || !System.IO.File.Exists(path + "011.jpg"))
                                            {
                                                _response["isenable"] = "0";     // disable video - thumbs not grabbed properly.
                                            }
                                        }
                                    }
                                    catch (Exception ex)
                                    {
                                        _response["ecode"] = "1010";
                                        _response["edesc"] = ex.Message;

                                        var _message = new System.Text.StringBuilder();
                                        _message.Append("<h4>Thumb Generation Error</h4>");
                                        _message.Append("<p>Error: " + ex.Message + "</p>");
                                        _message.Append("<p>Source FileName: " + Source);
                                        _message.Append("<p>Published FileName: " + Published);
                                    }

                                    _response["tfile"]   = thumb_start_index + "" + "008.jpg";
                                    _response["fIndex"]  = thumb_start_index;
                                    _response["img_url"] = "/uploads/thumbnails/";     // + _response["tfile"]);
                                }
                                else
                                {
                                    // generate thumbnail is disabled
                                    _response["tfile"]   = "";
                                    _response["fIndex"]  = "";
                                    _response["img_url"] = "";
                                }
                            }
                        }
                    }
                    return(Ok(_response));
                }

                break;

            case 3:
                // final check
                ProcessID = data[0].pid;
                Source    = data[0].key;
                Published = Path.GetFileNameWithoutExtension(data[0].key) + data[0].template.prefix;

                if (ProcessID != "" && Source != "" && Published != "")
                {
                    if (_lst.Count > 0)
                    {
                        int i = 0;
                        for (i = 0; i <= _lst.Count - 1; i++)
                        {
                            if (_lst[i].vinfo.ProcessID == ProcessID)
                            {
                                if (_lst[i].vinfo.ProcessingCompleted >= 100)
                                {
                                    // check whether published file uploaded properly
                                    string publishedPath = UrlConfig.Upload_Path("published");

                                    if (!System.IO.File.Exists(publishedPath + "/" + Published))
                                    {
                                        _response["status"] = "INVALID";    // published file not found
                                    }
                                    else
                                    {
                                        _response["encodeoutput"] = "2.0";
                                        _response["status"]       = "OK";
                                    }
                                }
                            }
                        }
                    }

                    return(Ok(_response));
                }
                break;
            }
            _response["status"] = "INVALID";
            return(Ok(_response));
        }
示例#31
0
    private string convWMV(string _mediaName)
    {
        string ret = "";
        // Sample code for encoding any format video to wmv format.
        MediaHandler _mhandler = new MediaHandler();

        // required properties

        string rootpath    = Server.MapPath(Request.ApplicationPath);
        string inputpath   = Server.MapPath("~/lib/up/v/");
        string outputpath  = Server.MapPath("~/lib/up/v/");
        string _ffmpegpath = HttpContext.Current.Server.MapPath("~\\ffmpeg\\ffmpeg.dll");

        string filenameWMV = Guid.NewGuid().ToString().Substring(0, 10) + ".wmv";

        _mhandler.FFMPEGPath = _ffmpegpath;
        _mhandler.InputPath  = inputpath;
        _mhandler.OutputPath = outputpath;
        _mhandler.FileName   = _mediaName;

        // optional output filename

        _mhandler.OutputFileName = filenameWMV;

        // setting video related properties

        //_mhandler.Video_Bitrate = 786;
        //_mhandler.Audio_Bitrate = 64;
        //_mhandler.Audio_SamplingRate = 44100;

        // generate highest quality mp4 video, note by making this option true, video bitrate will no longer work.

        _mhandler.MaxQuality = true;

        // optional video width and height settings

        _mhandler.Width  = 538;
        _mhandler.Height = 400;

        // Optional parameters for setting audio and video codec for wmv video
        _mhandler.VCodec        = "wmv2";
        _mhandler.ACodec        = "wmav2";
        _mhandler.Audio_Bitrate = 64;
        _mhandler.Video_Bitrate = 1000;

        // posting watermark on wmv video, view detail in watermark section
        //  _mhandler.WaterMarkPath = RootPath + "\\contents\\watermark";
        //  _mhandler.WaterMarkImage = "watermark.gif";

        // view more options in component documentation.

        // Encode WMV Video using Media Handler Pro version 3.0

        //  string output = _mhandler.Encode_WMV();

        // Encode WMV Video using Media Handler Pro version 4.0 or later

        VideoInfo info = _mhandler.Encode_WMV();

        // Check for errors
        if (info.ErrorCode > 0)
        {
            Response.Write("Video processing failed, Error code " + info.ErrorCode + " generated");
            return("");
        }
        ret = filenameWMV;
        return(filenameWMV);
    }