ScreenShot.cs 8.8 KB
Newer Older
C
chao 已提交
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246
using Jvedio.Core.CustomEventArgs;
using Jvedio.Core.Exceptions;
using Jvedio.Entity;
using Jvedio.Utils.IO;
using Jvedio.Utils.Media;
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;

namespace Jvedio.Core.FFmpeg
{

    //TODO 线程池
    public class ScreenShot
    {
        private const int MAX_THREAD_NUM = 10;
        private const int DEFAULT_THREAD_NUM = 1;
        private const int DEFAULT_GIF_WIDTH = 280;
        private const int DEFAULT_GIF_HEIGHT = 170;
        private const int DEFAULT_DURATION = 3;
        private object ScreenShotLockObject = new object();

        private Video CurrentVideo { get; set; }

        private int TotalCount = (int)GlobalConfig.FFmpegConfig.ScreenShotNum;
        private int TimeOut = (int)GlobalConfig.FFmpegConfig.TimeOut;
        private string FFmpegPath = GlobalConfig.FFmpegConfig.Path;
        private bool SkipExistScreenShot = GlobalConfig.FFmpegConfig.SkipExistScreenShot;

        private List<string> saveFileNames = new List<string>();


        public int TotalTaskCount { get; set; }
        public int CurrentTaskCount { get; set; }
        private object TaskCountLock = new object();

        private StringBuilder outputs = new StringBuilder();

        private CancellationToken Token;

        public ScreenShot(Video video, CancellationToken token)
        {
            CurrentVideo = video;
            Token = token;
        }


        public event EventHandler onProgress;
        public event EventHandler onError;
        private object ErrorLock = new object();



        public async Task<string> AsyncScreenShot()
        {
            if (!File.Exists(FFmpegPath))
                throw new NotFoundException("ffmpeg.exe");
            string originPath = CurrentVideo.Path;
            if (!File.Exists(originPath))
                throw new NotFoundException(originPath);
            string[] cutoffArray = MediaParse.GetCutOffArray(originPath); //获得需要截图的视频进度
            if (cutoffArray.Length == 0)
                throw new MediaCutOutOfRangeException();
            int threadNum = (int)GlobalConfig.FFmpegConfig.ThreadNum;// 截图线程
            if (threadNum > MAX_THREAD_NUM || threadNum <= 0) threadNum = DEFAULT_THREAD_NUM;

            string outputDir = CurrentVideo.getScreenShot();
            if (SkipExistScreenShot && Directory.Exists(outputDir))
            {
                outputs.Append($"跳过截图,因为文件夹存在(可在设置中关闭) => {outputDir}");
                return outputs.ToString();
            }

            DirHelper.TryCreateDirectory(outputDir, (ex) =>
            {
                throw new DirCreateFailedException(outputDir);
            });

            // 生成截图命令
            List<string> ffmpegParams = new List<string>();
            for (int i = 0; i < cutoffArray.Count(); i++)
            {
                string saveFileName = Path.Combine(outputDir, $"ScreenShot-{i.ToString().PadLeft(2, '0')}.jpg");
                saveFileNames.Add(saveFileName);
                string cutoffTime = cutoffArray[i];
                if (string.IsNullOrEmpty(cutoffTime)) continue;
                string ffmpegParam = $"-y -threads 1 -ss {cutoffTime} -i \"{originPath}\" -f image2 -frames:v 1 \"{saveFileName}\"";
                ffmpegParams.Add(ffmpegParam);
            }

            StringBuilder cmd = new StringBuilder();
            cmd.AppendLine();
            cmd.AppendLine();
            cmd.Append($"#### ffmpeg commads ####{Environment.NewLine}");
            foreach (var item in ffmpegParams)
                cmd.Append($"ffmpeg {item}{Environment.NewLine}");
            cmd.AppendLine();
            cmd.AppendLine();
            outputs.Append(cmd.ToString());

            // 放到线程池里运行
            TotalTaskCount = ffmpegParams.Count;
            ThreadPool.SetMaxThreads(threadNum, threadNum);
            for (int i = 0; i < TotalTaskCount; i++)
            {
                ThreadPool.QueueUserWorkItem(new WaitCallback(RunFFmpeg), ffmpegParams[i]);
            }

            // 等待所有任务完成
            while (CurrentTaskCount < TotalTaskCount)
            {
                await Task.Delay(50);
                Console.WriteLine("等待截图完成");
                if (Token.IsCancellationRequested) break;
            }
            return outputs.ToString();
        }


        public void RunFFmpeg(object ffmpegParam)
        {
            StringBuilder currentOutput = new StringBuilder();
            Process process = new Process
            {
                StartInfo = new ProcessStartInfo
                {
                    FileName = FFmpegPath,
                    Arguments = ffmpegParam.ToString(),
                    CreateNoWindow = true,
                    UseShellExecute = false,
                    RedirectStandardOutput = true,
                    StandardErrorEncoding = Encoding.UTF8,
                    StandardOutputEncoding = Encoding.UTF8,
                    RedirectStandardError = true
                },
                EnableRaisingEvents = true

            };
            try
            {

                process.Start();
                string processOutput = "";
                while ((processOutput = process.StandardError.ReadLine()) != null)
                {
                    currentOutput.Append(processOutput);
                    currentOutput.AppendLine();
                }
                if (Token.IsCancellationRequested)
                    throw new TaskCanceledException();
            }
            catch (Exception ex)
            {
                lock (ErrorLock)
                {
                    onError?.Invoke(this, new MessageCallBackEventArgs(ex.Message));
                }
            }
            finally
            {
                process.Dispose();
                lock (TaskCountLock)
                {
                    CurrentTaskCount++;
                    onProgress?.Invoke(this, null);
                    outputs.Append(currentOutput.ToString());
                }
            }
        }





        public async Task<string> AsyncGenrateGif()
        {
            if (!File.Exists(FFmpegPath))
                throw new NotFoundException("ffmpeg.exe");
            string originPath = CurrentVideo.Path;
            if (!File.Exists(originPath))
                throw new NotFoundException(originPath);

            string[] cutoffArray = MediaParse.GetCutOffArray(originPath); //获得需要截图的视频进度
            if (cutoffArray.Length == 0)
                throw new MediaCutOutOfRangeException();


            string saveFileName = CurrentVideo.getGifPath();
            if (string.IsNullOrEmpty(saveFileName))
                throw new NotFoundException(saveFileName);

            if (GlobalConfig.FFmpegConfig.SkipExistGif && File.Exists(saveFileName))
            {
                outputs.Append($"跳过已截取的 GIF: {saveFileName}");
                return outputs.ToString();
            }

            string outputDir = Path.GetDirectoryName(saveFileName);
            DirHelper.TryCreateDirectory(outputDir, (ex) =>
            {
                throw new DirCreateFailedException(outputDir);
            });

            string cutofftime = cutoffArray[new Random().Next(cutoffArray.Length - 1)];
            if (string.IsNullOrEmpty(cutofftime))
                throw new MediaCutOutOfRangeException();

            int duration = (int)GlobalConfig.FFmpegConfig.GifDuration;
            int width = (int)GlobalConfig.FFmpegConfig.GifWidth;
            int height = (int)GlobalConfig.FFmpegConfig.GifHeight;
            if (width <= 0) width = DEFAULT_GIF_WIDTH;


            if (GlobalConfig.FFmpegConfig.GifAutoHeight)
            {
                (double w, double h) = MediaParse.GetWidthHeight(originPath);
                if (w != 0) height = (int)(h / w * (double)width);
            }

            if (width <= 0) width = DEFAULT_GIF_WIDTH;
            if (height <= 0) height = DEFAULT_GIF_HEIGHT;
            if (duration <= 0) duration = DEFAULT_DURATION;

            string ffmpegParam = $"-y -t {duration} -ss {cutofftime} -i \"{originPath}\" -s {width}x{height}  \"{saveFileName}\"";
            TotalCount = 1;

            outputs.Append($"{Environment.NewLine}#### ffmpeg commads ####{Environment.NewLine}");
            outputs.Append($"ffmpeg {ffmpegParam}{Environment.NewLine}");
            outputs.Append($"{Environment.NewLine}{Environment.NewLine}");

            RunFFmpeg(ffmpegParam);
            while (CurrentTaskCount < TotalTaskCount)
            {
                await Task.Delay(50);
                Console.WriteLine("等待 gif 生成");
                if (Token.IsCancellationRequested) break;
            }
            return outputs.ToString();
        }
    }
}