#2
龙胆草2022-11-02 16:46
|
原理:调用adb命令控制手机录屏,输出到一个播放器。
画面流畅不卡。
adb不知道的百度查询。
adb相关操作参考:
https://
播放器参考:
https://
以上均为开源软件,全部源代码。
下载:
链接:https://pan.baidu.com/s/1Ps6terEiFEQD8FdEURju-g
提取码:5b3z
只有本站会员才能查看附件,请 登录
程序代码:
using System;
using System.Diagnostics;
using using System.Text;
using System.Text.RegularExpressions;
using System.Windows.Forms;
namespace Phone_Demo
{
public partial class Form1 : Form
{
public class DeviceInfoData
{
public int deviceWidth = 1920;
public int deviceHeight = 1080;
public double deviceRefreshRate = 60;
public bool deviceVmode = false;
}
private Process stdoutProcess = null;
private Process stdinProcess = null;
private StreamPipe rePipe;
private readonly DeviceInfoData deviceInfoData = new DeviceInfoData();
private readonly DeviceInfoData instartDeviceInfoData = new DeviceInfoData();
private double castMbitRate = 30;
public Form1()
{
InitializeComponent();
this.FormClosed += (s, e) => { Kill_Process("adb"); };
}
private void button1_Click(object sender, EventArgs e)
{
StopCast();
if (UpdateScreenDeviceInfo())
{
StartCast();
}
}
private void StartCast()
{
stdoutProcess = new Process();
stdinProcess = new Process();
StdOut();
StdIn();
rePipe = new StreamPipe(stdoutProcess.StandardOutput.BaseStream, stdinProcess.StandardInput.BaseStream);
rePipe.Connect();
instartDeviceInfoData.deviceVmode = deviceInfoData.deviceVmode; // 记录播放时的横竖屏状态
}
private void StopCast()
{
try
{
try
{
if (stdoutProcess != null)
{
stdoutProcess.Exited -= StdIOProcess_Exited;
stdoutProcess.Kill();
stdoutProcess = null;
}
}
catch (Exception ex)
{
MessageBox.Show("无法关闭StdOUT," + ex.Message);
}
try
{
if (stdinProcess != null)
{
stdinProcess.Exited -= StdIOProcess_Exited;
stdinProcess.Kill();
stdoutProcess = null;
}
}
catch (Exception ex)
{
MessageBox.Show("无法关闭StdIN," + ex.Message);
}
if (rePipe != null)
{
rePipe.Disconnect();
}
}
catch (Exception ex)
{
MessageBox.Show("无法断开重定向," + ex.Message);
}
nosigalLabel.Text = "等一下...,滑动手机屏幕";
}
private string ADBResult(string args)
{
Process process = new Process();
process.StartInfo.FileName = System.AppDomain.CurrentDomain.BaseDirectory + @"lib\adb\adb.exe";
process.StartInfo.Arguments = args;
process.StartInfo.UseShellExecute = false;
process.StartInfo.RedirectStandardOutput = true;
process.StartInfo.RedirectStandardError = true;
process.StartInfo.CreateNoWindow = true;
process.StartInfo.StandardOutputEncoding = Encoding.UTF8;
process.Start();
string result = process.StandardOutput.ReadToEnd();
string error = process.StandardError.ReadLine();
process.Close();
return error + result;
}
private bool UpdateScreenDeviceInfo()
{
string str = ADBResult("shell \"dumpsys window displays && dumpsys SurfaceFlinger\"").ToLower();
if (str.StartsWith("error: no devices/emulators found"))
{
MessageBox.Show("找不到任何设备或模拟器");
return false;
}
else if (str.StartsWith("error: more than one device/emulator"))
{
MessageBox.Show("暂时只支持单个设备开启 ADB 调试");
return false;
}
Regex regexSize = new Regex(@"\s+cur=(?<width>[0-9]*)x(?<height>[0-9]*?)\s+", RegexOptions.Multiline);
Match matchSize = regexSize.Match(str);
Regex regexRefreshRate = new Regex(@"\s+refresh-rate.+?(?<refreshRate>[0-9]*\.{0,1}[0-9]*?)\s*fps\s+", RegexOptions.Multiline);
Match matchRefreshRate = regexRefreshRate.Match(str);
if (matchSize.Success)
{
try
{
int width = int.Parse(matchSize.Groups["width"].Value); //宽
int height = int.Parse(matchSize.Groups["height"].Value); //高
bool vmode = true; //垂直
if (width > height)
{
vmode = false; //水平
}
deviceInfoData.deviceWidth = width;
deviceInfoData.deviceHeight = height;
deviceInfoData.deviceVmode = vmode;
}
catch { }
}
if (matchRefreshRate.Success)
{
try
{
double refreshRate = double.Parse(matchRefreshRate.Groups["refreshRate"].Value);
deviceInfoData.deviceRefreshRate = refreshRate;
}
catch { }
}
return true;
}
private void StdIOProcess_Exited(object sender, EventArgs e)
{
StopCast();
}
/// adb 录屏控制
private void StdOut()
{
stdoutProcess.StartInfo.FileName = @"lib\adb\adb.exe";
stdoutProcess.StartInfo.Arguments = $"exec-out \"while true;do screenrecord --bit-rate={(int)(castMbitRate * 1000000)} --output-format=h264 --size {deviceInfoData.deviceWidth.ToString()}x{deviceInfoData.deviceHeight.ToString()} - ;done\""; //
stdoutProcess.StartInfo.UseShellExecute = false;
stdoutProcess.StartInfo.RedirectStandardOutput = true;
stdoutProcess.StartInfo.CreateNoWindow = true;
stdoutProcess.EnableRaisingEvents = true;
stdoutProcess.Exited += StdIOProcess_Exited;
stdoutProcess.Start();
if (stdinProcess.StartInfo.FileName.Length != 0)
{
stdinProcess.CancelOutputRead();
stdinProcess.Close();
}
}
/// 播放器控制
private void StdIn()
{
string widArg = $"--wid={screenBox.Handle.ToInt64().ToString()}";
string vsyncArgs = "--d3d11-sync-interval=" + (false ? "1" : "0");
string releaseArgs = "--input-default-bindings=no --osd-level=0";
string fpsControlArgs = false ? $"--no-correct-pts --fps={deviceInfoData.deviceRefreshRate}" : "--untimed";
string hwdecArgs = true ? "--hwdec=yes" : "--hwdec=no";
string mpvFullArgs = $"--title=\"Phone Demo\" --cache=no --no-cache --profile=low-latency --framedrop=decoder {vsyncArgs} --scale=spline36 --cscale=spline36 --dscale=mitchell --correct-downscaling=yes --linear-downscaling=yes --sigmoid-upscaling=yes {fpsControlArgs} --video-latency-hacks=yes --vo=gpu {hwdecArgs} --no-audio --no-config --no-border -no-osc --no-taskbar-progress {releaseArgs} {widArg} -";
Console.WriteLine("MPV ARGS:\r\n" + mpvFullArgs);
stdinProcess.StartInfo.FileName = @"lib\mpv\mpv.exe";
stdinProcess.StartInfo.Arguments = mpvFullArgs;
stdinProcess.StartInfo.UseShellExecute = false;
stdinProcess.StartInfo.RedirectStandardOutput = true;
stdinProcess.StartInfo.RedirectStandardInput = true;
stdinProcess.StartInfo.CreateNoWindow = true;
stdinProcess.EnableRaisingEvents = true;
stdinProcess.Exited += StdIOProcess_Exited;
stdinProcess.Start();
stdinProcess.BeginOutputReadLine();
}
/// 删除进程
private void Kill_Process(string processName)
{
foreach (Process p in Process.GetProcesses())
{
if (p.ProcessName.Contains(processName))
{
try
{
p.Kill();
p.WaitForExit();
}
catch { }
}
}
}
}
}
[此贴子已经被作者于2022-11-2 08:15编辑过]