メインコンテンツへスキップ

動画の分散エンコードクラスタを自作・運用している話・39

    目次

    他の処理もまとめたい 

    前回、初期化関連の処理を見直しましたが、ついでなんで他の処理もまとめておきましょう。


    ちょうどいいので、変更後の全部のコードを列挙しておきます。
    まずはクラスから。

    FILEクラス

    using System.Collections.Generic;
    using System.Linq;
    
    using System.Threading;
    using System.Diagnostics;
    
    namespace ClusterManager
    {
        public class FILE
        {
            public string InputPath;
            public string OutputPath;
            public string TmpPath;
    
            public uint TotalFrame;
            public List<JOB> JobList;
    
            public FILE()
            {
                JobList = new List<JOB>();
            }
    
            public void GetTotalFrame(string frame_reader_path)
            {
                using (var p = new Process())
                {
                    p.StartInfo.FileName = frame_reader_path;
                    p.StartInfo.Arguments = $"\"{this.InputPath}\"";
                    p.StartInfo.CreateNoWindow = true;
                    p.StartInfo.UseShellExecute = false;
                    p.StartInfo.RedirectStandardOutput = true;
    
                    p.Start();
    
                    while (p.HasExited == false)
                        Thread.Sleep(100);
    
                    using (var s = p.StandardOutput)
                    {
                        var line = s.ReadToEnd();
                        if (uint.TryParse(line, out uint tmp_val) == true)
                            this.TotalFrame = tmp_val;
                    }
                }
            }
    
            public void CreateJobList(uint initial_split_num, uint min_frame_size)
            {
                var split_num = initial_split_num;
    
                if (this.TotalFrame / split_num < min_frame_size)
                    split_num = this.TotalFrame / min_frame_size;
    
                for (int i = 0; i < split_num; i++)
                {
                    var start_frame = this.TotalFrame * i / split_num;
                    var end_frame = this.TotalFrame * (i + 1) / split_num;
                    var dst_path = $@"{this.TmpPath}\tmp_{i}.mp4";
    
                    var json_string = new List<string>
                    {
                        $@"""{JOB_DATA.INPUT}"":""{this.InputPath}""",
                        $@"""{JOB_DATA.OUTPUT}"":""{dst_path}""",
                        $@"""{JOB_DATA.START}"":""{ start_frame}""",
                        $@"""{JOB_DATA.END}"":""{end_frame}""",
                    }
                    .Aggregate((a, b) => $"{a},{b}")
                    .Replace("\\", "\\\\");
    
                    json_string = $"{{{json_string}}}";
    
                    var data_string = json_string;
    
                    this.JobList.Add(new JOB(data_string, dst_path));
                }
            }
        }
    }

    JOBクラス

    public class JOB
    {
        public string Arg;
        public string DstPath;
        public bool finish;
        public DateTime StartTime;
        public DateTime EndTime;
    
        public JOB(string arg, string dst)
        {
            Arg = arg;
            DstPath = dst;
            finish = false;
        }
    }

    REMOTEクラス

    using System;
    using System.Text;
    using System.Threading.Tasks;
    
    using System.Net.Sockets;
    using System.IO;
    
    namespace ClusterManager
    {
        public partial class REMOTE
        {
            public string Name;
            public int Port;
    
            public Task<string> task;
            public JOB job;
    
            public REMOTE(string name, int port)
            {
                Name = name;
                Port = port;
                task = null;
                job = null;
            }
        }
    
        public partial class REMOTE
        {
            public string RecieveData(string remote_name, int remote_port, string send_msg)
            {
                var socket = new TcpClient();
    
                socket.Connect(remote_name, remote_port);
    
                using (var ns = socket.GetStream())
                {
                    // メッセージのエンコード
                    var enc = Encoding.UTF8;
                    byte[] send_buffer = enc.GetBytes(send_msg);
    
                    // メッセージの送信
                    ns.Write(send_buffer, 0, send_buffer.Length);
    
                    // メッセージの受信
                    var recieve_buffer = new byte[128];
                    using (var ms = new MemoryStream())
                    {
                        do
                        {
                            int n = ns.Read(recieve_buffer, 0, recieve_buffer.Length);
                            if (n < 1)
                                break;
    
                            ms.Write(recieve_buffer, 0, n);
                        }
                        while (ns.DataAvailable == true);
                    }
    
                    // メッセージのデコード
                    return enc.GetString(recieve_buffer).TrimEnd('\0');
                }
            }
        }
    }

    APPLICATIONクラス

    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Text;
    using System.Threading.Tasks;
    
    using System.Text.Json;
    using System.IO;
    
    namespace ClusterManager
    {
        public partial class APPLICATION
        {
            public string InputPath;
            public string FFmpegPath;
            public string ReaderPath;
            public string TmpDirPath;
    
            public uint SplitNum;
            public uint MinFrameSize;
    
            public FILE File;
            public List<REMOTE> RemoteList;
    
            public APPLICATION()
            {
                RemoteList = new List<REMOTE>();
            }
        }
    
        public partial class APPLICATION
        {
            public static APPLICATION Initialize(string[] args)
            {
                // 設定ファイルの読み込み
                var cfg_path = $@"{Directory.GetCurrentDirectory()}\config.cfg";
                var cfg_string = ReadConfigFile(cfg_path);
    
                var cfg_list = GetConfig(cfg_string);
    
                // コマンドライン引数の解析
                var arg_list = GetArgument(args);
    
                if (arg_list.Keys.Contains(ARG_SWITCH.INPUT_FILE) == false
                    || arg_list[ARG_SWITCH.INPUT_FILE] == "")
                {
                    Console.WriteLine("INPUT FILE is not found.");
                    Console.Read();
                    return null;
                }
    
                // 設定の比較
                var app_config = CompareConfig(cfg_list, arg_list);
    
                // ファイルの初期化
                app_config.File = InitializeFile(app_config);
    
                // リモートサーバーの初期化
                app_config.RemoteList = InitializeServer(app_config);
    
                return app_config;
            }
    
            static List<REMOTE> InitializeServer(APPLICATION app_config)
            {
                // 設定ファイルの読み込み
                var server_cfg_path = $@"{Directory.GetCurrentDirectory()}\server_list.cfg";
                var server_cfg_string = "";
    
                // リモートPC情報の初期化
                using (var s = new StreamReader(server_cfg_path))
                {
                    server_cfg_string = s.ReadToEnd();
                }
    
                var server_cfg_list = JsonSerializer.Deserialize<List<Dictionary<string, string>>>(server_cfg_string);
    
                var remote_list = new List<REMOTE>();
                foreach (var cfg in server_cfg_list)
                {
                    remote_list.Add(new REMOTE(cfg[CONFIG.KEY.SERVER_NAME], int.Parse(cfg[CONFIG.KEY.SERVER_PORT])));
                }
    
                return remote_list;
            }
    
            static FILE InitializeFile(APPLICATION app_config)
            {
                FILE File = new FILE();
                File.InputPath = app_config.InputPath;
                File.OutputPath = $@"{Path.GetDirectoryName(File.InputPath)}\output.mp4";
                File.TmpPath = app_config.TmpDirPath;
    
                // フレーム集の取得
                File.GetTotalFrame(app_config.ReaderPath);
    
                // ジョブリストの初期化
                File.CreateJobList(app_config.SplitNum, app_config.MinFrameSize);
    
                return File;
            }
    
            static APPLICATION CompareConfig(Dictionary<string, string> cfg_list,
                                             Dictionary<string, string> arg_list)
            {
                var app_config = new APPLICATION();
    
                {
                    var value = IncludeKey(cfg_list, CONFIG.KEY.FFMPEG_PATH);
                    if (value != "" && System.IO.File.Exists(value) == true)
                        app_config.FFmpegPath = value;
                }
    
                {
                    var value = IncludeKey(cfg_list, CONFIG.KEY.READER_PATH);
                    if (value != "" && System.IO.File.Exists(value) == true)
                        app_config.ReaderPath = value;
                }
    
                {
                    var value = IncludeKey(cfg_list, CONFIG.KEY.TMP_DIR);
                    if (value != "" && Directory.Exists(value) == true)
                        app_config.TmpDirPath = value;
                }
    
                {
                    var value = IncludeKey(cfg_list, CONFIG.KEY.SPLIT_NUM);
                    if (value != "" && uint.TryParse(value, out uint t) == true)
                        app_config.SplitNum = t;
    
                    value = IncludeKey(arg_list, ARG_SWITCH.SPLIT_NUM);
                    if (value != "" && uint.TryParse(value, out uint t2) == true)
                        app_config.SplitNum = t2;
                }
    
                {
                    var value = IncludeKey(cfg_list, CONFIG.KEY.MIN_FRAME_SIZE);
                    if (value != "" && uint.TryParse(value, out uint t) == true)
                        app_config.MinFrameSize = t;
    
                    value = IncludeKey(arg_list, ARG_SWITCH.MIN_FRAME_SIZE);
                    if (value != "" && uint.TryParse(value, out uint t2) == true)
                        app_config.MinFrameSize = t2;
                }
    
                {
                    var value = IncludeKey(arg_list, ARG_SWITCH.INPUT_FILE);
                    if (value != "" && System.IO.File.Exists(value) == true)
                        app_config.InputPath = value;
                }
    
                return app_config;
            }
    
            static string IncludeKey(Dictionary<string, string> list, string key)
            {
                if (list.Keys.ToList().IndexOf(key) > -1)
                    return list[key];
    
                return "";
            }
    
            static Dictionary<string, string> GetArgument(string[] args)
            {
                var arg_list = new Dictionary<string, string>();
    
                for (int i = 0; i < args.Length; i++)
                {
                    var key = args[i];
                    var value = "";
                    if (i + 1 < args.Length)
                        value = args[i + 1];
    
                    switch (key)
                    {
                        case ARG_SWITCH.INPUT_FILE:
                            arg_list[ARG_SWITCH.INPUT_FILE] = value;
                            if (System.IO.File.Exists(arg_list[ARG_SWITCH.INPUT_FILE]) == false)
                                arg_list[ARG_SWITCH.INPUT_FILE] = "";
                            break;
    
                        case ARG_SWITCH.SPLIT_NUM:
                            {
                                if (int.TryParse(value, out int t) == true)
                                    arg_list[ARG_SWITCH.SPLIT_NUM] = value;
                            }
                            break;
    
                        case ARG_SWITCH.MIN_FRAME_SIZE:
                            {
                                if (int.TryParse(value, out int t) == true)
                                    arg_list[ARG_SWITCH.MIN_FRAME_SIZE] = value;
                            }
                            break;
                    }
                }
    
                return arg_list;
            }
    
            static Dictionary<string, string> GetConfig(string cfg_string)
            {
                var cfg_list = JsonSerializer.Deserialize<Dictionary<string, string>>(cfg_string);
    
                if (cfg_list.Keys.ToList().IndexOf(CONFIG.KEY.FFMPEG_PATH) < 0)
                    cfg_list[CONFIG.KEY.FFMPEG_PATH] = @"C:\Program Files\ffmpeg\bin\ffmpeg.exe";
    
                if (cfg_list.Keys.ToList().IndexOf(CONFIG.KEY.READER_PATH) < 0)
                    cfg_list[CONFIG.KEY.READER_PATH] = @"C:\Program Files\ffmpeg\bin\FrameReader.exe";
    
                if (cfg_list.Keys.ToList().IndexOf(CONFIG.KEY.TMP_DIR) < 0)
                    cfg_list[CONFIG.KEY.TMP_DIR] = @"C:\tmp\";
    
                if (cfg_list.Keys.ToList().IndexOf(CONFIG.KEY.SPLIT_NUM) < 0)
                    cfg_list[CONFIG.KEY.SPLIT_NUM] = "2";
    
                if (cfg_list.Keys.ToList().IndexOf(CONFIG.KEY.MIN_FRAME_SIZE) < 0)
                    cfg_list[CONFIG.KEY.MIN_FRAME_SIZE] = "1000";
    
                return cfg_list;
            }
    
            static string ReadConfigFile(string cfg_path)
            {
                var cfg_string = "";
                using (var s = new StreamReader(cfg_path))
                {
                    cfg_string = s.ReadToEnd();
                }
                return cfg_string;
            }
        }
    }

    で、メインメソッド。

    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.IO;
    using System.Threading;
    using System.Threading.Tasks;
    using System.Diagnostics;
    
    using System.Text.Json;
    
    namespace ClusterManager
    {
        internal class Program
        {
            static void Main(string[] args)
            {
                // 設定の初期化
                var AppData = APPLICATION.Initialize(args);
    
                // 完了を待機
                while (true)
                {
                    Thread.Sleep(1000);
    
                    if (AppData.File.JobList.Where(j => j.finish == false).Count() == 0)
                        break;
    
                    // エンコード処理
                    Encode(AppData);
                }
    
                // 断片ファイルの結合
                if (Merge(AppData) == true)
                    Console.WriteLine("\nMerge Compelete.");
                else
                    Console.WriteLine("\nMerge Failed.");
    
                Console.Read();
            }
    
            static void Encode(APPLICATION AppData)
            {
                foreach (var remote in AppData.RemoteList)
                {
                    var msg_list = new List<string>();
    
                    var task_status = "";
    
                    if (remote.task != null)
                    {
                        if (remote.task.Status != TaskStatus.Running)
                        {
                            var msg = remote.task.Result;
                            remote.task = null;
    
                            var now_time = DateTime.Now;
                            var passed_time = (now_time - remote.job.StartTime).TotalSeconds;
    
                            var dst_file_name = $@"{Path.GetFileName(remote.job.DstPath)}";
    
                            Dictionary<string, string> recieve_data = null;
    
                            // JSONのパース
                            recieve_data = JsonSerializer.Deserialize<Dictionary<string, string>>(msg);
    
                            if (recieve_data == null)
                                continue;
    
                            if (recieve_data[JOB_DATA.PROGRESS] == JOB_PROGRESS.FINISH)
                            {
                                // ノードの処理が完了
                                remote.job.EndTime = now_time;
                                remote.job.finish = true;
                                remote.job = null;
    
                                task_status = $"{remote.Name} : {dst_file_name} Compelete. {passed_time:0.0}s";
                            }
                            else
                            {
                                task_status = $"{remote.Name} : {dst_file_name} Operating. {passed_time:0.0}s";
                            }
                        }
                    }
    
                    if (task_status != "")
                    {
                        msg_list.Add(task_status);
                    }
    
                    if (remote.task == null)
                    {
                        if (remote.job == null)
                        {
                            var executing_job_list = AppData.RemoteList.Select(r => r.job).ToList();
                            var unfinshed_job_list = AppData.File.JobList.Where(j => j.finish == false)
                                                                 .Where(j => executing_job_list.IndexOf(j) < 0)
                                                                 .ToList();
    
                            if (unfinshed_job_list.Count > 0)
                            {
                                remote.job = unfinshed_job_list[0];
                                remote.job.StartTime = DateTime.Now;
                            }
                        }
    
                        if (remote.job != null)
                            remote.task = Task.Run(() => remote.RecieveData(remote.Name, remote.Port, remote.job.Arg));
                    }
    
                    if (msg_list.Count > 0)
                    {
                        var status_msg = msg_list.Aggregate((a, b) => $"{a}, {b}");
                        Console.WriteLine($"{status_msg}");
                    }
                }
            }
    
            static bool Merge(APPLICATION AppData)
            {
                // ファイルリストの作成
                var filelist_path = $@"{Directory.GetCurrentDirectory()}\filelist.txt";
                using (var s = new StreamWriter(filelist_path, false))
                {
                    foreach (var job in AppData.File.JobList)
                    {
                        var file_name = job.DstPath;//.Replace('\\', '/');
                        s.WriteLine($@"file '{file_name}'");
                    }
                }
    
                using (var p = new Process())
                {
                    p.StartInfo.FileName = AppData.FFmpegPath;
                    p.StartInfo.Arguments = $@"-f concat -safe 0 -i ""{filelist_path}"" -c copy ""{AppData.File.OutputPath}""";
    
                    p.Start();
    
                    while (p.HasExited == false)
                        Thread.Sleep(100);
                }
    
                return File.Exists(AppData.File.OutputPath);
            }
        }
    }

    設定ファイルはこんな感じ。

    config.cfg

    {
    	"FFMPEG_PATH" : "D:\\Program Files\\ffmpeg\\bin\\ffmpeg.exe",
    	"READER_PATH" : "D:\\Program Files\\ffmpeg\\bin\\FrameReader.exe",
    
    	"TMP_DIR" : "C:\\tmp\\",
    
    	"SPLIT_NUM" : "5",
    	"MIN_FRAME_SIZE" : "2000"
    }

    server_list.cfg

    [
      {
        "NAME": "REMOTE-PC1",
        "PORT": "10000"
      },
      {
        "NAME": "REMOTE-PC12",
        "PORT": "10000"
      }
    ]

    とても長くなりましたが、これで一段落です。さらに改良を続けていきましょう。


     
     
    私は自宅で動画エンコードクラスタを運用している日曜プログラマです。13年以上にわたる運用での気付きや自作クラスタへのフィードバックをまとめていきたいと思います。

    あなたへのおすすめ