Thứ Sáu, 4 tháng 10, 2019

Check and Convert Video .mp4 From H265 to H264 C#

Trên Android chỉ chạy được mp4 với codec_name là H264, vì vậy cần hàm chuyển đổi video trên Server rồi trả api kết quả.

Code:
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Threading.Tasks;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

public partial class ConvertVideoH264 : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
        ConvertVideoH265toH264();
    }

    string exeFfmpegPath = @"F:\OTL\ffmpeg\ffmpeg\bin\ffmpeg.exe";
    string exeFfprobePath = @"F:\OTL\ffmpeg\ffmpeg\bin\ffprobe.exe";
    string fileInputPath = @"F:\OTL\ffmpeg\ffmpeg\bin\input.mp4";
    protected void ConvertVideoH265toH264()
    {
        string output = @"F:\OTL\ffmpeg\ffmpeg\bin\output.mp4";

        string cmdConvertH265toH264 = String.Format("-i {0} -c:v libx264 -crf 23 -vf format=yuv420p -c:a copy {1}", fileInputPath, output);

        string codecName = GetCodecName();
        //chuyen doi H255->H264
        if (codecName != "h264")
        {
            Task<string> callTask = Task.Run(() => RunFFTask(exeFfmpegPath, fileInputPath, cmdConvertH265toH264));
            callTask.Wait();
        }
    }

    protected string GetCodecName()
    {
        string cmdGetCodec = String.Format("-v error -select_streams v:0 -show_entries stream=codec_name -of default=noprint_wrappers=1:nokey=1 {0}", fileInputPath);

        Task<string> callTask = Task.Run(() => RunFFTask(exeFfprobePath, fileInputPath, cmdGetCodec));
        callTask.Wait();
        // does NOT deadlock - shouldn't call await Task.Result on main
        string codec = callTask.Result;
        return codec;
    }

    protected Task<string> RunFFTask(string exeFilePath, string fileInputPath, string cmd)
    {
        var tcs = new TaskCompletionSource<string>();

        // Use ProcessStartInfo class
        ProcessStartInfo startInfo = new ProcessStartInfo();
        startInfo.CreateNoWindow = false;
        startInfo.UseShellExecute = false;
        startInfo.FileName = exeFilePath;
        startInfo.WindowStyle = ProcessWindowStyle.Hidden;
        startInfo.Arguments = String.Format("{0}", cmd);
        startInfo.RedirectStandardOutput = true; // add to receive output

        var process = new Process
        {
            StartInfo = startInfo,
            EnableRaisingEvents = true,
        };

        process.Exited += (sender, args) =>
        {
            tcs.SetResult(process.StandardOutput.ReadLine());

            process.Dispose();
        };

        process.Start();

        return tcs.Task;
    }
}

Không có nhận xét nào:

Đăng nhận xét