-
Notifications
You must be signed in to change notification settings - Fork 6
Expand file tree
/
Copy pathProgram.cs
More file actions
265 lines (233 loc) · 9.67 KB
/
Copy pathProgram.cs
File metadata and controls
265 lines (233 loc) · 9.67 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
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
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
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 Guid _codecGuid;
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 encoder on Nvidia GPUs to encode
// H.264, HEVC or AV1 video directly from the GPU texture.
// The output is written as containerless frames. Most software
// does not support playback of containerless formats but ffplay can:
// ffplay.exe -f h264 sample.264
// ffplay.exe -f hevc sample.hevc
// ffplay.exe -f obu sample.obu
public static void Main(string[] args)
{
var program = new Program();
program.Run(new ProgramArguments(args));
}
private void Run(ProgramArguments args)
{
_codecGuid = args.CodecGuid;
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}");
Console.WriteLine($"Codec: {(_codecGuid == NvEncCodecGuids.Av1 ? "AV1" : _codecGuid == NvEncCodecGuids.Hevc ? "HEVC" : "H.264")}");
try
{
CaptureFrames(duplicate, output);
}
finally
{
if (_encoder.Handle != IntPtr.Zero)
{
try
{
if (_bitstreamBuffer.BitstreamBuffer.Handle != IntPtr.Zero)
_encoder.DestroyBitstreamBuffer(_bitstreamBuffer.BitstreamBuffer);
}
finally
{
_encoder.DestroyEncoder();
}
}
}
}
private void CaptureFrames(OutputDuplication duplicate, Stream output)
{
while (true)
{
// Get the next screen image.
duplicate.AcquireNextFrame(500,
out var frameInfo, out var resourceOut);
try
{
using (resourceOut)
{
// If the frame has not changed, there's no reason to encode it.
if (frameInfo.LastPresentTime != 0)
{
using var desktopTexture = resourceOut.QueryInterface<Texture2D>();
EncodeFrame(desktopTexture, frameInfo.LastPresentTime, output);
}
}
}
finally
{
duplicate.ReleaseFrame();
}
Thread.Sleep(_frameDuration);
}
// ReSharper disable once FunctionNeverReturns
}
private void EncodeFrame(Texture2D desktopTexture, long timestamp, Stream output)
{
var encoder = _initialized ? _encoder : CreateEncoder(desktopTexture);
var desc = desktopTexture.Description;
var reg = new NvEncRegisterResource
{
Version = NV_ENC_REGISTER_RESOURCE_VER,
ResourceType = NvEncInputResourceType.Directx,
BufferFormat = NvEncBufferFormat.Argb,
BufferUsage = NvEncBufferUsage.NvEncInputImage,
ResourceToRegister = desktopTexture.NativePointer,
Width = (uint)desc.Width,
Height = (uint)desc.Height,
Pitch = 0
};
// Desktop duplication provides BGRA bytes (NVENC's little-endian ARGB).
using var registration = encoder.RegisterResource(ref reg);
var mapped = new NvEncMapInputResource
{
Version = NV_ENC_MAP_INPUT_RESOURCE_VER,
RegisteredResource = reg.RegisteredResource
};
encoder.MapInputResource(ref mapped);
try
{
var pic = new NvEncPicParams
{
Version = NV_ENC_PIC_PARAMS_VER,
PictureStruct = NvEncPicStruct.Frame,
InputBuffer = mapped.MappedResource,
BufferFmt = mapped.MappedBufferFmt,
InputWidth = (uint)desc.Width,
InputHeight = (uint)desc.Height,
OutputBitstream = _bitstreamBuffer.BitstreamBuffer,
InputTimeStamp = (ulong)timestamp,
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);
}
}
}
finally
{
encoder.UnmapInputResource(mapped.MappedResource);
}
}
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);
_encoder = encoder; // Retain ownership even if initialization fails.
if (!encoder.IsValidGuid(_codecGuid))
{
throw new NotSupportedException("The selected codec is not supported by this GPU's encoder.");
}
var encoderConfig = encoder.GetEncodePresetConfigEx(_codecGuid, NvEncPresetGuids.P1).PresetCfg;
if (_codecGuid == NvEncCodecGuids.Hevc)
{
encoderConfig.ProfileGuid = NvEncProfileGuids.HevcMain;
}
else if (_codecGuid == NvEncCodecGuids.Av1)
{
encoderConfig.ProfileGuid = NvEncProfileGuids.Av1Main;
encoderConfig.EncodeCodecConfig.Av1Config.OutputAnnexBFormat = false;
}
// Each mapped texture must finish encoding before this iteration releases it.
encoderConfig.FrameIntervalP = 1;
encoderConfig.RcParams.EnableLookahead = false;
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 = _codecGuid,
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.P1,
EnableEncodeAsync = 0,
EnablePTD = 1,
EnableWeightedPrediction = _codecGuid != NvEncCodecGuids.Av1,
EncodeConfig = p,
TuningInfo = NvEncTuningInfo.HighQuality,
};
encoder.InitializeEncoder(ref initparams);
}
_bitstreamBuffer = encoder.CreateBitstreamBuffer();
_encoder = encoder;
_initialized = true;
return encoder;
}
}