Exemplo n.º 1
0
        protected override void Convert()
        {
            var result = SautinSoftOffice.InitWord();

            if (result == 0) //succesfully opend program
            {
                do
                {
                    var document = ConversionQueue.Dequeue();

                    string newPath = "";

                    if (document.Name.EndsWith(SupportedExtension))
                    {
                        var newName = document.Name.Replace(SupportedExtension, Constants.PDFExtension);
                        newPath = document.FullPath.Replace(document.Name, newName);
                    }

                    result = SautinSoftOffice.ConvertFile(document.FullPath, newPath, UseOffice.eDirection.DOCX_to_PDF);
                } while (ConversionQueue.Count > 0);

                SautinSoftOffice.CloseWord();
            }

            ConversionThread.Abort();
        }
Exemplo n.º 2
0
        public void QueueTimeOutTest()
        {
            var queue            = new ConversionQueue();
            var exceptionOccures = false;

            for (var i = 0; i < 2; i++)
            {
                string      output     = Path.Combine(Path.GetTempPath(), Guid.NewGuid() + Extensions.Mp4);
                IConversion conversion = ConversionHelper.ToTs(Resources.Mp4, output);
                queue.Add(conversion);
            }

            var cancellationTokenSource = new CancellationTokenSource(500);

            queue.Start(cancellationTokenSource);
            var resetEvent = new AutoResetEvent(false);

            queue.OnException += (number, count, conversion) =>
            {
                exceptionOccures = true;
                resetEvent.Set();
            };
            queue.Dispose();
            resetEvent.WaitOne();
            Assert.True(exceptionOccures);
        }
Exemplo n.º 3
0
        public async Task QueueNumberIncrementExceptionTest()
        {
            var queue             = new ConversionQueue();
            var currentItemNumber = 0;
            var totalItemsCount   = 0;

            for (var i = 0; i < 2; i++)
            {
                string output = Path.Combine(Path.GetTempPath(), Guid.NewGuid() + FileExtensions.Mp4);
                File.Create(output);
                IConversion conversion = await FFmpeg.Conversions.FromSnippet.ToMp4(Resources.MkvWithAudio, output);

                queue.Add(conversion);
            }

            var resetEvent = new AutoResetEvent(false);

            queue.OnException += (number, count, conversion) =>
            {
                totalItemsCount   = count;
                currentItemNumber = number;
                if (number == count)
                {
                    resetEvent.Set();
                }
            };
            queue.Start();
            Assert.True(resetEvent.WaitOne(10000));
            Assert.Equal(totalItemsCount, currentItemNumber);
        }
Exemplo n.º 4
0
        public async Task QueueExceptionTest()
        {
            var queue            = new ConversionQueue();
            var exceptionOccures = false;

            for (var i = 0; i < 2; i++)
            {
                string output = Path.Combine(Path.GetTempPath(), Guid.NewGuid() + FileExtensions.Mp4);
                File.Create(output);
                IConversion conversion = await FFmpeg.Conversions.FromSnippet.ToMp4(Resources.MkvWithAudio, output);

                queue.Add(conversion);
            }

            var resetEvent = new AutoResetEvent(false);

            queue.OnException += (number, count, conversion) =>
            {
                exceptionOccures = true;
                resetEvent.Set();
            };
            queue.Start();
            Assert.True(resetEvent.WaitOne(2000));
            Assert.True(exceptionOccures);
        }
Exemplo n.º 5
0
        // Methods
        public void Push(DocumentInfo document)
        {
            if (ConversionQueue.All(x => x.Name != document.Name))
            {
                ConversionQueue.Enqueue(document);
            }

            if (ConversionThread == null || !ConversionThread.IsAlive)
            {
                ConversionThread = new Thread(Convert);
                ConversionThread.Start();
            }
        }
Exemplo n.º 6
0
        public void QueueTest(bool parallel)
        {
            var queue = new ConversionQueue(parallel);

            for (var i = 0; i < 2; i++)
            {
                string      output     = Path.Combine(Path.GetTempPath(), Guid.NewGuid() + Extensions.Mp4);
                IConversion conversion = ConversionHelper.ToTs(Resources.Mp4, output);
                queue.Add(conversion);
            }

            queue.Start();
            var resetEvent = new AutoResetEvent(false);

            queue.OnConverted += (number, count, conversion) => Queue_OnConverted(number, count, conversion, resetEvent);
            queue.OnException += (number, count, conversion) =>
            {
                resetEvent.Set();
                throw new Exception();
            };
            Assert.True(resetEvent.WaitOne(60000));
        }
        public IEnumerable <string> Liste()
        {
            string inputVideoPath = Path.Combine(System.Environment.CurrentDirectory, "Temp", "erhan.mp4");

            IMediaInfo mediaInfo = new MediaInfo(inputVideoPath);
            string     output    = $"Video fullName -> {mediaInfo.FileInfo.FullName}";

            string outputPathWebm  = Path.ChangeExtension(mediaInfo.FileInfo.FullName, ".webm");
            string output1PathWebm = Path.ChangeExtension(mediaInfo.FileInfo.FullName, "1.webm");


            var lst = new List <string>();

            lst.Add(outputPathWebm);
            lst.Add(output1PathWebm);


            var queue = new ConversionQueue(parallel: false);

            for (int i = 0; i < lst.Count(); i++)
            {
                var         currentItem = lst[i];
                IConversion con         = new Conversion().SetInput(inputVideoPath).SetOutput(currentItem);
                con.OnProgress += async(duration, totalLength) =>
                {
                    var percent = (int)(Math.Round(duration.TotalSeconds / totalLength.TotalSeconds, 2) * 100);
                    //_logger.LogInformation($"[{e.Duration} / {e.TotalLength}] {percent}%");
                    await _notificationsMessageHandler.SendMessageToAllAsync($"[{duration} / {totalLength}] {percent}%");
                };
                string message = string.Empty;
                queue.OnException += async(number, count, conversion) =>
                {
                    //System.Console.Out.WriteLine($"Exception when converting file {number}/{count}");
                    message = $"Exception when converting file {number}/{count}";
                    await _notificationsMessageHandler.SendMessageToAllAsync(message);
                };

                queue.OnConverted += async(number, count, conversion) =>
                {
                    //System.Console.Out.WriteLine($"File {number}/{count} converted into {conversion.OutputFilePath}");
                    message = $"File {number}/{count} converted into {conversion.OutputFilePath}";
                    await _notificationsMessageHandler.SendMessageToAllAsync(message);
                };
                queue.Add(con);
            }

            /*
             * IConversion conversion1 = new Conversion().SetInput(inputVideoPath).SetOutput(outputPathWebm);
             * IConversion conversion2 = new Conversion().SetInput(inputVideoPath).AddParameter($"-c:v libvpx-vp9 -crf 30 -b:v 0").SetOutput(output1PathWebm);
             *
             *
             * conversion1.OnProgress += async (duration, totalLength) =>
             * {
             *  var percent = (int)(Math.Round(duration.TotalSeconds / totalLength.TotalSeconds, 2) * 100);
             *  //_logger.LogInformation($"[{e.Duration} / {e.TotalLength}] {percent}%");
             *  await _notificationsMessageHandler.SendMessageToAllAsync($"[{duration} / {totalLength}] {percent}%");
             * };
             *
             * conversion2.OnProgress += async (duration, totalLength) =>
             * {
             *  var percent = (int)(Math.Round(duration.TotalSeconds / totalLength.TotalSeconds, 2) * 100);
             *  //_logger.LogInformation($"[{e.Duration} / {e.TotalLength}] {percent}%");
             *  await _notificationsMessageHandler.SendMessageToAllAsync($"[{duration} / {totalLength}] {percent}%");
             * };
             *
             * string message = string.Empty;
             * queue.OnException += async (number, count, conversion) =>
             * {
             *  //System.Console.Out.WriteLine($"Exception when converting file {number}/{count}");
             *  message = $"Exception when converting file {number}/{count}";
             *  await _notificationsMessageHandler.SendMessageToAllAsync(message);
             * };
             *
             * queue.OnConverted += async (number, count, conversion) =>
             * {
             *  //System.Console.Out.WriteLine($"File {number}/{count} converted into {conversion.OutputFilePath}");
             *  message = $"File {number}/{count} converted into {conversion.OutputFilePath}";
             *  await _notificationsMessageHandler.SendMessageToAllAsync(message);
             * };
             * queue.Add(conversion1);
             * queue.Add(conversion2);
             */
            queue.Start();

            return(new string[] { "Result", mediaInfo.Properties.AudioFormat,
                                  mediaInfo.Properties.VideoFormat,
                                  mediaInfo.FileInfo.FullName,
                                  mediaInfo.FileInfo.Directory.FullName,
                                  mediaInfo.FileInfo.Length.ToString(),
                                  mediaInfo.Properties.Duration.Minutes.ToString(), queue.ToString() });
        }
Exemplo n.º 8
0
        protected override void BeginProcessing()
        {
            var    videoSourcePath         = SessionState.Path.GetResolvedPSPathFromPSPath(VideoSourceDirectory)?[0].Path;
            string subtitleVideoSourcePath = "";
            string subtitleSourcePath      = "";
            bool   isUseSubtitle           = string.IsNullOrEmpty(SubtitleSourceDirectory);
            bool   isUseSubtitleVideo      = string.IsNullOrEmpty(SubtitleVideoSourceDirectory);

            if (isUseSubtitle)
            {
                subtitleSourcePath = SessionState.Path.GetResolvedPSPathFromPSPath(SubtitleSourceDirectory)?[0].Path;
            }

            if (isUseSubtitleVideo)
            {
                subtitleVideoSourcePath = SessionState.Path.GetResolvedPSPathFromPSPath(SubtitleVideoSourceDirectory)?[0].Path;
            }

            var videoFileInfos = (new DirectoryInfo(videoSourcePath))
                                 .GetFiles()
                                 .Where(fi => string.IsNullOrWhiteSpace(VideoSourcePattern)
                    ? Regex.IsMatch(fi.Extension, "mp4|mkv|avi|ts|mov|vob", RegexOptions.IgnoreCase)
                    : Regex.IsMatch(fi.Name, videoSourcePath))
                                 .ToArray();

            FileInfo[] subtitleFileInfos      = null;
            FileInfo[] subtitleVideoFileInfos = null;

            if (isUseSubtitle)
            {
                subtitleFileInfos = (new DirectoryInfo(subtitleSourcePath))
                                    .GetFiles()
                                    .Where(fi => string.IsNullOrWhiteSpace(subtitleSourcePath)
                        ? Regex.IsMatch(fi.Extension, "ass|ssa|srt|sub|sup", RegexOptions.IgnoreCase)
                        : Regex.IsMatch(fi.Name, subtitleSourcePath))
                                    .ToArray();
            }

            if (isUseSubtitleVideo)
            {
                subtitleVideoFileInfos = (new DirectoryInfo(videoSourcePath))
                                         .GetFiles()
                                         .Where(fi => string.IsNullOrWhiteSpace(VideoSourcePattern)
                        ? Regex.IsMatch(fi.Extension, "mp4|mkv|avi|ts|mov|vob", RegexOptions.IgnoreCase)
                        : Regex.IsMatch(fi.Name, videoSourcePath))
                                         .ToArray();
            }

            if (!(isUseSubtitle
                ? isUseSubtitleVideo
                    ? subtitleVideoFileInfos.Length == videoFileInfos.Length && subtitleFileInfos.Length == videoFileInfos.Length
                    : subtitleFileInfos.Length == videoFileInfos.Length
                : subtitleFileInfos.Length == videoFileInfos.Length))
            {
                WriteError(new ErrorRecord(new ItemNotFoundException("Subtitle or SubtitleVideo number not match video number."), "0", ErrorCategory.ResourceUnavailable, videoFileInfos));
                return;
            }

            //extract ass
            if (isUseSubtitleVideo && !isUseSubtitle)
            {
                ConversionQueue queue = new ConversionQueue(false);
                for (int i = 0; i < subtitleVideoFileInfos.Length; i++)
                {
                    var mediainfo = MediaInfo.Get(subtitleVideoFileInfos[i]).GetAwaiter().GetResult();
                    if (mediainfo.SubtitleStreams.Count() <= 0)
                    {
                        WriteError(new ErrorRecord(new ItemNotFoundException("Cannot found subtitle in video file."), "0", ErrorCategory.ResourceUnavailable, subtitleVideoFileInfos));
                        return;
                    }
                    queue.Add(new Conversion()
                              .AddStream(mediainfo.SubtitleStreams.First())
                              .SetOutput(SessionState.Path.GetUnresolvedProviderPathFromPSPath(subtitleVideoFileInfos[i].Name + ".PSRemux.ass")));
                }
                queue.OnConverted += (c, t, d) => WriteProgress(new ProgressRecord(1, "Extracting Subtitle", "")
                {
                    PercentComplete = (int)((float)c / t * 100)
                });
                queue.Start();
                isUseSubtitle     = true;
                subtitleFileInfos = (new DirectoryInfo(subtitleVideoSourcePath))
                                    .GetFiles()
                                    .Where(fi => Regex.IsMatch(fi.Name, @"\.PSRemux\.ass", RegexOptions.IgnoreCase))
                                    .ToArray();
            }

            //use sushi to currect timeline
            if (isUseSubtitle && isUseSubtitleVideo)
            {
                for (int i = 0; i < subtitleVideoFileInfos.Length; i++)
                {
                    Process sushiProcess = new Process();
                    sushiProcess.StartInfo = new ProcessStartInfo()
                    {
                        FileName        = "sushi",
                        Arguments       = $"--script {subtitleFileInfos[i].FullName} --src {subtitleVideoFileInfos[i].FullName} --dst {videoFileInfos[i].FullName} -o {videoFileInfos[i].Name}.PSRemuxSushi.ass",
                        UseShellExecute = false,
                        CreateNoWindow  = true
                    };
                    sushiProcess.Start();
                    sushiProcess.WaitForExit();
                    WriteProgress(new ProgressRecord(1, "Extracting Subtitle", "")
                    {
                        PercentComplete = (int)((float)i / subtitleVideoFileInfos.Length * 100)
                    });
                }
                foreach (var item in subtitleFileInfos)
                {
                    item.Delete();
                }
                subtitleFileInfos = (new DirectoryInfo(subtitleVideoSourcePath))
                                    .GetFiles()
                                    .Where(fi => Regex.IsMatch(fi.Name, @"\.PSRemuxSushi\.ass", RegexOptions.IgnoreCase))
                                    .ToArray();
            }

            //remux to mkv
            for (int i = 0; i < subtitleVideoFileInfos.Length; i++)
            {
                Process mkvmergeProcess = new Process();
                mkvmergeProcess.StartInfo = new ProcessStartInfo()
                {
                    FileName        = "mkvmerge",
                    Arguments       = $"-o \"{SessionState.Path.GetUnresolvedProviderPathFromPSPath(OutputPath + "\\" + videoFileInfos[i].Name)}\" --track-name 0:\"{OutputVideoTrackTitle}\" \"{videoFileInfos[i].FullName}\" --track-name 0:\"{OutputSubtitleTrackTitle}\" \"{subtitleFileInfos[i].FullName}\"",
                    UseShellExecute = false,
                    CreateNoWindow  = true
                };
                mkvmergeProcess.Start();
                mkvmergeProcess.WaitForExit();
            }
            subtitleFileInfos.Where(fi => Regex.IsMatch(fi.Name, @"\.PSRemuxSushi\.ass", RegexOptions.IgnoreCase)).ToList().ForEach(fi => fi.Delete());
        }