-
Notifications
You must be signed in to change notification settings - Fork 6
Expand file tree
/
Copy pathProgram.cs
More file actions
206 lines (174 loc) · 8.15 KB
/
Program.cs
File metadata and controls
206 lines (174 loc) · 8.15 KB
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
using System;
using System.IO;
using System.Linq;
using System.Threading;
using SharpDX.Direct3D11;
using SharpDX.DXGI;
using static Lennox.NvEncSharp.LibNvEnc;
namespace Lennox.NvEncSharp.Sample.ScreenCapture
{
internal class Program
{
private bool _initialized = false;
private NvEncoder _encoder;
private NvEncCreateBitstreamBuffer _bitstreamBuffer;
private readonly object _writeMutex = new object();
private const int _fps = 30;
private const int _frameDuration = 1000 / _fps;
// This program captures the full frames of a display using directX,
// then uses the hardware NvEnc h264 encoder on Nvidia GPUs to encode
// h264 video directly from the GPU texture.
// The output is written as containerless h264 frames. Most software
// does not support playback of containerless formats but ffplay can:
// ffplay.exe -f h264 sample.264
public static void Main(string[] args)
{
var program = new Program();
program.Run(new ProgramArguments(args));
}
private void Run(ProgramArguments args)
{
using var duplicate = GetDisplayDuplicate(
args.DisplayName, out var outputDescription);
using var output = File.Open(args.OutputPath, FileMode.Create);
Console.WriteLine($"Process: {(Environment.Is64BitProcess ? "64" : "32")} bits");
Console.WriteLine($"Display: {outputDescription.DeviceName}");
Console.WriteLine($"Output: {output.Name}");
while (true)
{
// Get the next screen image.
duplicate.AcquireNextFrame(500,
out var frameInfo, out var resourceOut);
// If the frame has not changed, there's no reason to encode
// a new frame.
if (frameInfo.LastPresentTime == 0)
{
duplicate.ReleaseFrame();
resourceOut.Dispose();
Thread.Sleep(_frameDuration);
continue;
}
var desktopTexture = resourceOut.QueryInterface<Texture2D>();
var encoder = _initialized
? _encoder
: CreateEncoder(desktopTexture);
var desc = desktopTexture.Description;
var reg = new NvEncRegisterResource
{
Version = NV_ENC_REGISTER_RESOURCE_VER,
BufferFormat = NvEncBufferFormat.Abgr,
BufferUsage = NvEncBufferUsage.NvEncInputImage,
ResourceToRegister = desktopTexture.NativePointer,
Width = (uint)desc.Width,
Height = (uint)desc.Height,
Pitch = 0
};
// Registers the hardware texture surface as a resource for
// NvEnc to use.
using var _ = _encoder.RegisterResource(ref reg);
var pic = new NvEncPicParams
{
Version = NV_ENC_PIC_PARAMS_VER,
PictureStruct = NvEncPicStruct.Frame,
InputBuffer = reg.AsInputPointer(),
BufferFmt = NvEncBufferFormat.Abgr,
InputWidth = (uint)desc.Width,
InputHeight = (uint)desc.Height,
OutputBitstream = _bitstreamBuffer.BitstreamBuffer,
InputTimeStamp = (ulong)frameInfo.LastPresentTime,
InputDuration = _frameDuration
};
// Do the actual encoding. With this configuration this is done
// sync (blocking).
encoder.EncodePicture(ref pic);
// The output is written to the bitstream, which is now copied
// to the output file.
using (var sm = encoder.LockBitstreamAndCreateStream(
ref _bitstreamBuffer))
{
lock (_writeMutex)
{
sm.CopyTo(output);
}
}
desktopTexture.Dispose();
duplicate.ReleaseFrame();
resourceOut.Dispose();
Thread.Sleep(_frameDuration);
}
// ReSharper disable once FunctionNeverReturns
}
private static OutputDuplication GetDisplayDuplicate(
string displayName, out OutputDescription description)
{
// This much simpler code will grab an arbitrary display but
// works in most single output systems. It's useful for enabling
// debug on a device.
/*using var device = new SharpDX.Direct3D11.Device(
DriverType.Hardware, DeviceCreationFlags.Debug);
using var dxgiDevice = device.QueryInterface<SharpDX.DXGI.Device>();
using var dxgiAdapter = dxgiDevice.GetParent<Adapter>();
using var dxgiOutput = dxgiAdapter.GetOutput(0);
using var output1 = dxgiOutput.QueryInterface<Output1>();
return output1.DuplicateOutput(device);*/
using var factory = new Factory4();
var availableAdaptors = factory.Adapters;
var output = availableAdaptors
.SelectMany(t => t.Outputs)
.FirstOrDefault(t => displayName == null
? t.Description.IsAttachedToDesktop == true
: t.Description.DeviceName == displayName);
if (output == null)
{
throw new DriveNotFoundException(displayName);
}
var foundDeviceName = output.Description.DeviceName;
using var dxgiAdapter = output.GetParent<Adapter>();
using var device = new SharpDX.Direct3D11.Device(dxgiAdapter);
var dxgiOutput = dxgiAdapter.Outputs
.Single(t => t.Description.DeviceName == foundDeviceName);
using var output1 = dxgiOutput.QueryInterface<Output1>();
description = output1.Description;
return output1.DuplicateOutput(device);
}
private NvEncoder CreateEncoder(Texture2D texture)
{
if (_initialized) return _encoder;
var desc = texture.Description;
var encoder = OpenEncoderForDirectX(texture.Device.NativePointer);
var encoderConfig = encoder.GetEncodePresetConfig(NvEncCodecGuids.H264, NvEncPresetGuids.LowLatencyDefault).PresetCfg;
encoderConfig.RcParams.AverageBitRate = 4 * (1 << 20); // 4 Mbit
encoderConfig.RcParams.MaxBitRate = 8 * (1 << 20);
encoderConfig.RcParams.RateControlMode = NvEncParamsRcMode.Vbr;
unsafe
{
NvEncConfig* p = &encoderConfig;
var initparams = new NvEncInitializeParams
{
Version = NV_ENC_INITIALIZE_PARAMS_VER,
EncodeGuid = NvEncCodecGuids.H264,
EncodeHeight = (uint)desc.Height,
EncodeWidth = (uint)desc.Width,
MaxEncodeHeight = (uint)desc.Height,
MaxEncodeWidth = (uint)desc.Width,
DarHeight = (uint)desc.Height,
DarWidth = (uint)desc.Width,
FrameRateNum = _fps,
FrameRateDen = 1,
ReportSliceOffsets = false,
EnableSubFrameWrite = false,
PresetGuid = NvEncPresetGuids.LowLatencyDefault,
EnableEncodeAsync = 0,
EnablePTD = 1,
EnableWeightedPrediction = true,
EncodeConfig = p,
};
encoder.InitializeEncoder(ref initparams);
}
_bitstreamBuffer = encoder.CreateBitstreamBuffer();
_encoder = encoder;
_initialized = true;
return encoder;
}
}
}