예제 #1
0
        private FileItem(FileContainer fileContainer, string sourceFilePath, TypeFile typeFile)
        {
            FileContainer = fileContainer;
            FilesToDelete = new List <string>();
            CreationDate  = DateTime.UtcNow;
            SetSourceFilePath(sourceFilePath);
            TypeFile = typeFile;
            switch (typeFile)
            {
            case TypeFile.EncodedVideo:
            case TypeFile.SourceVideo:
                SetTempFilePath(Path.ChangeExtension(TempFileManager.GetNewTempFilePath(), ".mp4"));
                break;

            case TypeFile.SpriteVideo:
                SetTempFilePath(Path.ChangeExtension(TempFileManager.GetNewTempFilePath(), ".jpeg"));
                break;

            case TypeFile.SourceImage:
            case TypeFile.SnapImage:
            case TypeFile.OverlayImage:
                SetTempFilePath(Path.ChangeExtension(TempFileManager.GetNewTempFilePath(), ".png"));
                break;

            case TypeFile.SubtitleText:
                SetTempFilePath(Path.ChangeExtension(TempFileManager.GetNewTempFilePath(), ".vtt"));
                break;
            }
        }
예제 #2
0
        public static async Task <Guid> ComputeSubtitle(string text)
        {
            FileContainer fileContainer  = FileContainer.NewSubtitleContainer();
            string        outputfilePath = Path.ChangeExtension(TempFileManager.GetNewTempFilePath(), ".vtt");

            if (!IsValidVTT(text))
            {
                return(fileContainer.ProgressToken);
            }

            try
            {
                await System.IO.File.WriteAllTextAsync(outputfilePath, text);

                fileContainer.SubtitleFileItem.SetOutputFilePath(outputfilePath);
                IpfsDaemon.Instance.Queue(fileContainer.SubtitleFileItem);
            }
            catch (Exception ex)
            {
                TempFileManager.SafeDeleteTempFile(outputfilePath);
                LogManager.AddSubtitleMessage(ex.ToString(), "Exception");
                return(fileContainer.ProgressToken);
            }

            return(fileContainer.ProgressToken);
        }
예제 #3
0
        public static async Task <Guid> ComputeSubtitle(string text)
        {
            FileContainer fileContainer  = FileContainer.NewSubtitleContainer();
            string        outputfilePath = Path.ChangeExtension(TempFileManager.GetNewTempFilePath(), ".vtt");

            if (!IsValidVTT(text))
            {
                fileContainer.SubtitleFileItem.IpfsProcess.SetErrorMessage("Not a valid WEBVTT file", "Not a valid WEBVTT file");
                return(fileContainer.ProgressToken);
            }

            try
            {
                await File.WriteAllTextAsync(outputfilePath, text);

                fileContainer.SubtitleFileItem.SetOutputFilePath(outputfilePath);
                IpfsDaemon.Instance.Queue(fileContainer.SubtitleFileItem);
            }
            catch (Exception ex)
            {
                TempFileManager.SafeDeleteTempFile(outputfilePath);
                LogManager.AddSubtitleMessage(LogLevel.Critical, "Exception non gérée", "Exception", ex);
                return(fileContainer.ProgressToken);
            }

            return(fileContainer.ProgressToken);
        }
예제 #4
0
        public static Guid ComputeOverlay(string sourceFilePath)
        {
            FileContainer fileContainer = FileContainer.NewOverlayContainer(sourceFilePath);

            var processStartInfo = new ProcessStartInfo();

            processStartInfo.WorkingDirectory = TempFileManager.GetTempDirectory();
            processStartInfo.UseShellExecute  = false;
            processStartInfo.ErrorDialog      = false;
            processStartInfo.CreateNoWindow   = true;
            processStartInfo.WindowStyle      = ProcessWindowStyle.Hidden;

            string oldFilePath    = fileContainer.SourceFileItem.FilePath;
            string outputFilePath = null;

            try
            {
                LogManager.AddOverlayMessage("SourceFileName " + Path.GetFileName(oldFilePath), "Start Crop");
                // resize + crop source image
                outputFilePath             = Path.ChangeExtension(TempFileManager.GetNewTempFilePath(), ".png");
                processStartInfo.FileName  = Path.Combine(FrontSettings.ImageMagickPath, "convert");
                processStartInfo.Arguments = $"{Path.GetFileName(fileContainer.SourceFileItem.FilePath)} -resize \"{_finalWidth}x{_finalHeight}^\" -gravity Center -crop {_finalWidth}x{_finalHeight}+0+0 {Path.GetFileName(outputFilePath)}";
                StartProcess(processStartInfo, 5000);
                fileContainer.SourceFileItem.FilePath = outputFilePath;
                LogManager.AddOverlayMessage("OutputFileName " + Path.GetFileName(outputFilePath), "End Crop");
                IpfsDaemon.Queue(fileContainer.SourceFileItem);
            }
            catch (Exception ex)
            {
                TempFileManager.SafeDeleteTempFile(outputFilePath);
                LogManager.AddOverlayMessage(ex.ToString(), "Exception");
                return(fileContainer.ProgressToken);
            }
            finally
            {
                TempFileManager.SafeDeleteTempFile(oldFilePath);
            }

            try
            {
                LogManager.AddOverlayMessage("SourceFileName " + Path.GetFileName(fileContainer.SourceFileItem.FilePath), "Start Overlay");
                // watermark source image
                outputFilePath             = Path.ChangeExtension(TempFileManager.GetNewTempFilePath(), ".png");
                processStartInfo.FileName  = Path.Combine(FrontSettings.ImageMagickPath, "composite");
                processStartInfo.Arguments = $"-gravity NorthEast {_overlayImagePath} {Path.GetFileName(fileContainer.SourceFileItem.FilePath)} {Path.GetFileName(outputFilePath)}";
                StartProcess(processStartInfo, 5000);
                fileContainer.OverlayFileItem.FilePath = outputFilePath;
                LogManager.AddOverlayMessage("OutputFileName " + Path.GetFileName(outputFilePath), "End Overlay");
                IpfsDaemon.Queue(fileContainer.OverlayFileItem);
            }
            catch (Exception ex)
            {
                TempFileManager.SafeDeleteTempFile(outputFilePath);
                LogManager.AddOverlayMessage(ex.ToString(), "Exception");
                return(fileContainer.ProgressToken);
            }

            return(fileContainer.ProgressToken);
        }
예제 #5
0
        public static void ResizeImage(FileContainer fileContainer)
        {
            try
            {
                string oldFilePath = fileContainer.SourceFileItem.FilePath;
                using (Image sourceImage = Image.FromFile(oldFilePath))
                {
                    //create a bitmap to hold the new image
                    using (var finalBitmap = new Bitmap(_finalWidth, _finalHeight))
                    {
                        using (Graphics graphics = Graphics.FromImage(finalBitmap))
                        {
                            Rectangle sourceRectangle;
                            Rectangle destRectangle = new Rectangle(0, 0, _finalWidth, _finalHeight);
                            // video verticale, garder largeur _finalWidth, couper la hauteur
                            if ((double)sourceImage.Width / (double)sourceImage.Height < ((double)_finalWidth / (double)_finalHeight))
                            {
                                int hauteur = sourceImage.Width * _finalHeight / _finalWidth;
                                int yOffset = (sourceImage.Height - hauteur) / 2;
                                sourceRectangle = new Rectangle(0, yOffset, sourceImage.Width, hauteur);
                            }
                            else // video horizontale, garder hauteur _finalHeight, couper la largeur
                            {
                                int largeur = sourceImage.Height * _finalWidth / _finalHeight;
                                int xOffset = (sourceImage.Width - largeur) / 2;
                                sourceRectangle = new Rectangle(xOffset, 0, largeur, sourceImage.Height);
                            }
                            graphics.DrawImage(sourceImage, destRectangle, sourceRectangle, GraphicsUnit.Pixel);
                        }
                        string outputFilePath = System.IO.Path.ChangeExtension(TempFileManager.GetNewTempFilePath(), ".jpeg");
                        finalBitmap.Save(outputFilePath, ImageFormat.Jpeg);
                        fileContainer.SourceFileItem.FilePath = outputFilePath;
                    }
                }

                IpfsDaemon.Queue(fileContainer.SourceFileItem);
                TempFileManager.SafeDeleteTempFile(oldFilePath);
            }
            catch (Exception ex)
            {
                LogManager.AddOverlayMessage(ex.ToString(), "Exception");
            }
        }
예제 #6
0
        private async Task <string> GetFileToTemp()
        {
            // Copy file to temp location
            string sourceFilePath = TempFileManager.GetNewTempFilePath();

            FormValueProvider formModel;

            try
            {
                // Récupération du fichier
                using (System.IO.FileStream stream = System.IO.File.Create(sourceFilePath))
                {
                    formModel = await Request.StreamFile(stream);
                }
            }
            catch (Exception ex)
            {
                LogManager.AddGeneralMessage(LogLevel.Critical, $"Exception Download File : {ex}", "Exception");
                TempFileManager.SafeDeleteTempFile(sourceFilePath);
                throw;
            }

            try
            {
                ValueProviderResult fileName = formModel.GetValue("qqFileName");
                if (fileName.Length == 1)
                {
                    var extension = System.IO.Path.GetExtension(fileName.FirstValue);
                    if (!string.IsNullOrWhiteSpace(extension))
                    {
                        string newFilePath = System.IO.Path.ChangeExtension(sourceFilePath, extension);
                        System.IO.File.Move(sourceFilePath, newFilePath);
                        sourceFilePath = newFilePath;
                    }
                }
            }
            catch {}

            return(sourceFilePath);
        }
        private async Task <string> GetFileToTemp()
        {
            // Copy file to temp location
            string sourceFilePath = TempFileManager.GetNewTempFilePath();

            try
            {
                // Récupération du fichier
                FormValueProvider formModel;
                using (FileStream stream = System.IO.File.Create(sourceFilePath))
                {
                    formModel = await Request.StreamFile(stream);
                }
                //var fileName = formModel.GetValue("qqFileName");
                return(sourceFilePath);
            }
            catch
            {
                TempFileManager.SafeDeleteTempFile(sourceFilePath);
                throw;
            }
        }
예제 #8
0
        public static Guid ComputeOverlay(string sourceFilePath, int?x = null, int?y = null)
        {
            FileContainer fileContainer = FileContainer.NewOverlayContainer(sourceFilePath);

            ResizeImage(fileContainer);

            try
            {
                using (Image overlayImage = Image.FromFile(_overlayImagePath))
                {
                    using (Image sourceImage = Image.FromFile(fileContainer.SourceFileItem.FilePath))
                    {
                        using (Graphics graphics = Graphics.FromImage(sourceImage))
                        {
                            // Si position n'est pas fournie, centrer l'image
                            if (x == null || y == null)
                            {
                                x = (sourceImage.Width / 2) - (overlayImage.Width / 2);
                                y = (sourceImage.Height / 2) - (overlayImage.Height / 2);
                            }

                            graphics.DrawImage(overlayImage, x.Value, y.Value);
                        }
                        string outputFilePath = System.IO.Path.ChangeExtension(TempFileManager.GetNewTempFilePath(), ".jpeg");
                        sourceImage.Save(outputFilePath, ImageFormat.Jpeg);
                        fileContainer.OverlayFileItem.FilePath = outputFilePath;
                    }
                }

                IpfsDaemon.Queue(fileContainer.OverlayFileItem);
            }
            catch (Exception ex)
            {
                LogManager.AddOverlayMessage(ex.ToString(), "Exception");
            }

            return(fileContainer.ProgressToken);
        }
예제 #9
0
        private static void Start()
        {
            daemon = Task.Run(() =>
            {
                while (true)
                {
                    Thread.Sleep(1000);

                    FileItem fileItem;

                    if (!queueFileItems.TryDequeue(out fileItem))
                    {
                        continue;
                    }

                    CurrentPositionInQueue++;

                    // encode video
                    bool success = EncodeManager.Encode(fileItem);

                    if (success)
                    {
                        if (fileItem.ModeSprite)
                        {
                            string[] files    = SpriteManager.GetListImageFrom(fileItem.FilePath); // récupération des images
                            string outputPath = TempFileManager.GetNewTempFilePath();              // nom du fichier sprite
                            SpriteManager.CombineBitmap(files, outputPath);                        // création du sprite
                            TempFileManager.SafeDeleteTempFiles(fileItem.FilePath);                // suppression des images
                            fileItem.FilePath = outputPath;                                        // réaffectation chemin sprite
                        }

                        IpfsDaemon.Queue(fileItem);
                    }
                }
            });
        }
예제 #10
0
        private static void Start()
        {
            daemon = Task.Run(() =>
            {
                while (true)
                {
                    try
                    {
                        Thread.Sleep(1000);

                        FileItem fileItem;

                        if (!queueFileItems.TryDequeue(out fileItem))
                        {
                            continue;
                        }

                        CurrentPositionInQueue++;

                        // si le client a pas demandé le progress depuis plus de 20s, annuler l'opération
                        if ((DateTime.UtcNow - fileItem.FileContainer.LastTimeProgressRequested).TotalSeconds > FrontSettings.MaxGetProgressCanceled)
                        {
                            fileItem.EncodeErrorMessage = "Canceled";
                            fileItem.EncodeProgress     = null;

                            fileItem.IpfsErrorMessage = "Canceled";
                            fileItem.IpfsProgress     = null;

                            continue;
                        }

                        // encode video
                        if (!EncodeManager.Encode(fileItem))
                        {
                            continue;
                        }

                        switch (fileItem.TypeFile)
                        {
                        case TypeFile.SpriteVideo:
                            {
                                string[] files     = EncodeManager.GetListImageFrom(fileItem.FilePath);                                                          // récupération des images
                                string outputPath  = Path.ChangeExtension(TempFileManager.GetNewTempFilePath(), ".jpeg");                                        // nom du fichier sprite
                                bool successSprite = SpriteManager.CombineBitmap(files.Skip(files.Length - VideoSettings.NbSpriteImages).ToArray(), outputPath); // création du sprite
                                TempFileManager.SafeDeleteTempFiles(files);                                                                                      // suppression des images
                                if (successSprite)
                                {
                                    fileItem.FilePath = outputPath;     // réaffectation chemin sprite
                                    LogManager.AddEncodingMessage("FileSize " + fileItem.FileSize, "End Sprite");
                                    IpfsDaemon.Queue(fileItem);
                                }
                                else
                                {
                                    TempFileManager.SafeDeleteTempFile(outputPath);
                                }

                                break;
                            }

                        case TypeFile.EncodedVideo:
                            IpfsDaemon.Queue(fileItem);
                            break;

                        default:
                            throw new InvalidOperationException("type non prévu");
                        }
                    }
                    catch (Exception ex)
                    {
                        LogManager.AddEncodingMessage(ex.ToString(), "Exception non gérée");
                    }
                }
            });
        }
예제 #11
0
        public static bool SuccessAnalyseSource(FileItem sourceFile, bool spriteMode, ProcessItem processItem)
        {
            if (sourceFile == null)
            {
                throw new ArgumentNullException(nameof(sourceFile));
            }
            if (sourceFile == null)
            {
                throw new ArgumentNullException(nameof(sourceFile));
            }
            if (!sourceFile.IsSource)
            {
                throw new ArgumentException("Doit être le fichier source", nameof(sourceFile));
            }

            // Récupérer la durée totale de la vidéo et sa résolution
            if (!sourceFile.VideoDuration.HasValue)
            {
                lock (sourceFile)
                {
                    if (!sourceFile.VideoDuration.HasValue)
                    {
                        string imageOutputPath = Path.ChangeExtension(TempFileManager.GetNewTempFilePath(), ".jpeg");

                        try
                        {
                            var    ffmpegProcessManager = new FfmpegProcessManager(sourceFile, sourceFile.InfoSourceProcess);
                            string argumentsImage       = $"-y -i {Path.GetFileName(sourceFile.SourceFilePath)} -vf fps=1 -vframes 1 {Path.GetFileName(imageOutputPath)}";
                            ffmpegProcessManager.StartProcess(argumentsImage, VideoSettings.EncodeGetOneImageTimeout);

                            using (Image image = Image.FromFile(imageOutputPath))
                            {
                                sourceFile.VideoWidth  = image.Width;
                                sourceFile.VideoHeight = image.Height;
                            }
                        }
                        catch (Exception ex)
                        {
                            Log(ex.ToString(), "Exception source info", spriteMode);
                            sourceFile.VideoDuration = -1; //pour ne pas essayer de le recalculer sur une demande de video à encoder
                        }

                        TempFileManager.SafeDeleteTempFile(imageOutputPath);
                    }
                }
            }

            // Si durée totale de vidéo, largeur hauteur non récupéré, on ne peut pas continuer
            if (!sourceFile.SuccessGetSourceInfo())
            {
                string message = "Error while getting duration, height or width.";
                Log(message + " FileName : " + Path.GetFileName(sourceFile.SourceFilePath), "Error source info", spriteMode);

                if (!spriteMode && sourceFile.IpfsProcess == null)
                {
                    sourceFile.AddIpfsProcess(sourceFile.SourceFilePath);
                    IpfsDaemon.Instance.Queue(sourceFile);
                }

                processItem.SetErrorMessage(message);

                return(false);
            }

            int duration = sourceFile.VideoDuration.Value;

            Log("SourceVideoDuration " + duration + " / SourceVideoFileSize " + sourceFile.FileSize, "Info source", spriteMode);

            // Désactivation encoding et sprite si dépassement de la durée maximale
            if (sourceFile.HasReachMaxVideoDurationForEncoding())
            {
                if (!spriteMode && sourceFile.IpfsProcess == null)
                {
                    sourceFile.AddIpfsProcess(sourceFile.SourceFilePath);
                    IpfsDaemon.Instance.Queue(sourceFile);
                }

                processItem.CancelCascade("Dépassement de la durée limite de la vidéo atteinte.");

                return(false);
            }

            return(true);
        }
예제 #12
0
        public static bool CheckAndAnalyseSource(FileItem fileItem, bool spriteMode)
        {
            FileItem sourceFile = fileItem.FileContainer.SourceFileItem;

            // Récupérer la durée totale de la vidéo et sa résolution
            if (!sourceFile.VideoDuration.HasValue)
            {
                lock (sourceFile)
                {
                    if (!sourceFile.VideoDuration.HasValue)
                    {
                        string imageOutputPath = Path.ChangeExtension(TempFileManager.GetNewTempFilePath(), ".jpeg");

                        try
                        {
                            var    ffmpegProcessManager = new FfmpegProcessManager(fileItem);
                            string argumentsImage       = $"-y -i {Path.GetFileName(sourceFile.FilePath)} -vf fps=1 -vframes 1 {Path.GetFileName(imageOutputPath)}";
                            ffmpegProcessManager.StartProcess(argumentsImage, VideoSettings.EncodeGetOneImageTimeout);

                            using (Image image = Image.FromFile(imageOutputPath))
                            {
                                sourceFile.VideoWidth  = image.Width;
                                sourceFile.VideoHeight = image.Height;
                            }
                        }
                        catch (Exception ex)
                        {
                            Log(ex.ToString(), "Exception", spriteMode);
                            sourceFile.VideoDuration = -1; //pour ne pas essayer de le recalculer sur une demande de video à encoder
                        }

                        TempFileManager.SafeDeleteTempFile(imageOutputPath);
                    }
                }
            }

            // Si durée totale de vidéo, largeur hauteur non récupéré, on ne peut pas continuer
            if ((sourceFile.VideoDuration ?? 0) <= 0 || (sourceFile.VideoWidth ?? 0) <= 0 || (sourceFile.VideoHeight ?? 0) <= 0)
            {
                Log("Error while getting duration, height or width. FileName : " + Path.GetFileName(sourceFile.FilePath), "Error", spriteMode);
                fileItem.EncodeErrorMessage = "Error while getting duration, height or width.";
                fileItem.CleanFiles();
                return(false);
            }

            int duration = sourceFile.VideoDuration.Value;

            Log("SourceVideoDuration " + duration + " / SourceVideoFileSize " + fileItem.FileContainer.SourceFileItem.FileSize, "Info source", spriteMode);

            // Désactivation encoding et sprite si dépassement de la durée maximale
            if (duration > VideoSettings.MaxVideoDurationForEncoding)
            {
                fileItem.EncodeErrorMessage = "Disable because duration reach the max limit.";
                if (spriteMode)
                {
                    fileItem.FileContainer.DeleteSpriteVideo();
                }
                else
                {
                    fileItem.FileContainer.EncodedFileItems.Clear();
                }
                fileItem.CleanFiles();
                return(false);
            }

            return(true);
        }
예제 #13
0
        public static bool Encode(FileItem fileItem)
        {
            string newEncodedFilePath = null;

            try
            {
                currentFileItem = fileItem;
                currentFileItem.EncodeProgress = "0.00%";

                FileItem sourceFile     = currentFileItem.FileContainer.SourceFileItem;
                string   sourceFilePath = sourceFile.FilePath;
                newEncodedFilePath = Path.ChangeExtension(TempFileManager.GetNewTempFilePath(), ".mp4");
                LogManager.AddEncodingMessage("FileName " + Path.GetFileName(newEncodedFilePath), "Start");
                VideoSize videoSize = currentFileItem.VideoSize;

                Debug.WriteLine(Path.GetFileName(sourceFilePath) + " / " + videoSize);

                var processStartInfo = new ProcessStartInfo();
                processStartInfo.FileName = "ffmpeg";

                processStartInfo.RedirectStandardError = true;
                processStartInfo.WorkingDirectory      = TempFileManager.GetTempDirectory();

                processStartInfo.UseShellExecute = false;
                processStartInfo.ErrorDialog     = false;
                processStartInfo.CreateNoWindow  = true;
                processStartInfo.WindowStyle     = ProcessWindowStyle.Hidden;

                // Récupérer la durée totale de la vidéo et sa résolution
                if (!sourceFile.VideoDuration.HasValue)
                {
                    string imageOutput = Path.ChangeExtension(sourceFilePath, ".jpeg");
                    processStartInfo.Arguments = $"-y -i {Path.GetFileName(sourceFilePath)} -vf fps=1 -vframes 1 {Path.GetFileName(imageOutput)}";

                    StartProcess(processStartInfo, VideoSettings.EncodeGetOneImageTimeout);

                    using (Image image = Image.FromFile(imageOutput))
                    {
                        sourceFile.VideoWidth  = image.Width;
                        sourceFile.VideoHeight = image.Height;
                    }
                    TempFileManager.SafeDeleteTempFile(imageOutput);
                }

                // Si durée totale de vidéo, largeur hauteur non récupéré, on ne peut pas continuer
                if ((sourceFile.VideoDuration ?? 0) <= 0)
                {
                    return(false);
                }
                if ((sourceFile.VideoHeight ?? 0) <= 0)
                {
                    return(false);
                }
                if ((sourceFile.VideoHeight ?? 0) <= 0)
                {
                    return(false);
                }

                int duration = sourceFile.VideoDuration.Value;

                // Désactivation encoding et sprite si dépassement de la durée maximale
                if (duration > VideoSettings.MaxVideoDurationForEncoding)
                {
                    currentFileItem.EncodeErrorMessage = "Disable because duration reach the max limit.";
                    currentFileItem.FileContainer.EncodedFileItems.Clear();
                    currentFileItem.FileContainer.DeleteSpriteVideo();
                    return(false);
                }

                switch (currentFileItem.TypeFile)
                {
                case TypeFile.SpriteVideo:
                {
                    int nbImages     = VideoSettings.NbSpriteImages;
                    int heightSprite = VideoSettings.HeightSpriteImages;

                    // Calculer nb image/s
                    //  si < 100s de vidéo -> 1 image/s
                    //  sinon (nb secondes de la vidéo / 100) image/s
                    string frameRate = "1";
                    if (duration > nbImages)
                    {
                        frameRate = $"{nbImages}/{duration}";         //frameRate = inverse de image/s
                    }

                    int    spriteWidth  = GetWidth(sourceFile.VideoWidth.Value, sourceFile.VideoHeight.Value, heightSprite);
                    string sizeImageMax = $"scale={spriteWidth}:{heightSprite}";

                    // Extract frameRate image/s de la video
                    string pattern = GetPattern(newEncodedFilePath);
                    processStartInfo.Arguments = $"-y -i {Path.GetFileName(sourceFilePath)} -r {frameRate} -vf \"{sizeImageMax}\" -f image2 {pattern}";

                    StartProcess(processStartInfo, VideoSettings.EncodeGetImagesTimeout);
                    break;
                }

                case TypeFile.EncodedVideo:
                {
                    string size;
                    switch (videoSize)
                    {
                    case VideoSize.F360p:
                    {
                        Tuple <int, int> finalSize = GetSize(sourceFile.VideoWidth.Value, sourceFile.VideoHeight.Value, 640, 360);
                        size = $"{finalSize.Item1}:{finalSize.Item2}";
                        break;
                    }

                    case VideoSize.F480p:
                    {
                        Tuple <int, int> finalSize = GetSize(sourceFile.VideoWidth.Value, sourceFile.VideoHeight.Value, 854, 480);
                        size = $"{finalSize.Item1}:{finalSize.Item2}";
                        break;
                    }

                    case VideoSize.F720p:
                    {
                        Tuple <int, int> finalSize = GetSize(sourceFile.VideoWidth.Value, sourceFile.VideoHeight.Value, 1280, 720);
                        size = $"{finalSize.Item1}:{finalSize.Item2}";
                        break;
                    }

                    case VideoSize.F1080p:
                    {
                        Tuple <int, int> finalSize = GetSize(sourceFile.VideoWidth.Value, sourceFile.VideoHeight.Value, 1920, 1080);
                        size = $"{finalSize.Item1}:{finalSize.Item2}";
                        break;
                    }

                    default:
                        throw new InvalidOperationException("Format non reconnu.");
                    }

                    string formatEncode = "libx264";
                    if (VideoSettings.GpuEncodeMode)
                    {
                        string maxRate = string.Empty;
                        formatEncode = "h264_nvenc";
                        switch (videoSize)
                        {
                        case VideoSize.F360p:
                            maxRate = "200k";
                            break;

                        case VideoSize.F480p:
                            maxRate = "500k";
                            break;

                        case VideoSize.F720p:
                            maxRate = "1000k";
                            break;

                        case VideoSize.F1080p:
                            maxRate = "1600k";
                            break;

                        default:
                            throw new InvalidOperationException("Format non reconnu.");
                        }

                        processStartInfo.Arguments = $"-y -i {Path.GetFileName(sourceFilePath)} -vcodec {formatEncode} -vf \"scale={size},format=yuv420p\" -b:v {maxRate} -maxrate {maxRate} -bufsize {maxRate} -acodec aac {Path.GetFileName(newEncodedFilePath)}";
                    }
                    else
                    {
                        processStartInfo.Arguments = $"-y -i {Path.GetFileName(sourceFilePath)} -vcodec {formatEncode} -vf \"scale={size},format=yuv420p\" -acodec aac {Path.GetFileName(newEncodedFilePath)}";
                    }

                    StartProcess(processStartInfo, VideoSettings.EncodeTimeout);
                    break;
                }

                default:
                    throw new InvalidOperationException("type non prévu");
                }

                currentFileItem.FilePath       = newEncodedFilePath;
                currentFileItem.EncodeProgress = "100.00%";
                switch (currentFileItem.TypeFile)
                {
                case TypeFile.SpriteVideo:
                    LogManager.AddEncodingMessage("Video Duration " + duration + " / SourceVideoFileSize " + currentFileItem.FileContainer.SourceFileItem.FileSize, "End Extract Images");
                    break;

                case TypeFile.EncodedVideo:
                    LogManager.AddEncodingMessage("Video Duration " + duration + " / FileSize " + currentFileItem.FileSize + " / Format " + videoSize, "End Encoding");
                    break;

                default:
                    throw new InvalidOperationException("type non prévu");
                }

                return(true);
            }
            catch (Exception ex)
            {
                LogManager.AddEncodingMessage("Video Duration " + currentFileItem.VideoDuration + " / FileSize " + currentFileItem.FileSize + " / Progress " + currentFileItem.EncodeProgress + " / Exception : " + ex, "Exception");
                currentFileItem.EncodeErrorMessage = ex.Message;

                TempFileManager.SafeDeleteTempFile(newEncodedFilePath);

                if (currentFileItem.VideoSize != VideoSize.Source)
                {
                    TempFileManager.SafeDeleteTempFile(currentFileItem.FilePath);
                }

                if (currentFileItem.TypeFile == TypeFile.SpriteVideo)
                {
                    string[] files = EncodeManager.GetListImageFrom(newEncodedFilePath); // récupération des images
                    TempFileManager.SafeDeleteTempFiles(files);                          // suppression des images
                }

                return(false);
            }
        }
예제 #14
0
        public static bool Encode(FileItem fileItem)
        {
            string newEncodedFilePath = null;

            try
            {
                fileItem.EncodeProgress = "0.00%";

                FileItem  sourceFile     = fileItem.FileContainer.SourceFileItem;
                string    sourceFilePath = sourceFile.FilePath;
                VideoSize videoSize      = fileItem.VideoSize;
                LogManager.AddEncodingMessage("SourceFilePath " + Path.GetFileName(sourceFilePath) + " -> " + videoSize, "Start");

                // Récupérer la durée totale de la vidéo et sa résolution, autorisation encoding
                if (!VideoSourceManager.CheckAndAnalyseSource(fileItem, false))
                {
                    return(false);
                }

                string size;
                string maxRate = string.Empty;
                switch (videoSize)
                {
                case VideoSize.F360p:
                {
                    maxRate = "200k";
                    Tuple <int, int> finalSize = SizeHelper.GetSize(sourceFile.VideoWidth.Value, sourceFile.VideoHeight.Value, 640, 360);
                    size = $"{finalSize.Item1}:{finalSize.Item2}";
                    break;
                }

                case VideoSize.F480p:
                {
                    maxRate = "500k";
                    Tuple <int, int> finalSize = SizeHelper.GetSize(sourceFile.VideoWidth.Value, sourceFile.VideoHeight.Value, 854, 480);
                    size = $"{finalSize.Item1}:{finalSize.Item2}";
                    break;
                }

                case VideoSize.F720p:
                {
                    maxRate = "1000k";
                    Tuple <int, int> finalSize = SizeHelper.GetSize(sourceFile.VideoWidth.Value, sourceFile.VideoHeight.Value, 1280, 720);
                    size = $"{finalSize.Item1}:{finalSize.Item2}";
                    break;
                }

                case VideoSize.F1080p:
                {
                    maxRate = "1600k";
                    Tuple <int, int> finalSize = SizeHelper.GetSize(sourceFile.VideoWidth.Value, sourceFile.VideoHeight.Value, 1920, 1080);
                    size = $"{finalSize.Item1}:{finalSize.Item2}";
                    break;
                }

                default:
                    throw new InvalidOperationException("Format non reconnu.");
                }

                newEncodedFilePath = Path.ChangeExtension(TempFileManager.GetNewTempFilePath(), ".mp4");
                string arguments;
                if (VideoSettings.GpuEncodeMode)
                {
                    arguments = $"-y -hwaccel cuvid -vcodec h264_cuvid -vsync 0 -i {Path.GetFileName(sourceFilePath)} -vf \"scale_npp={size},format=yuv420p\" -b:v {maxRate} -maxrate {maxRate} -bufsize {maxRate} -vcodec h264_nvenc -acodec copy {Path.GetFileName(newEncodedFilePath)}";
                }
                else
                {
                    arguments = $"-y -i {Path.GetFileName(sourceFilePath)} -vf \"scale={size},format=yuv420p\" -vcodec libx264 -acodec aac {Path.GetFileName(newEncodedFilePath)}";
                }

                var ffmpegProcessManager = new FfmpegProcessManager(fileItem);
                ffmpegProcessManager.StartProcess(arguments, VideoSettings.EncodeTimeout);

                fileItem.FilePath = newEncodedFilePath;
                LogManager.AddEncodingMessage("OutputFileName " + Path.GetFileName(newEncodedFilePath) + " / FileSize " + fileItem.FileSize + " / Format " + videoSize, "End Encoding");

                fileItem.EncodeProgress = "100.00%";
                return(true);
            }
            catch (Exception ex)
            {
                LogManager.AddEncodingMessage("Video Duration " + fileItem.VideoDuration + " / FileSize " + fileItem.FileSize + " / Progress " + fileItem.EncodeProgress + " / Exception : " + ex, "Exception");
                fileItem.EncodeErrorMessage = "Exception";
                TempFileManager.SafeDeleteTempFile(newEncodedFilePath);
                fileItem.CleanFiles();
                return(false);
            }
        }
예제 #15
0
        public static bool Encode(FileItem fileItem)
        {
            string newEncodedFilePath = null;

            try
            {
                fileItem.EncodeProgress = "0.00%";

                FileItem sourceFile     = fileItem.FileContainer.SourceFileItem;
                string   sourceFilePath = sourceFile.FilePath;
                LogManager.AddSpriteMessage("SourceFilePath " + Path.GetFileName(sourceFilePath), "Start Sprite");

                // Récupérer la durée totale de la vidéo et sa résolution, autorisation sprite creation
                if (!VideoSourceManager.CheckAndAnalyseSource(fileItem, false))
                {
                    return(false);
                }

                int nbImages     = VideoSettings.NbSpriteImages;
                int heightSprite = VideoSettings.HeightSpriteImages;

                // Calculer nb image/s
                //  si < 100s de vidéo -> 1 image/s
                //  sinon (nb secondes de la vidéo / 100) image/s
                string frameRate = "1";
                int    duration  = sourceFile.VideoDuration.Value;
                if (duration > nbImages)
                {
                    frameRate = $"{nbImages}/{duration}"; //frameRate = inverse de image/s
                }

                int    spriteWidth  = SizeHelper.GetWidth(sourceFile.VideoWidth.Value, sourceFile.VideoHeight.Value, heightSprite);
                string sizeImageMax = $"scale={spriteWidth}:{heightSprite}";

                newEncodedFilePath = Path.ChangeExtension(TempFileManager.GetNewTempFilePath(), ".sprite");

                // Extract frameRate image/s de la video
                string pattern = GetPattern(newEncodedFilePath);

                string arguments            = $"-y -i {Path.GetFileName(sourceFilePath)} -r {frameRate} -vf \"{sizeImageMax}\" -f image2 {pattern}";
                var    ffmpegProcessManager = new FfmpegProcessManager(fileItem);
                ffmpegProcessManager.StartProcess(arguments, VideoSettings.EncodeGetImagesTimeout);

                string[] files = GetListImageFrom(newEncodedFilePath);                                                                    // récupération des images
                LogManager.AddSpriteMessage((files.Length - 1) + " images", "Start Combine images");
                string outputFilePath = Path.ChangeExtension(TempFileManager.GetNewTempFilePath(), ".jpeg");                              // nom du fichier sprite
                bool   successSprite  = CombineBitmap(files.Skip(files.Length - VideoSettings.NbSpriteImages).ToArray(), outputFilePath); // création du sprite
                TempFileManager.SafeDeleteTempFiles(files);                                                                               // suppression des images
                if (successSprite)
                {
                    newEncodedFilePath = outputFilePath;
                    fileItem.FilePath  = newEncodedFilePath;
                    LogManager.AddSpriteMessage("OutputFileName " + Path.GetFileName(outputFilePath) + " / FileSize " + fileItem.FileSize, "End Sprite");
                }
                else
                {
                    LogManager.AddSpriteMessage("Error while combine images", "Error");
                    fileItem.EncodeErrorMessage = "Error creation sprite while combine images";
                    fileItem.CleanFiles();
                    return(false);
                }

                fileItem.EncodeProgress = "100.00%";
                return(true);
            }
            catch (Exception ex)
            {
                LogManager.AddSpriteMessage("Video Duration " + fileItem.VideoDuration + " / FileSize " + fileItem.FileSize + " / Progress " + fileItem.EncodeProgress + " / Exception : " + ex, "Exception");
                fileItem.EncodeErrorMessage = "Exception";
                string[] files = GetListImageFrom(newEncodedFilePath); // récupération des images
                TempFileManager.SafeDeleteTempFiles(files);            // suppression des images
                fileItem.CleanFiles();
                return(false);
            }
        }