123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103 |
- using SkiaSharp;
- using System;
- using System.Drawing;
- using System.IO;
- using Vinno.IUS.Common.Media.FFmpeg;
- using Vinno.IUS.Common.Media.FFmpeg.Settings;
- using Vinno.IUS.Common.Media.FFmpeg.Video;
- using Vinno.IUS.Common.Media.FFmpeg.Video.Codecs;
- using Vinno.vCloud.Common.Vid2;
- namespace vCloud.Server.Utilities
- {
- class Mpeg4Converter
- {
- static string RootPath;
- static Mpeg4Converter()
- {
-
- }
- private static SKBitmap GetBitmap(VinnoImage image)
- {
- using (MemoryStream ms = new MemoryStream(image.ImageData))
- {
- var bitmap = SKBitmap.Decode(ms);
- return bitmap;
- }
- }
- public static void ConvertVidToMpeg4(VinnoImageData sourceVid, string destFile,string rootPath)
- {
- try
- {
- if (string.IsNullOrWhiteSpace(RootPath))
- {
- RootPath = rootPath;
- Console.WriteLine("Mpeg4Converter:" + Path.Combine(RootPath, "Utilities", "ffmpeg"));
- FFmpegService.SetFFmpegPath(Path.Combine(RootPath, "Utilities", "ffmpeg"));
- }
- var firstFrame = sourceVid.GetImage(0);
- if (firstFrame != null)
- {
- var width = firstFrame.Width;
- var height = firstFrame.Height;
- if (width % 2 != 0)
- {
- width--;
- }
- if (height % 2 != 0)
- {
- height--;
- }
- var imageRect = new Rectangle(0, 0, width, height);
- var frameSize = width * height * 4;
- var frameData = new byte[frameSize];
- var frameRate = (int)sourceVid.Probe.FrameRate;
- frameRate = frameRate == 0 ? 10 : frameRate; //FrameRate can not 0,if 0 give default value 10
- var setting = new FFmpegSettings();
- var writeArgs = new FFmpegVideoWriterArgs(destFile, firstFrame.Width, firstFrame.Height)
- {
- FrameRate = frameRate,
- VideoCodec = FFmpegVideoCodec.X264
- };
- using (var videoWriter = new FFmpegVideoWriter(writeArgs, setting))
- {
- for (var i = 0; i < sourceVid.ImageCount; i++)
- {
- var vinnoImage = sourceVid.GetImage(i);
- if (vinnoImage.Height > 0 && vinnoImage.Width > 0 && vinnoImage.ImageData != null && vinnoImage.ImageData.Length > 0)
- {
- SKBitmap bitmap = GetBitmap(vinnoImage);
- if (bitmap.Width != width || bitmap.Height != height)
- {
- bitmap = bitmap.Resize(new SKImageInfo(width, height), SKFilterQuality.None);
- }
- try
- {
- if (bitmap.Bytes != null && bitmap.Bytes.Length > 0 && bitmap.Width > 0 && bitmap.Height > 0)
- {
- var frame = new BitmapFrame(bitmap.Width, bitmap.Height, bitmap.Bytes);
- videoWriter.WriteFrame(frame);
- }
- }
- catch (Exception exception)
- {
- throw new Exception($"encoder add image index {i} error:{exception}");
- }
- finally
- {
- bitmap.Dispose();
- }
- }
- }
- }
- }
- }
- catch (Exception exception)
- {
- throw new Exception($"ConvertVidToMpeg4 error:{exception}");
- }
- }
- }
- }
|