예제 #1
0
        public async Task ChangeBitrate(int expectedBitrate)
        {
            IMediaInfo inputFile = await MediaInfo.Get(Resources.Mp3).ConfigureAwait(false);

            string outputPath = Path.ChangeExtension(Path.GetTempFileName(), FileExtensions.Mp3);

            var audioStream = inputFile.AudioStreams.First();
            var bitrate     = audioStream.Bitrate;

            audioStream.ChangeBitrate(expectedBitrate);

            IConversionResult conversionResult = await Conversion.New()
                                                 .AddStream(audioStream)
                                                 .SetOutput(outputPath)
                                                 .Start().ConfigureAwait(false);

            Assert.True(conversionResult.Success);
            IMediaInfo mediaInfo = await MediaInfo.Get(outputPath).ConfigureAwait(false);

            Assert.Equal(expectedBitrate, mediaInfo.AudioStreams.First().Bitrate);
            Assert.Equal("mp3", mediaInfo.AudioStreams.First().Format);
            Assert.NotEmpty(mediaInfo.AudioStreams);
        }
예제 #2
0
        public async Task WatermarkTest(Position position)
        {
            IMediaInfo inputFile = await MediaInfo.Get(Resources.MkvWithAudio);

            string       outputPath = Path.ChangeExtension(Path.GetTempFileName(), FileExtensions.Mp4);
            IVideoStream stream     = inputFile.VideoStreams.First()
                                      .SetWatermark(Resources.PngSample, position);

            IConversionResult conversionResult = await Conversion.New()
                                                 .SetPreset(ConversionPreset.UltraFast)
                                                 .AddStream(stream)
                                                 .SetOutput(outputPath)
                                                 .Start();

            Assert.True(conversionResult.Success);
            Assert.Contains("overlay", conversionResult.Arguments);
            Assert.Contains(Resources.PngSample, conversionResult.Arguments);
            IMediaInfo mediaInfo = await MediaInfo.Get(outputPath);

            Assert.Equal(TimeSpan.FromSeconds(9), mediaInfo.Duration);
            Assert.Equal("h264", mediaInfo.VideoStreams.First().Format);
            Assert.False(mediaInfo.AudioStreams.Any());
        }
예제 #3
0
        public async Task LoopTest()
        {
            IMediaInfo inputFile = await MediaInfo.Get(Resources.Mp4).ConfigureAwait(false);

            string outputPath = Path.ChangeExtension(Path.GetTempFileName(), FileExtensions.Gif);

            IConversionResult conversionResult = await Conversion.New()
                                                 .AddStream(inputFile.VideoStreams.First()
                                                            .SetLoop(1))
                                                 .SetOutput(outputPath)
                                                 .Start().ConfigureAwait(false);

            Assert.True(conversionResult.Success);
            IMediaInfo mediaInfo = await MediaInfo.Get(outputPath).ConfigureAwait(false);

            Assert.Equal(TimeSpan.FromSeconds(0), mediaInfo.Duration);
            Assert.Equal("gif", mediaInfo.VideoStreams.First().Format);
            Assert.Equal("16:9", mediaInfo.VideoStreams.First().Ratio);
            Assert.Equal(25, mediaInfo.VideoStreams.First().FrameRate);
            Assert.Equal(1280, mediaInfo.VideoStreams.First().Width);
            Assert.Equal(720, mediaInfo.VideoStreams.First().Height);
            Assert.False(mediaInfo.AudioStreams.Any());
        }
예제 #4
0
        public async Task OverwriteFilesTest()
        {
            string     output = Path.Combine(Path.GetTempPath(), Guid.NewGuid() + FileExtensions.Mp4);
            IMediaInfo info   = await FFmpeg.GetMediaInfo(Resources.MkvWithAudio);

            IAudioStream audioStream = info.AudioStreams.First()?.SetCodec(AudioCodec.ac3);

            IConversionResult conversionResult = await FFmpeg.Conversions.New()
                                                 .AddStream(audioStream)
                                                 .SetOutput(output)
                                                 .Start();


            Assert.Contains("-n ", conversionResult.Arguments);

            IConversionResult secondConversionResult = await FFmpeg.Conversions.New()
                                                       .AddStream(audioStream)
                                                       .SetOverwriteOutput(true)
                                                       .SetOutput(output)
                                                       .Start();

            Assert.Contains(" -y ", secondConversionResult.Arguments);
            Assert.DoesNotContain(" -n ", secondConversionResult.Arguments);
        }
예제 #5
0
        public async Task SetHashFormat_HashInString_CorrectLenght()
        {
            string fileExtension = FileExtensions.Txt;

            string     output = Path.Combine(Path.GetTempPath(), Guid.NewGuid() + fileExtension);
            IMediaInfo info   = await FFmpeg.GetMediaInfo(Resources.MkvWithAudio);

            IVideoStream videoStream = info.VideoStreams.First()?.SetCodec(VideoCodec.copy);
            IAudioStream audioStream = info.AudioStreams.First()?.SetCodec(AudioCodec.copy);

            IConversionResult conversionResult = await FFmpeg.Conversions.New()
                                                 .AddStream(videoStream)
                                                 .AddStream(audioStream)
                                                 .SetOutputFormat(Format.hash)
                                                 .SetHashFormat("SHA512/224")
                                                 .SetOutput(output)
                                                 .Start();


            FileInfo fi = new FileInfo(output);

            Assert.Equal(fileExtension, fi.Extension);
            Assert.Equal(68L, fi.Length);
        }
        public static async Task <BitmapSource> GenerateThumbnailFromVideo(string videoFilePath)
        {
            BitmapSource thumbnailBitmapSource = null;

            try
            {
                string thumbnailFilePath = videoFilePath.Replace(".mp4", "_thumb.jpg");
                if (File.Exists(thumbnailFilePath))
                {
                    File.Delete(thumbnailFilePath);
                }

                //Set directory where app should look for FFmpeg
                FFmpeg.ExecutablesPath =
                    @"C:\Users\udara\Downloads\ffmpeg-20190818-1965161-win64-static\ffmpeg-20190818-1965161-win64-static\bin\";

                FileInfo file      = new FileInfo(videoFilePath);
                var      mediaInfo = await MediaInfo.Get(file).ConfigureAwait(false);

                // grab a random timespan for a frame
                Random rand             = new Random();
                var    randomFrameValue = rand.Next(Convert.ToInt32(mediaInfo.Duration.TotalMilliseconds));

                IConversionResult result = await Conversion.Snapshot(videoFilePath, thumbnailFilePath,
                                                                     TimeSpan.FromMilliseconds(randomFrameValue)).Start();;

                thumbnailBitmapSource = new BitmapImage(new Uri(thumbnailFilePath));
            }
            catch (Exception ex)
            {
                // ignored
                // or handle it :)
            }

            return(thumbnailBitmapSource);
        }
예제 #7
0
        public async Task <bool> convertMp4ToMp3(string mp4FilePath, string outputFilePath)
        {
            bool success = false;

            try
            {
                IConversion conversion = Conversion.ExtractAudio(mp4FilePath, outputFilePath);
                conversion.OnProgress += (sender, args) =>
                {
                    int percent = (int)(Math.Round(args.Duration.TotalSeconds / args.TotalLength.TotalSeconds, 2) * 100);
                    indicator.updateProgress("Converting to MP3: ", percent);
                };
                IConversionResult result = await conversion.Start();

                File.Delete(mp4FilePath);
                indicator.updateProgress("Conversion Done! ", 100);
                success = true;
            }
            catch (Xabe.FFmpeg.Exceptions.ConversionException e)
            {
                MessageBox.Show("An error has occurred at: " + outputFilePath + "\n" + e.Message);
            }
            return(success);
        }
예제 #8
0
        public async Task <ResponseDTO <long> > CrawlVideosByUrlAsync(CrawlOtherVideoDTO otherVideoDTO)
        {
            var exVideo = dbContext.OtherCrawledVideos.FirstOrDefault(x => x.VideoUrl == otherVideoDTO.VideoUrl);

            if (exVideo != null)
            {
                return(new ResponseDTO <long>
                {
                    success = false,
                    data = -1,
                    responseMessage = "alrdy Crawled This video"
                });
            }
            string url = otherVideoDTO.VideoUrl;

            if (!System.IO.Directory.Exists($"{Config.OtherVideoPhysicalFilePath}/{otherVideoDTO.SiteName.Trim()}_{otherVideoDTO.Author.Trim()}"))
            {
                System.IO.Directory.CreateDirectory($"{Config.OtherVideoPhysicalFilePath}/{otherVideoDTO.SiteName.Trim()}_{otherVideoDTO.Author.Trim()}");
            }
            var ytdl = new YoutubeDL();

            // set the path of the youtube-dl and FFmpeg if they're not in PATH or current directory
            ytdl.YoutubeDLPath = $"H:/MyProjects/youtube-dl.exe";
            ytdl.FFmpegPath    = $"C:/ffmpeg/bin/ffmpeg.exe";
            // optional: set a different download folder
            ytdl.OutputFolder      = $"{Config.OtherVideoPhysicalFilePath}/{otherVideoDTO.SiteName.Trim()}_{otherVideoDTO.Author.Trim()}";
            ytdl.RestrictFilenames = true;
            // download a video
            var data = await ytdl.RunVideoDataFetch(url : url);

            string title            = data.Data.Title;
            string publishedAt      = data.Data.UploadDate.ToString();
            string author           = data.Data.Uploader;
            string description      = data.Data.Description;
            string channelId        = data.Data.ChannelID;
            string thumbnailDefault = data.Data.Thumbnail;
            double duration         = data.Data.Duration ?? 0;

            var res = await ytdl.RunVideoDownload(url : url);

            // the path of the downloaded file
            string path        = res.Data;
            var    splitedPath = path.Split("\\");
            string folder      = $"{otherVideoDTO.SiteName.Trim()}_{otherVideoDTO.Author.Trim()}";
            string fileName    = splitedPath[splitedPath.Length - 1];
            string fullPath    = $"{otherVideoDTO.SiteName.Trim()}_{otherVideoDTO.Author.Trim()}/{fileName}";

            string timeStr = DateTime.UtcNow.ToString("MMddHHmmss");

            string newFileName = otherVideoDTO.TagString.Trim() + "_" + timeStr + fileName;
            string newFullPath = $"{folder}/{newFileName}";

            System.IO.File.Move($"{Config.OtherVideoPhysicalFilePath}/{fullPath}", $"{Config.OtherVideoPhysicalFilePath}/{newFullPath}");

            if (duration < 1)
            {
                var mediaInfo = await FFmpeg.GetMediaInfo($"{Config.OtherVideoPhysicalFilePath}/{newFullPath}");

                duration = mediaInfo.VideoStreams.First().Duration.TotalSeconds;
            }
            string      thumbnailOutputPath = $"{Config.OtherVideoPhysicalFilePath}/{newFullPath}_thumbnail.png";
            string      thumbnailPath       = $"{newFullPath}_thumbnail.png";
            IConversion conversion          = await FFmpeg.Conversions.FromSnippet.Snapshot($"{Config.OtherVideoPhysicalFilePath}/{newFullPath}"
                                                                                            , thumbnailOutputPath, TimeSpan.FromSeconds(duration / 2));

            IConversionResult result = await conversion.Start();

            OtherCrawledVideos otherCrawledVideos = new OtherCrawledVideos
            {
                Author    = otherVideoDTO.Author.Trim(),
                FileName  = newFileName,
                FullPath  = newFullPath,
                Path      = folder,
                Type      = otherVideoDTO.Type,
                SiteName  = otherVideoDTO.SiteName.Trim(),
                TagString = otherVideoDTO.TagString.Trim(),
                Title     = title ?? newFileName,
                VideoUrl  = otherVideoDTO.VideoUrl,
                Thumbnail = thumbnailPath,
                order     = dbContext.OtherCrawledVideos.DefaultIfEmpty().Max(x => x == null ? 0 : x.order) + 1
            };

            await dbContext.OtherCrawledVideos.AddAsync(otherCrawledVideos);

            await dbContext.SaveChangesAsync();

            return(new ResponseDTO <long> {
                success = true, data = otherCrawledVideos.Id
            });
        }
 public async Task GeneratePreviewVideo(string videoDirectory, string videoName, string extension)
 {
     IConversionResult result = await Conversion.Snapshot(Path.Combine(videoDirectory, videoName + extension), Path.Combine(videoDirectory, videoName + "_preview.png"), TimeSpan.FromSeconds(0))
                                .Start();
 }
예제 #10
0
        private async Task ConnectAsync()
        {
            //TimeSpan delay = TimeSpan.FromSeconds(5);

            var serverUri            = new Uri("rtsp://192.168.0.103:554/videoMain");
            var credentials          = new NetworkCredential("admin", "admin");
            var connectionParameters = new ConnectionParameters(serverUri, credentials);

            connectionParameters.RtpTransport = RtpTransportProtocol.TCP;

            this.rtspClient = new RtspClient(connectionParameters);

            this.rtspClient.FrameReceived +=
                async(sender, frame) =>
            {
                FrameCounter++;
                var fileName = $"{hostingEnvironment.ContentRootPath}/frames/frame-{FrameCounter}.mp4";
                await File.WriteAllBytesAsync(fileName, frame.FrameSegment.Array);


                Func <string, string> outputFileNameBuilder = (number) => { return($"{hostingEnvironment.ContentRootPath}/images/frame-{FrameCounter}.png"); };

                IMediaInfo info = await FFmpeg.GetMediaInfo(fileName);

                IVideoStream videoStream = info.VideoStreams.First().SetCodec(VideoCodec.h264);

                IConversionResult conversionResult = await FFmpeg.Conversions.New()
                                                     .AddStream(videoStream)
                                                     .ExtractNthFrame(1, outputFileNameBuilder)
                                                     .Start();



                var img = Convert.ToBase64String(frame.FrameSegment.Array);
                for (int i = 0; i < frameChannles.Count; i++)
                {
                    var data = new StreamFrame()
                    {
                        Base64ImageString = img,
                        TimeStamp         = frame.Timestamp
                    };

                    await frameChannles[i].Writer.WriteAsync(data, cancellationTokens[i]);
                    LastFrame = DateTime.UtcNow;
                }


                if (FrameCounter > 50)
                {
                    File.Delete($"{hostingEnvironment.ContentRootPath}/frames/frame-{FrameCounter-50}.mp4");
                    FrameCounter--;
                }
                ;
            };

            //while (true)
            //{
            Console.WriteLine("Connecting...");
            await rtspClient.ConnectAsync(tokenSoruce.Token);

            Console.WriteLine("Connected.");

            var task = Task.Factory.StartNew(async() =>
            {
                await rtspClient.ReceiveAsync(tokenSoruce.Token);
            }, TaskCreationOptions.LongRunning);
        }
예제 #11
0
        public async Task <ExtractVideoDataResult> ExtractVideoDataAsync(
            string filename,
            CancellationToken cancellationToken)
        {
            Log.Information("Extract VideoData for: {Filename}", filename);

            ExtractVideoDataResult result = new ExtractVideoDataResult()
            {
                Meta = new MediaMetadata()
            };


            IMediaInfo mediaInfo = await FFmpeg.GetMediaInfo(filename, cancellationToken);

            IVideoStream?videoStream = mediaInfo.VideoStreams.FirstOrDefault();

            if (videoStream != null)
            {
                result.Info = new VideoInfo
                {
                    Bitrate   = videoStream.Bitrate,
                    Format    = videoStream.PixelFormat,
                    FrameRate = videoStream.Framerate,
                    Duration  = videoStream.Duration
                };

                result.Size = mediaInfo.Size;

                result.Meta.Dimension = new MediaDimension
                {
                    Width  = videoStream.Width,
                    Height = videoStream.Height
                };

                videoStream.SetCodec(VideoCodec.png);

                var tmpFile = Path.Combine(Path.GetTempPath(), $"{Guid.NewGuid()}.png");

                try
                {
                    IConversionResult cr = await FFmpeg.Conversions.New()
                                           .AddStream(videoStream)
                                           .ExtractNthFrame(3, (n) => tmpFile)
                                           .Start();

                    result.ImageData = await File.ReadAllBytesAsync(tmpFile, cancellationToken);

                    File.Delete(tmpFile);
                }
                catch (Exception ex)
                {
                    Console.WriteLine(ex.Message);
                }

                IReadOnlyList <MetadataEx.Directory>?meta = MetadataEx.ImageMetadataReader
                                                            .ReadMetadata(filename);

                result.Meta.DateTaken   = GetDateTaken(meta);
                result.Meta.GeoLocation = await GetGpsLocation(meta, cancellationToken);
            }

            return(result);
        }
예제 #12
0
        private void GenerateAudio(List <string> sourceFiles, uint audioId, int bitRate, bool useVbr, string prefixLocation = null)
        {
            int         channels     = 2;
            int         samplingRate = 48000;
            List <uint> chapters     = new List <uint>();

            var outFormat = new WaveFormat(samplingRate, 2);

            OpusEncoder encoder = OpusEncoder.Create(48000, 2, OpusApplication.OPUS_APPLICATION_AUDIO);

            encoder.Bitrate = bitRate;
            encoder.UseVBR  = useVbr;

            if (audioId == 0)
            {
                audioId = (uint)((DateTimeOffset)DateTime.UtcNow).ToUnixTimeSeconds();
            }

            string tempName = Path.GetTempFileName();

            using (Stream outputData = new FileStream(tempName, FileMode.OpenOrCreate))
            {
                byte[]   buffer = new byte[2880 * channels * 2];
                OpusTags tags   = new OpusTags();
                tags.Comment                   = "Lavf56.40.101";
                tags.Fields["encoder"]         = "opusenc from opus-tools 0.1.9";
                tags.Fields["encoder_options"] = "--quiet --bitrate 96 --vbr";
                tags.Fields["pad"]             = new string('0', 0x138);

                OpusOggWriteStream oggOut = new OpusOggWriteStream(encoder, outputData, tags, samplingRate, (int)audioId);

                uint lastIndex = 0;
                int  track     = 0;
                bool warned    = false;
                long maxSize   = 0x77359400;

                foreach (var sourceFile in sourceFiles)
                {
                    if ((outputData.Length + 0x1000) >= maxSize)
                    {
                        Console.WriteLine("Error: Close to 2 GiB, aborting");
                        break;
                    }

                    try
                    {
                        int bytesReturned  = 1;
                        int totalBytesRead = 0;

                        track++;
                        chapters.Add(lastIndex);

                        int    lastPct     = 0;
                        int    snipLen     = 15;
                        string displayName = new FileInfo(sourceFile).Name;
                        try
                        {
                            var tag = new Mp3(sourceFile, Mp3Permissions.Read).GetAllTags().FirstOrDefault();
                            if (tag != null && tag.Title.IsAssigned)
                            {
                                displayName = tag.Title.Value;
                            }
                        }
                        catch (Exception ex)
                        {
                        }

                        string shortName = displayName.PadRight(snipLen).Substring(0, snipLen);

                        Console.Write(" Track " + track.ToString().PadLeft(3) + " - " + shortName + "  [");


                        /* prepend a audio file for e.g. chapter number */
                        if (prefixLocation != null)
                        {
                            string prefixFile = Path.Combine(prefixLocation, track.ToString("0000") + ".mp3");

                            if (!File.Exists(prefixFile))
                            {
                                throw new FileNotFoundException("Missing prefix file '" + prefixFile + "'");
                            }

                            try
                            {
                                Stream prefixResampled = new MemoryStream();

                                // Linux
                                string prefixTmpWavFile = "";

                                if (RuntimeInformation.IsOSPlatform(OSPlatform.Linux))
                                {
                                    prefixTmpWavFile = Path.ChangeExtension(Path.GetTempFileName(), "wav");

                                    //Console.Write(" Convert file " + sourceFile + " to WAV. Temp file " + prefixTmpWavFile);

                                    // The isReady flag and error test variables are not a nice solution but is working
                                    bool   isReadyPrefix         = false;
                                    String FFmpegErrorTextPrefix = "";

                                    // Convert to WAV
                                    Task.Run(async() =>
                                    {
                                        try
                                        {
                                            // Convert to WAV and resample
                                            IMediaInfo prefixInputFile = await FFmpeg.GetMediaInfo(sourceFile);

                                            IAudioStream prefixAudioStream = prefixInputFile.AudioStreams.First()
                                                                             .SetCodec(AudioCodec.pcm_f32le)
                                                                             .SetChannels(2)
                                                                             .SetSampleRate(samplingRate);

                                            IConversionResult prefixConversionResult = await FFmpeg.Conversions.New()
                                                                                       .AddStream(prefixAudioStream)
                                                                                       .SetOutput(prefixTmpWavFile)
                                                                                       .Start();
                                        }
                                        catch (Exception e)
                                        {
                                            FFmpegErrorTextPrefix = e.Message;
                                            throw new Exception("FFmepg error " + e.Message + "\n");
                                        }

                                        isReadyPrefix = true;
                                    });

                                    while (!isReadyPrefix)
                                    {
                                        Thread.Sleep(200);
                                        if (FFmpegErrorTextPrefix != "")
                                        {
                                            throw new Exception("FFmepg error: " + FFmpegErrorTextPrefix + "\n");
                                        }
                                    }

                                    // Read WAV file
                                    byte[] prefixWavBytes = File.ReadAllBytes(prefixTmpWavFile);
                                    prefixResampled.Write(prefixWavBytes, 0, prefixWavBytes.Length);
                                    prefixResampled.Seek(0, SeekOrigin.Begin);

                                    // Skip WAV header
                                    byte[] bytes = new byte[4];
                                    prefixResampled.Seek(16, 0);
                                    prefixResampled.Read(bytes, 0, 4);
                                    int Subchunk1Size = BitConverter.ToInt32(bytes, 0); // Get FMT size

                                    // Skip some header information
                                    prefixResampled.Read(buffer, 0, Subchunk1Size + 12); // Data starts at FMT size + 12 bytes

                                    // Read data chunk
                                    prefixResampled.Read(bytes, 0, 4);
                                    var str = System.Text.Encoding.Default.GetString(bytes);
                                    if (str != "data")
                                    {
                                        throw new Exception("WAV error: Data section not found \n");
                                    }

                                    // Skip data length
                                    prefixResampled.Read(bytes, 0, 4);
                                }
                                else
                                {
                                    var prefixStream       = new Mp3FileReader(prefixFile);
                                    var prefixResampledTmp = new MediaFoundationResampler(prefixStream, outFormat);

                                    // Convert NAudioStream to System.IO.Stream
                                    byte[] sampleByte = { 0 };
                                    int    read;
                                    while ((read = prefixResampledTmp.Read(sampleByte, 0, sampleByte.Length)) > 0)
                                    {
                                        prefixResampled.Write(sampleByte, 0, read);
                                    }

                                    prefixResampled.Seek(0, SeekOrigin.Begin);
                                }

                                while (true)
                                {
                                    bytesReturned = prefixResampled.Read(buffer, 0, buffer.Length);

                                    if (bytesReturned <= 0)
                                    {
                                        break;
                                    }

                                    bool isEmpty = (buffer.Where(v => v != 0).Count() == 0);
                                    if (!isEmpty)
                                    {
                                        float[] sampleBuffer;
                                        if (RuntimeInformation.IsOSPlatform(OSPlatform.Linux))
                                        {
                                            sampleBuffer = MemoryMarshal.Cast <byte, float>(buffer.AsSpan()).ToArray();
                                        }
                                        else
                                        {
                                            sampleBuffer = ConvertToFloat(buffer, bytesReturned, channels);
                                        }

                                        if ((outputData.Length + 0x1000 + sampleBuffer.Length) >= maxSize)
                                        {
                                            break;
                                        }
                                        oggOut.WriteSamples(sampleBuffer, 0, sampleBuffer.Length);
                                    }
                                    lastIndex = (uint)oggOut.PageCounter;
                                }

                                if (RuntimeInformation.IsOSPlatform(OSPlatform.Linux))
                                {
                                    File.Delete(prefixTmpWavFile);
                                }
                            }
                            catch (Exception ex)
                            {
                                throw new Exception("Failed processing prefix file '" + prefixFile + "'");
                            }
                        }

                        Stream streamResampled = new MemoryStream();

                        // Linux
                        string tmpWavFile = "";

                        /* then the real audio file */
                        if (RuntimeInformation.IsOSPlatform(OSPlatform.Linux))
                        {
                            tmpWavFile = Path.ChangeExtension(Path.GetTempFileName(), "wav");

                            //Console.Write(" Convert file " + sourceFile + " to WAV. Temp file " + TmpWavFile);

                            // The isReady flag and error test variables are not a nice solution but is working
                            bool   isReady         = false;
                            String FFmpegErrorText = "";

                            // Convert to WAV and resample
                            Task.Run(async() =>
                            {
                                try
                                {
                                    IMediaInfo inputFile = await FFmpeg.GetMediaInfo(sourceFile);

                                    IAudioStream audioStream = inputFile.AudioStreams.First()
                                                               .SetCodec(AudioCodec.pcm_f32le)
                                                               .SetChannels(2)
                                                               .SetSampleRate(samplingRate);

                                    IConversionResult conversionResult = await FFmpeg.Conversions.New()
                                                                         .AddStream(audioStream)
                                                                         .SetOutput(tmpWavFile)
                                                                         .AddParameter("-map_metadata -1 -fflags +bitexact -flags:v +bitexact -flags:a +bitexact") // Remove meta data
                                                                         .Start();
                                }
                                catch (Exception e)
                                {
                                    FFmpegErrorText = e.Message;
                                    Console.WriteLine(e.Message);
                                    throw new Exception("FFmepg error " + e.Message + "\n");
                                }

                                isReady = true;
                            });

                            while (!isReady)
                            {
                                Thread.Sleep(200);
                                if (FFmpegErrorText != "")
                                {
                                    throw new Exception("FFmepg error: " + FFmpegErrorText + "\n");
                                }
                            }

                            // Read WAV file
                            byte[] wavBytes = File.ReadAllBytes(tmpWavFile);
                            streamResampled.Write(wavBytes, 0, wavBytes.Length);
                            streamResampled.Seek(0, SeekOrigin.Begin);

                            // Skip WAV header
                            byte[] bytes = new byte[4];
                            streamResampled.Seek(16, 0);
                            streamResampled.Read(bytes, 0, 4);
                            int Subchunk1Size = BitConverter.ToInt32(bytes, 0); // Get FMT size

                            // Skip some header information
                            streamResampled.Read(buffer, 0, Subchunk1Size + 12); // Data starts at FMT size + 12 bytes

                            // Read data chunk
                            streamResampled.Read(bytes, 0, 4);
                            var str = System.Text.Encoding.Default.GetString(bytes);
                            if (str != "data")
                            {
                                throw new Exception("WAV error: Data section not found \n");
                            }

                            // Skip data length
                            streamResampled.Read(bytes, 0, 4);
                        }
                        else
                        {
                            var stream             = new Mp3FileReader(sourceFile);
                            var streamResampledTmp = new MediaFoundationResampler(stream, outFormat);

                            // Convert NAudioStream to System.IO.Stream
                            byte[] sampleByte = { 0 };
                            int    read;
                            while ((read = streamResampledTmp.Read(sampleByte, 0, sampleByte.Length)) > 0)
                            {
                                streamResampled.Write(sampleByte, 0, read);
                            }

                            streamResampled.Seek(0, SeekOrigin.Begin);
                        }

                        while (true)
                        {
                            bytesReturned = streamResampled.Read(buffer, 0, buffer.Length);

                            if (bytesReturned <= 0)
                            {
                                break;
                            }
                            totalBytesRead += bytesReturned;

                            float progress = (float)streamResampled.Position / streamResampled.Length;

                            if ((int)(progress * 20) != lastPct)
                            {
                                lastPct = (int)(progress * 20);
                                if (lastPct % 5 == 0)
                                {
                                    if (lastPct != 20)
                                    {
                                        Console.Write("" + (lastPct * 5) + "%");
                                    }
                                }
                                else
                                {
                                    Console.Write(".");
                                }
                            }

                            bool isEmpty = (buffer.Where(v => v != 0).Count() == 0);
                            if (!isEmpty)
                            {
                                float[] sampleBuffer;
                                if (RuntimeInformation.IsOSPlatform(OSPlatform.Linux))
                                {
                                    sampleBuffer = MemoryMarshal.Cast <byte, float>(buffer.AsSpan()).ToArray();
                                }
                                else
                                {
                                    sampleBuffer = ConvertToFloat(buffer, bytesReturned, channels);
                                }

                                oggOut.WriteSamples(sampleBuffer, 0, sampleBuffer.Length);
                            }
                            lastIndex = (uint)oggOut.PageCounter;
                        }

                        Console.WriteLine("]");
                        if (RuntimeInformation.IsOSPlatform(OSPlatform.Linux))
                        {
                            File.Delete(tmpWavFile);
                        }

                        streamResampled.Close();
                    }
                    catch (OpusOggWriteStream.PaddingException e)
                    {
                        Console.WriteLine();
                        throw new EncodingException("Failed to pad opus data properly. Please try CBR with bitrates a multiple of 24 kbps");
                    }
                    catch (FileNotFoundException e)
                    {
                        Console.WriteLine();
                        throw new FileNotFoundException(e.Message);
                    }
                    catch (InvalidDataException e)
                    {
                        Console.WriteLine();
                        throw new Exception("Failed processing " + sourceFile);
                    }
                    catch (Exception e)
                    {
                        Console.WriteLine();
                        throw new Exception("Failed processing " + sourceFile + "\n Error: " + e.Message + "\n");
                    }

                    if (!warned && outputData.Length >= maxSize / 2)
                    {
                        Console.WriteLine("Warning: Approaching 2 GiB, please reduce the bitrate");
                        warned = true;
                    }
                }

                oggOut.Finish();
                Header.AudioId = oggOut.LogicalStreamId;
            }

            Audio = File.ReadAllBytes(tempName);

            var prov = new SHA1CryptoServiceProvider();

            Header.Hash          = prov.ComputeHash(Audio);
            Header.AudioChapters = chapters.ToArray();
            Header.AudioLength   = Audio.Length;
            Header.Padding       = new byte[0];

            File.Delete(tempName);
        }
예제 #13
0
        public async static Task <IConversionResult> buildBrokenMp4From(string input, string output, double crashTiming)
        {
            List <string> badParts = new List <string>();

            try
            {
                writeLine("Getting total Length...");
                TimeSpan totalLength = (await FFmpeg.GetMediaInfo(input)).VideoStreams.ToList().FirstOrDefault().Duration;

                if (totalLength.TotalSeconds <= 1)
                {
                    throw new Exception("The Video has to be longer than 1 second!");
                }

                if (crashTiming < 1 || crashTiming > totalLength.TotalSeconds)
                {
                    throw new Exception("The Crash Timing cannot be before the first second and cannot exceed the total length of the Video!");
                }

                writeLine("Checking for Files...");

                #region Generate View-Able portion of the video
                writeLine("Generating View-Able Part...");
                IConversion good = await FFmpeg.Conversions.FromSnippet.Split(input, goodSample, TimeSpan.Zero, TimeSpan.FromSeconds(crashTiming));

                good.SetPixelFormat(PixelFormat.yuv420p);
                good.SetOverwriteOutput(true);
                IConversionResult goodResult = await good.Start();

                #endregion


                #region Generate multiple broken parts of the Video
                writeLine("Generating Broken Video Parts...");

                {
                    TimeSpan time2workwith = (totalLength - TimeSpan.FromSeconds(crashTiming)) / brokenSamples;

                    TimeSpan position = TimeSpan.FromSeconds(crashTiming);

                    for (int i = 0; i < brokenSamples; i++)
                    {
                        string samplePath = badSample + i + ".mp4";

                        writeLine("> Generating Broken Sample " + (i + 1) + " out of " + brokenSamples);

anotherAttempt:
                        try
                        {
                            await generateBrokenSample(input, samplePath, position, time2workwith);

                            //  await gifBreaker(samplePath);
                        }
                        catch (Exception e)
                        { // in some cases conversion will f**k up, so just try again cuz i cba to filter out which cant be converted
                            if (e is ConversionException)
                            {
                                writeLine(ConsoleColor.Red, "Invalid Conversion occurred. Trying again...", null);
                                Thread.Sleep(1000);
                                goto anotherAttempt;
                            }
                            else
                            {
                                writeLine(ConsoleColor.Red, e, null);
                            }
                        }

                        badParts.Add(samplePath);

                        position += time2workwith;
                    }
                }

                //           badParts.Add(await Get10k());

                #endregion


                #region Files Collection
                writeLine("Creating Files Collection...");

                if (File.Exists(sampleCollection))
                {
                    File.Delete(sampleCollection);
                }

                File.Create(sampleCollection).Close();

                {
                    string content = "file '" + goodSample + "'\n";

                    foreach (string sample in badParts)
                    {
                        content += "file '" + sample + "'\n";
                    }

                    await File.WriteAllTextAsync(sampleCollection, content);
                }
                #endregion


                #region Concat
                writeLine("Merging Files...");

                List <IMediaInfo> mediaInfos = new List <IMediaInfo>();

                IConversion conversion = FFmpeg.Conversions.New();

                conversion.SetOverwriteOutput(true);
                conversion.AddParameter($"-f concat");
                conversion.AddParameter($"-safe 0");
                conversion.AddParameter($"-i \"{sampleCollection}\"");
                conversion.AddParameter($"-codec copy");

                writeLine("Building output...");

                writeLine("File can be found in: ", ConsoleColor.Yellow, output, null);

                return(await conversion.SetOutput(output)
                       .Start());

                #endregion
            }
            catch (Exception e)
            {
                if (e is FFmpegNotFoundException)
                {
                    writeLine(ConsoleColor.Yellow, "FFmpeg not found. You must install FFmpeg before using this Program.");
                    writeLine("Download the executables here: '", ConsoleColor.Red, "https://github.com/BtbN/FFmpeg-Builds/releases", null, "'");
                    writeLine(ConsoleColor.Yellow, "Place the Executables into: ", ConsoleColor.Red, @"C:\FFmpeg\bin", ConsoleColor.Gray);
                }
                else
                {
                    writeLine("An exception was Thrown: ", ConsoleColor.Yellow, e, null);
                }
            }
            finally
            {
                Cleanup();
            }

            return(null);
        }
예제 #14
0
 private async void Window_Loaded(object sender, RoutedEventArgs e)
 {
     IConversionResult result = await Conversion.ToMp4(@"D:\2.mp4", @"D:\3.mp4").Start();
 }
 protected void SetupCreate <T>(IConversionResult result)
 {
     InstanceCreatorMock.Setup(c => c.Create(typeof(T))).Returns <Type>(t => result);
 }
 protected void SetupCreateFromString <T>(string input, IConversionResult result)
 {
     SetupCreateFromString <T>(input, v => result);
 }