private static decimal GetDurationOfMediaFile(string filePath)
        {
            var inputFile = new MediaFile {Filename = filePath};

            using (var engine = new Engine())
                engine.GetMetadata(inputFile);

            var durationOfMediaFile = inputFile.Metadata.Duration.TotalMilliseconds;

            return Convert.ToDecimal(durationOfMediaFile);
        }
Ejemplo n.º 2
0
        internal static string Serialize(Engine.EngineParameters engineParameters)
        {
            switch (engineParameters.Task)
            {
                case Engine.FFmpegTask.Convert:
                    return Convert(engineParameters.InputFile, engineParameters.OutputFile, engineParameters.ConversionOptions);

                case Engine.FFmpegTask.GetMetaData:
                    return GetMetadata(engineParameters.InputFile);

                case Engine.FFmpegTask.GetThumbnail:
                    return GetThumbnail(engineParameters.InputFile, engineParameters.OutputFile, engineParameters.ConversionOptions);
            }
            return null;
        }
Ejemplo n.º 3
0
        private void OpenVideoFile(string filepath)
        {
            // read data from this file
            var mediafile = new MediaFile(filepath);

            using (var engine = new Engine())
                engine.GetMetadata(mediafile);

            selVideoRange.RangeValue2 = selVideoRange.FrameMax = (int)(mediafile.Metadata.VideoData.Fps * mediafile.Metadata.Duration.TotalSeconds);
            selVideoRange.RangeValue1 = 0;
            VideoFilePath = filepath;
            VideoDuration = TimeSpan.FromSeconds(mediafile.Metadata.Duration.TotalSeconds);

            // and load it in the player
            vlcVideoPlayer.Play(new FileInfo(filepath));
        }
Ejemplo n.º 4
0
        public static void ExtractFrame(string file, int momentFromStartInSeconds, string output)
        {
            var inputFile = new MediaFile { Filename = file };
            var outputFile = new MediaFile { Filename = output };

            using (var engine = new Engine())
            {
                engine.GetMetadata(inputFile);
                var options = new ConversionOptions { Seek = TimeSpan.FromSeconds(momentFromStartInSeconds) };
                try
                {
                    engine.GetThumbnail(inputFile, outputFile, options);
                }
                catch(Exception ex)
                {
                    Console.WriteLine("Failed to extract the image from: {0} because of {1}", inputFile, ex.ToString());
                }
            }
        }
Ejemplo n.º 5
0
        private void CreateImageButton_Click(object sender, RoutedEventArgs e)
        {
            _imageExt.ToBitmapImage(Screen);

            ImageItem.Source = _imageExt.GetImageSource();

            var time = Screen.Position;

            var foo = new MediaFile {Filename = "Hist.bmp"};

            if (File.Exists("Hist.bmp"))
            {
                File.Delete("Hist.bmp");
            }

            using (var engine = new Engine())
            {
                engine.GetMetadata(inputFile);

                var options = new ConversionOptions {Seek = TimeSpan.FromMilliseconds(time.Milliseconds)};
                engine.GetThumbnail(inputFile, foo, options);
            }
        }
        public StdResult<TimeSpan> GetVideoLength()
        {
            using (var engine = new Engine())
            {
                engine.GetMetadata(InputFile);
            }

            return StdResult<TimeSpan>.OkResultInstance(InputFile.Metadata.Duration);
        }
        public StdResult<double> GetVideoFrameRate()
        {
            using (var engine = new Engine())
            {
                engine.GetMetadata(InputFile);
            }

            return StdResult<double>.OkResultInstance(InputFile.Metadata.VideoData.Fps);
        }
        public StdResult<string> CreateThumbnail(string forceOutputFilePath = null, TimeSpan? forceTimeSpan = null)
        {
            var outputFile = new MediaFile { Filename = OutputImagePath };

            using (var engine = new Engine())
            {
                engine.GetMetadata(InputFile);

                // Saves the frame located on the 15th second of the video.
                var options = new ConversionOptions { Seek = TimeSpan.FromSeconds(15) };
                engine.GetThumbnail(InputFile, outputFile, options);
            }
            return StdResult<string>.OkResultInstance(OutputImagePath);
        }
Ejemplo n.º 9
0
        void bw_DoWork(object sender, DoWorkEventArgs e)
        {
            var options = new MediaToolkit.Options.ConversionOptions();
            var inputFiled = new MediaFile { Filename = VideoToTrim };
            var outputFile = new MediaFile { Filename = VideoToTrimTo };

            string video2trim = "\"" + VideoToTrim + "\"";
            string video2trim2 = "\"" + VideoToTrimTo + "\"";
            using (var engine = new Engine())
            {
                engine.GetMetadata(inputFiled);
                options.CutMedia(Start, End);
                //fade=in:0:30
                engine.ConvertProgressEvent += ConvertProgressEvent;
                engine.ConversionCompleteEvent += engine_ConversionCompleteEvent;
                engine.Convert(inputFiled, outputFile, options);

                //ffmpeg -i input.mp4 -filter:v 'fade=in:0:50' \ -c:v libx264 -crf 22 -preset veryfast -c:a copy output.mp4
                //engine.CustomCommand("-ss " + Start + " -t " + End + " -i " + video2trim + " " + "\"" + " fade=in:0:03" + "\"" +  " " + video2trim2);
                //engine.CustomCommand("-ss " + Start + " -t " + End + " -i" + " " + video2trim + " -filter:v" + " fade=in=0:130 " + "-c:v libx264 -crf 22 -preset veryfast -c:a copy " + video2trim2);
                //std trim
               // string startTime = Start.Hours + ":" + Start.m
                //engine.CustomCommand("-ss " + Start. + " -t " + End + " -i " + video2trim + " -acodec copy -vcodec copy " + video2trim2);
            }
        }
Ejemplo n.º 10
0
        private void downloadTheme(string[] manifest)
        {
            try
            {
                string[] fileMetaData = manifest.Skip(1).ToArray();
                BaseUpdateRegion updateRegion = BaseUpdateRegion.GetUpdateRegion(Client.UpdateRegion);

                if (!Directory.Exists(Path.Combine(Client.ExecutingDirectory, "Assets", "themes")))
                    Directory.CreateDirectory(Path.Combine(Client.ExecutingDirectory, "Assets", "themes"));

                foreach (string s in fileMetaData)
                {
                    if (string.IsNullOrEmpty(s))
                        continue;

                    string location = s.Split(',')[0];
                    string savePlace = location.Split(new[] { "/files/" }, StringSplitOptions.None)[1];
                    if (savePlace.Contains("theme.properties"))
                    {
                        using (var newClient = new WebClient())
                        {
                            LogTextBox("Checking Theme...");
                            newClient.DownloadFile(updateRegion.BaseLink + location,
                                Path.Combine(Client.ExecutingDirectory, "Assets", "themes", "theme.properties"));
                        }
                    }
                }

                if (!File.Exists(Path.Combine(Client.ExecutingDirectory, "Assets", "themes", "theme.properties")))
                    return;

                string[] file =
                    File.ReadAllLines(Path.Combine(Client.ExecutingDirectory, "Assets", "themes", "theme.properties"));
                string theme = "";

                foreach (string s in file)
                    if (s.StartsWith("themeConfig="))
                        theme = s.Split('=')[1].Split(',')[0];

                if (theme == "")
                    return;

                if (!Directory.Exists(Path.Combine(Client.ExecutingDirectory, "Assets", "themes", theme)))
                    Directory.CreateDirectory(Path.Combine(Client.ExecutingDirectory, "Assets", "themes", theme));
                else
                {
                    Client.Theme = theme;
                    return;
                }

                List<string> themeLink = fileMetaData.Where(
                                   line => (line.Contains("loop") || line.Contains("Loop")) &&
                                       line.Contains(theme)).ToList(); //loop is exacly the same as intro
                themeLink = themeLink.Select(link => link.Split(',')[0]).ToList();

                using (var newClient = new WebClient())
                {
                    foreach (var item in themeLink)
                    {
                        string fileName = item.Split('/').Last();
                        LogTextBox("Downloading " + fileName + " from http://l3cdn.riotgames.com");
                        newClient.DownloadFile(updateRegion.BaseLink + item,
                            Path.Combine(Client.ExecutingDirectory, "Assets", "themes", theme, fileName));

                    }
                }
                string[] flv = Directory.GetFiles(
                    Path.Combine(Client.ExecutingDirectory, "Assets", "themes", theme), "*.flv");

                foreach(var item in flv)
                {
                    var inputFile = new MediaFile { Filename = 
                        Path.Combine(Client.ExecutingDirectory, "Assets", "themes", theme, item) };
                    var outputFile = new MediaFile { Filename = 
                        Path.Combine(Client.ExecutingDirectory, "Assets", "themes", theme, item).Replace(".flv", ".mp4") };

                    using (var engine = new Engine())
                    {
                        engine.Convert(inputFile, outputFile);
                    }

                }
                Client.Theme = theme;
            }
            catch
            {
            }
        }
        private async Task DownloadTheme(PatcherFile[] files)
        {
            try
            {
                if (!Directory.Exists(GetAssetsDirectory("themes")))
                    Directory.CreateDirectory(GetAssetsDirectory("themes"));

                using (var wc = new WebClient())
                {
                    LogTextBox("Updating Theme");
                    await wc.DownloadFileTaskAsync(files.First(f => f.RelativePath.Contains("theme.properties")).AbsolutePath, GetAssetsDirectory("themes", "theme.properties"));
                }

                if (!File.Exists(GetAssetsDirectory("themes", "theme.properties")))
                    throw new Exception("Downloading of the file \"theme.properties\" failed");

                var theme = File.ReadAllLines(GetAssetsDirectory("themes", "theme.properties")).First(s => s.StartsWith("themeConfig=")).Split('=')[1].Split(',')[0];
                if (theme == "")
                    return;

                if (!Directory.Exists(GetAssetsDirectory("themes", theme)))
                    Directory.CreateDirectory(GetAssetsDirectory("themes", theme));
                else if (Directory.GetFiles(GetAssetsDirectory("themes", theme)).Any())
                {
                    Client.Theme = theme;
                    return;
                }

                var themePatcherFiles = files.Where(l => l.RelativePath.ToLower().Contains("loop") && l.RelativePath.Contains(theme)).ToList();
                Parallel.ForEach(themePatcherFiles,
                    new ParallelOptions {MaxDegreeOfParallelism = 10},
                    file =>
                    {
                        LogTextBox(String.Format("Downloading {0} ({1} KB) from http://l3cdn.riotgames.com", Path.GetFileName(file.RelativePath), file.FileSize/1024));
                        var fname = Path.GetFileName(file.RelativePath);
                        var localPath = GetAssetsDirectory("themes", theme, fname);
                        new WebClient().DownloadFile(file.AbsolutePath, localPath);
                    });

                var flv = Directory.GetFiles(GetAssetsDirectory("themes", theme), "*.flv");

                foreach (var item in flv)
                {
                    var inputFile = new MediaFile {Filename = GetAssetsDirectory("themes", theme, item)};

                    var outputFile = new MediaFile {Filename = GetAssetsDirectory("themes", theme, item).Replace(".flv", ".mp4")};

                    LogTextBox(String.Format("Converting {0}", Path.GetFileName(item)));
                    await Task.Run(() =>
                    {
                        using (var engine = new Engine())
                            engine.Convert(inputFile, outputFile);
                    });
                }
                Client.Theme = theme;
            }
            catch (Exception ex)
            {
                Client.Log(ex);
            }
        }
Ejemplo n.º 12
0
        protected virtual void Convert(String inputFilepath,String outputFolder, ConversionOptions conversionOptions, bool convertToAudio)
        {
            if(String.IsNullOrWhiteSpace(FileName))
                FileName = Path.GetFileNameWithoutExtension(inputFilepath) + GetFormat(true);

            string outputFilePath = Path.Combine(outputFolder, FileName);
            MediaFile inputFile = new MediaFile(@inputFilepath);
            MediaFile outputFile = new MediaFile(outputFilePath);
            using (var engine = new Engine())
            {
                if (processStartingEventHandler != null)
                    processStartingEventHandler(this, EventArgs.Empty);
                engine.Convert(inputFile, outputFile);
                if (processCompletionEventHandler != null)
                    processCompletionEventHandler(this, EventArgs.Empty);

            }
        }
        private async Task ExtractAudio(string path) {
            var cache = new FileInfo(context.audioSaveableFilename); //target cache
            var SavePath = context.audioSaveableFilename;//to universal string
            for (int i = 1; File.Exists(SavePath); i++) {
                SavePath = Path.Combine(cache.Directory.FullName, $"{cache.Name.Replace(cache.Extension,"")} ({i}){cache.Extension}");
            }
            context.AudioPath = new FileInfo(SavePath);
            switch (context.VideoInfo.VideoType) {
                case VideoType.Mobile:
                    break;
                case VideoType.Flash:
                    using (var flvFile = new FlvFile(path, SavePath)) {
                        flvFile.ConversionProgressChanged += (sender, args) => {
                            context.OnProgresStateChanged(YoutubeStage.ExtractingAudio, args.ProgressPercentage);
                        };

                        await Task.Run(()=>flvFile.ExtractStreams());
                    }
                    break;
                case VideoType.Mp4:
                    var @in = new MediaFile(path);
                    var @out = new MediaFile(SavePath);
                    using (var engine = new Engine()) {
                        //Desperate attempt to catch the extraction from the MediaToolkit lib but it simply does not pass into those events.
                        //engine.ConvertProgressEvent += (sender, args) => AudioExtractionProgressChanged?.Invoke(this, new ProgressEventArgs((args.ProcessedDuration.TotalMilliseconds / args.TotalDuration.TotalMilliseconds) * 100f));
                        //engine.ConversionCompleteEvent += (sender, args) => AudioExtractionProgressChanged?.Invoke(this, new ProgressEventArgs((args.ProcessedDuration.TotalMilliseconds / args.TotalDuration.TotalMilliseconds) * 100f));
                        //informing on 0% and 100%, btw those conversions are pretty fast, 5 to 10 seconds for a 50MB 1048p video.
                        context.OnProgresStateChanged(YoutubeStage.StartingAudioExtraction);
                        await Task.Run(()=>engine.Convert(@in, @out)); //begin conversion progress. it is executed serially.
                        context.OnProgresStateChanged(YoutubeStage.FinishedAudioExtraction);
                    }
                    break;
                case VideoType.WebM:
                    break;
                case VideoType.Unknown:
                    break;
                default:
                    throw new ArgumentOutOfRangeException();
            }
        }
Ejemplo n.º 14
0
        public static void IntroVideoss(string VideoFile)
        {
            // this.FileName = VideoFile;

            var inputFile = new MediaFile { Filename = VideoFile };
            var outputFile = new MediaFile {Filename = @"Z:\ddd.mp4"};
            var inputFiles = new MediaToolkit.Options.ConversionOptions();

            var engine = new MediaToolkit.Engine();

            TimeSpan t = new TimeSpan(0, 0, 2, 10, 49);
            TimeSpan d = new TimeSpan(0, 0, inputFile.Metadata.Duration.Minutes, inputFile.Metadata.Duration.Seconds, inputFile.Metadata.Duration.Milliseconds);
            d = inputFile.Metadata.Duration;
             d = d - t;

             inputFiles.CutMedia (t, d);
             engine.Convert(inputFile, outputFile, inputFiles);
        }
        private static void TrimFileToNewDuration(string inputFilePath, decimal newDurationInMilliseconds, TrailerClipperOptions clipperOptions)
        {
            var outputFilePath = ComputeOutputFilePath(inputFilePath, clipperOptions.OutputDirectoryPath);

            var inputFile = new MediaFile {Filename = inputFilePath};

            var outputFile = new MediaFile {Filename = outputFilePath};

            var options = InitializeClippingData(newDurationInMilliseconds, clipperOptions);

            using (var engine = new Engine())
            {
                engine.GetMetadata(inputFile);

                engine.Convert(inputFile, outputFile, options);
            }

            if (clipperOptions.OutputToConsole)
                Console.WriteLine("Finished on trimming file, output: " + outputFilePath);
        }
Ejemplo n.º 16
0
        public void GetProperties(string VideoFile)
        {
            var inputFile = new MediaFile { Filename = VideoFile };
            string GetFrameSize = string.Empty;

            try
            {
                using (var engine = new Engine())
                {
                    engine.GetMetadata(inputFile);
                    this.Format = inputFile.Metadata.VideoData.FrameSize;
                    this.FrameRate = inputFile.Metadata.VideoData.Fps;
                    engine.Dispose();
                }
            }
            catch (Exception)
            {
            }
        }
        public StdResult<List<string>> ExtractFrames(int nbFramesDesired)
        {
            DesiredFramesAmount = nbFramesDesired;
            int nbSeconds = (int)GetVideoLength().ReturnObject.TotalSeconds;
            int framePeriod = nbSeconds / (nbFramesDesired + 1);

            List<MediaFile> outputFiles = new List<MediaFile>();

            using (var engine = new Engine())
            {
                engine.GetMetadata(InputFile);

                for (int i = 0; i < DesiredFramesAmount; i++)
                {
                    outputFiles.Add(new MediaFile { Filename = string.Format(OutputSpriteFramePathTemplate, i) });
                    var options = new ConversionOptions { Seek = TimeSpan.FromSeconds((i + 1) * framePeriod), VideoSize = VideoSize._200par125 };
                    if (File.Exists(outputFiles[i].Filename))
                        File.Delete(outputFiles[i].Filename);
                    engine.GetThumbnail(InputFile, outputFiles[i], options);
                }
            }
            OutputSpriteFrames = outputFiles.Select(of => of.Filename).ToList();
            return StdResult<List<string>>.OkResultInstance(OutputSpriteFrames);
        }
Ejemplo n.º 18
0
 public void genThumb()
 {
     thumbPath = System.IO.Path.Combine( System.IO.Path.GetTempPath(), cutName+index.ToString()+".jpg");
     var inputFile = new MediaFile { Filename = sourcePath };
     var outputFile = new MediaFile { Filename = thumbPath };
     using (var engine = new Engine())
     {
         engine.GetMetadata(inputFile);
         var options = new ConversionOptions { Seek = startTime };
         engine.GetThumbnail(inputFile, outputFile, options);
     }
     var img = System.Drawing.Image.FromFile(thumbPath);
     MemoryStream ms = new MemoryStream();
     img.Save(ms, System.Drawing.Imaging.ImageFormat.Jpeg);
     imgThumb = ms.ToArray();
 }
        private async Task ExtractAudio(string path) {
            var cache = new FileInfo(context.AudioPath?.FullName ?? context.AudioSaveableFilename); //target cache
            var SavePath = context.AudioPath?.FullName ?? context.AudioSaveableFilename;//to universal string
            for (int i = 1; File.Exists(SavePath); i++) {
                SavePath = Path.Combine(cache.Directory.FullName, $"{cache.Name.Replace(cache.Extension,"")} ({i}){cache.Extension}");
            }
            SavePath = Path.ChangeExtension(SavePath, "aac");
            context.OnProgresStateChanged(YoutubeStage.StartingAudioExtraction);
            switch (context.VideoInfo.VideoType) {
                case VideoType.Mobile:
                    //no one is really going to use this..
                    break;
                case VideoType.Flash: {
                    using (var flvFile = new FlvFile(path, SavePath)) {
                        flvFile.ConversionProgressChanged += (sender, args) => {
                            context.OnProgresStateChanged(YoutubeStage.ExtractingAudio, args.ProgressPercentage);
                        };

                        await Task.Run(() => flvFile.ExtractStreams());
                    }
                    break;
                }
                case VideoType.Mp4: {
                    var @in = new MediaFile(new FileInfo(path).FullName);
                    var @out = new MediaFile(new FileInfo(SavePath).FullName);
                    using (var engine = new Engine()) {
                        //Desperate attempt to catch the extraction from the MediaToolkit lib but it simply does not pass into those events.
                        //engine.ConvertProgressEvent += (sender, args) => AudioExtractionProgressChanged?.Invoke(this, new ProgressEventArgs((args.ProcessedDuration.TotalMilliseconds / args.TotalDuration.TotalMilliseconds) * 100f));
                        //engine.ConversionCompleteEvent += (sender, args) => AudioExtractionProgressChanged?.Invoke(this, new ProgressEventArgs((args.ProcessedDuration.TotalMilliseconds / args.TotalDuration.TotalMilliseconds) * 100f));
                        //informing on 0% and 100%, btw those conversions are pretty fast, 5 to 10 seconds for a 50MB 1048p video.
                        await Task.Run(()=> engine.CustomCommand($"-i \"{@in.Filename.Replace("\\", "/")}\" -vn -acodec copy \"{@out.Filename.Replace("\\", "/")}\"")); //begin conversion progress. it is executed serially.
                    }
                    break;
                }
                case VideoType.WebM:
                    //the mkv files do not contain any audio files.
                    break;
                case VideoType.Unknown:
                    switch (context.VideoInfo?.AudioType ?? AudioType.None) {
                        case AudioType.Unknown:
                            break;
                        case AudioType.Aac:
                            File.Move(path, SavePath);
                            break;
                        case AudioType.Mp3:
                            SavePath = Path.ChangeExtension(SavePath, "mp3");
                            File.Move(path, SavePath);
                            break;
                        case AudioType.Vorbis: {
                            var @in = new MediaFile(new FileInfo(path).FullName);
                            var @out = new MediaFile(new FileInfo(SavePath).FullName);
                            using (var engine = new Engine()) {
                                await Task.Run(() => engine.Convert(@in, @out));
                            }
                            break;
                        }
                        case AudioType.Opus: {
                            var @in = new MediaFile(new FileInfo(path).FullName);
                            var @out = new MediaFile(new FileInfo(SavePath).FullName);
                            using (var engine = new Engine()) {
                                await Task.Run(()=> engine.CustomCommand($"-i {@in.Filename.Replace("\\","/")} -c:a libvo_aacenc -b:a 192k  {@out.Filename.Replace("\\","/")}"));
                            }
                            break;
                        }
                        default:
                            break;
                    }
                    break;
                default:
                    SavePath = Path.ChangeExtension(SavePath, cache.Extension.Replace(".",""));
                    File.Move(path, SavePath);
                    break;
            }
            context.OnProgresStateChanged(YoutubeStage.FinishedAudioExtraction);
            context.AudioPath = new FileInfo(SavePath);
        }
Ejemplo n.º 20
-1
        public IEnumerable<MediaSegment> Segment(FileInfo file, long fileId)
        {
            var source = new MediaFile(file.FullName);
            using (var engine = new Engine())
            {
                engine.GetMetadata(source);
                var progressMs = 0.0;
                while (progressMs < source.Metadata.Duration.TotalMilliseconds)
                {
                    var options = new ConversionOptions();
                    var endMs = Math.Min(progressMs + _segmentLengthMs, source.Metadata.Duration.TotalMilliseconds);

                    options.CutMedia(TimeSpan.FromMilliseconds(progressMs),
                        TimeSpan.FromMilliseconds(endMs));

                    var outputFile = Path.Combine(file.DirectoryName,
                        string.Format("{0}_audio_{1}ms.wav", file.Name, progressMs));

                    engine.Convert(source, new MediaFile(outputFile), options);
                    yield return new MediaSegment
                    {
                        FileId = fileId,
                        File = new FileInfo(outputFile),
                        OffsetMs = progressMs,
                        DurationMs = endMs - progressMs
                    };
                    progressMs = endMs;
                }
            }
        }