-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathMFTTest.cpp
More file actions
484 lines (366 loc) · 15 KB
/
MFTTest.cpp
File metadata and controls
484 lines (366 loc) · 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
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
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
// MIT License
//
// Copyright 2018 Otto Itkonen
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all
// copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
// SOFTWARE.
// This code demonstrates the use of a hardware H.264 encoder MFT.
// No useful encoding is done, but encoder performance is measured under
// different rates of incoming samples. You may need to modify the sample
// for use with a specific hardware encoder, as it makes a few assumptions
// about the MFT.
// The sample will print performance data to the console in the following format,
// one data point per encoded frame.
// [running time in seconds] [encode time in ms] [capped framerate?]
// Press down F8 (uncapKey) to enable uncapped framerate, i.e. to feed
// a sample into the encoder as soon as the last sample finishes encoding
// instead of adhering to the set framerate (frameRate).
#pragma comment(lib, "D3D11.lib")
#pragma comment(lib, "mfplat.lib")
#pragma comment(lib, "mfuuid.lib")
#pragma comment(lib, "Winmm.lib")
// std
#include <iostream>
#include <string>
// Windows
#include <windows.h>
#include <atlbase.h>
// DirectX
#include <d3d11.h>
// Media Foundation
#include <mfapi.h>
#include <mfplay.h>
#include <mfreadwrite.h>
#include <mferror.h>
#include <Codecapi.h>
// Simplified error handling via macros
#ifdef DEBUG
#define ON_ERROR __debugbreak(); return 1;
#else
#define ON_ERROR system("pause"); return 1;
#endif
#define CHECK(x, err) if (!(x)) { std::cerr << err << std::endl; ON_ERROR; }
#define CHECK_HR(x, err) if (FAILED(x)) { std::cerr << err << std::endl; ON_ERROR; }
// Constants
const int frameRate = 60;
const int surfaceWidth = 1920;
const int surfaceHeight = 1080;
const int uncapKey = VK_F8;
const int quitKey = VK_F9;
int main()
{
HRESULT hr;
CComPtr<ID3D11Device> device;
CComPtr<ID3D11DeviceContext> context;
CComPtr<IMFDXGIDeviceManager> deviceManager;
CComPtr<ID3D11Texture2D> surface;
CComPtr<IMFTransform> transform;
CComPtr<IMFAttributes> attributes;
CComQIPtr<IMFMediaEventGenerator> eventGen;
DWORD inputStreamID;
DWORD outputStreamID;
long long ticksPerSecond;
long long appStartTicks;
long long encStartTicks;
long long ticksPerFrame;
// ------------------------------------------------------------------------
// Initialize Media Foundation & COM
// ------------------------------------------------------------------------
hr = MFStartup(MF_VERSION);
CHECK_HR(hr, "Failed to start Media Foundation");
// ------------------------------------------------------------------------
// Initialize D3D11
// ------------------------------------------------------------------------
// Driver types supported
D3D_DRIVER_TYPE DriverTypes[] =
{
D3D_DRIVER_TYPE_HARDWARE,
D3D_DRIVER_TYPE_WARP,
D3D_DRIVER_TYPE_REFERENCE,
};
UINT NumDriverTypes = ARRAYSIZE(DriverTypes);
// Feature levels supported
D3D_FEATURE_LEVEL FeatureLevels[] =
{
D3D_FEATURE_LEVEL_11_0,
D3D_FEATURE_LEVEL_10_1,
D3D_FEATURE_LEVEL_10_0,
D3D_FEATURE_LEVEL_9_1
};
UINT NumFeatureLevels = ARRAYSIZE(FeatureLevels);
D3D_FEATURE_LEVEL FeatureLevel;
// Create device
for (UINT DriverTypeIndex = 0; DriverTypeIndex < NumDriverTypes; ++DriverTypeIndex)
{
hr = D3D11CreateDevice(nullptr, DriverTypes[DriverTypeIndex], nullptr,
D3D11_CREATE_DEVICE_VIDEO_SUPPORT | D3D11_CREATE_DEVICE_DEBUG,
FeatureLevels, NumFeatureLevels, D3D11_SDK_VERSION, &device, &FeatureLevel, &context);
if (SUCCEEDED(hr))
{
// Device creation success, no need to loop anymore
break;
}
}
CHECK_HR(hr, "Failed to create device");
// Create device manager
UINT resetToken;
hr = MFCreateDXGIDeviceManager(&resetToken, &deviceManager);
CHECK_HR(hr, "Failed to create DXGIDeviceManager");
hr = deviceManager->ResetDevice(device, resetToken);
CHECK_HR(hr, "Failed to assign D3D device to device manager");
// ------------------------------------------------------------------------
// Create surface
// ------------------------------------------------------------------------
D3D11_TEXTURE2D_DESC desc = { 0 };
desc.Format = DXGI_FORMAT_NV12;
desc.Width = surfaceWidth;
desc.Height = surfaceHeight;
desc.MipLevels = 1;
desc.ArraySize = 1;
desc.SampleDesc.Count = 1;
hr = device->CreateTexture2D(&desc, NULL, &surface);
CHECK_HR(hr, "Could not create surface");
// ------------------------------------------------------------------------
// Initialize hardware encoder MFT
// ------------------------------------------------------------------------
// Find encoder
CComHeapPtr<IMFActivate*> activateRaw;
UINT32 activateCount = 0;
// h264 output
MFT_REGISTER_TYPE_INFO info = { MFMediaType_Video, MFVideoFormat_H264 };
UINT32 flags =
MFT_ENUM_FLAG_HARDWARE |
MFT_ENUM_FLAG_SORTANDFILTER;
hr = MFTEnumEx(
MFT_CATEGORY_VIDEO_ENCODER,
flags,
NULL,
&info,
&activateRaw,
&activateCount
);
CHECK_HR(hr, "Failed to enumerate MFTs");
CHECK(activateCount, "No MFTs found");
// Choose the first available encoder
CComPtr<IMFActivate> activate = activateRaw[0]; // <<---------------- Index of MFT we're picking
for (UINT32 i = 0; i < activateCount; i++)
activateRaw[i]->Release();
CComHeapPtr<WCHAR> friendlyName;
UINT32 friendlyNameLength;
hr = activate->GetAllocatedString(MFT_FRIENDLY_NAME_Attribute, &friendlyName, &friendlyNameLength);
CHECK_HR(hr, "Failed to read MFT_FRIENDLY_NAME_Attribute");
std::wcout << static_cast<WCHAR const*>(friendlyName) << std::endl;
// Activate
hr = activate->ActivateObject(IID_PPV_ARGS(&transform));
CHECK_HR(hr, "Failed to activate MFT");
// Get attributes
hr = transform->GetAttributes(&attributes);
CHECK_HR(hr, "Failed to get MFT attributes");
/* NOTE: https://docs.microsoft.com/en-us/windows/win32/medfound/mft-friendly-name-attribute
This attribute is supported by hardware-based MFTs. It is also set on the IMFActivate pointers... (see above)
// Get encoder name
UINT32 nameLength = 0;
std::wstring name;
hr = attributes->GetStringLength(MFT_FRIENDLY_NAME_Attribute, &nameLength);
CHECK_HR(hr, "Failed to get MFT name length");
// IMFAttributes::GetString returns a null-terminated wide string
name.resize(nameLength + 1);
hr = attributes->GetString(MFT_FRIENDLY_NAME_Attribute, &name[0], name.size(), &nameLength);
CHECK_HR(hr, "Failed to get MFT name");
name.resize(nameLength);
std::wcout << name << std::endl;
*/
// Unlock the transform for async use and get event generator
hr = attributes->SetUINT32(MF_TRANSFORM_ASYNC_UNLOCK, TRUE); // <<---------------- Assuming asynchronous MFT without checking (fair, others are filtered out above)
CHECK_HR(hr, "Failed to unlock MFT");
eventGen = transform;
CHECK(eventGen, "Failed to QI for event generator");
// Get stream IDs (expect 1 input and 1 output stream)
hr = transform->GetStreamIDs(1, &inputStreamID, 1, &outputStreamID);
if (hr == E_NOTIMPL)
{
inputStreamID = 0;
outputStreamID = 0;
hr = S_OK;
}
CHECK_HR(hr, "Failed to get stream IDs");
// ------------------------------------------------------------------------
// Configure hardware encoder MFT
// ------------------------------------------------------------------------
// Set D3D manager
hr = transform->ProcessMessage(MFT_MESSAGE_SET_D3D_MANAGER, reinterpret_cast<ULONG_PTR>(deviceManager.p)); // <<-------- Would fail if D3D11 device does not match in hardware to this MFT
CHECK_HR(hr, "Failed to set D3D manager");
// Set low latency hint
hr = attributes->SetUINT32(MF_LOW_LATENCY, TRUE);
CHECK_HR(hr, "Failed to set MF_LOW_LATENCY");
// Set output type
CComPtr<IMFMediaType> outputType;
hr = MFCreateMediaType(&outputType);
CHECK_HR(hr, "Failed to create media type");
hr = outputType->SetGUID(MF_MT_MAJOR_TYPE, MFMediaType_Video);
CHECK_HR(hr, "Failed to set MF_MT_MAJOR_TYPE on H264 output media type");
hr = outputType->SetGUID(MF_MT_SUBTYPE, MFVideoFormat_H264);
CHECK_HR(hr, "Failed to set MF_MT_SUBTYPE on H264 output media type");
hr = outputType->SetUINT32(MF_MT_AVG_BITRATE, 30000000);
CHECK_HR(hr, "Failed to set average bit rate on H264 output media type");
hr = MFSetAttributeSize(outputType, MF_MT_FRAME_SIZE, desc.Width, desc.Height);
CHECK_HR(hr, "Failed to set frame size on H264 MFT out type");
hr = MFSetAttributeRatio(outputType, MF_MT_FRAME_RATE, 60, 1);
CHECK_HR(hr, "Failed to set frame rate on H264 MFT out type");
hr = outputType->SetUINT32(MF_MT_INTERLACE_MODE, 2);
CHECK_HR(hr, "Failed to set MF_MT_INTERLACE_MODE on H.264 encoder MFT");
hr = outputType->SetUINT32(MF_MT_ALL_SAMPLES_INDEPENDENT, TRUE);
CHECK_HR(hr, "Failed to set MF_MT_ALL_SAMPLES_INDEPENDENT on H.264 encoder MFT");
hr = transform->SetOutputType(outputStreamID, outputType, 0);
CHECK_HR(hr, "Failed to set output media type on H.264 encoder MFT");
// Set input type
CComPtr<IMFMediaType> inputType;
hr = MFCreateMediaType(&inputType);
CHECK_HR(hr, "Failed to create media type");
for (DWORD i = 0;; i++)
{
inputType = nullptr;
hr = transform->GetInputAvailableType(inputStreamID, i, &inputType);
CHECK_HR(hr, "Failed to get input type");
hr = inputType->SetGUID(MF_MT_MAJOR_TYPE, MFMediaType_Video);
CHECK_HR(hr, "Failed to set MF_MT_MAJOR_TYPE on H264 MFT input type");
hr = inputType->SetGUID(MF_MT_SUBTYPE, MFVideoFormat_NV12);
CHECK_HR(hr, "Failed to set MF_MT_SUBTYPE on H264 MFT input type");
hr = MFSetAttributeSize(inputType, MF_MT_FRAME_SIZE, desc.Width, desc.Height);
CHECK_HR(hr, "Failed to set MF_MT_FRAME_SIZE on H264 MFT input type");
hr = MFSetAttributeRatio(inputType, MF_MT_FRAME_RATE, 60, 1);
CHECK_HR(hr, "Failed to set MF_MT_FRAME_RATE on H264 MFT input type");
hr = transform->SetInputType(inputStreamID, inputType, 0);
CHECK_HR(hr, "Failed to set input type");
break;
}
// ------------------------------------------------------------------------
// Start encoding
// ------------------------------------------------------------------------
// Initialize timer
timeBeginPeriod(1);
LARGE_INTEGER ticksInt;
long long ticks;
QueryPerformanceFrequency(&ticksInt);
ticksPerSecond = ticksInt.QuadPart;
QueryPerformanceCounter(&ticksInt);
appStartTicks = ticksInt.QuadPart;
ticksPerFrame = ticksPerSecond / frameRate;
// Start encoder
hr = transform->ProcessMessage(MFT_MESSAGE_COMMAND_FLUSH, NULL);
CHECK_HR(hr, "Failed to process FLUSH command on H.264 MFT");
hr = transform->ProcessMessage(MFT_MESSAGE_NOTIFY_BEGIN_STREAMING, NULL);
CHECK_HR(hr, "Failed to process BEGIN_STREAMING command on H.264 MFT");
hr = transform->ProcessMessage(MFT_MESSAGE_NOTIFY_START_OF_STREAM, NULL);
CHECK_HR(hr, "Failed to process START_OF_STREAM command on H.264 MFT");
// Main encode loop
// Assume that METransformNeedInput and METransformHaveOutput are sent in a regular alternating pattern.
// Otherwise a queue is needed for performance measurement.
bool encoding = false;
bool throttle = false;
while (!(GetAsyncKeyState(quitKey) & (1 << 15)))
{
// Get next event
CComPtr<IMFMediaEvent> event;
hr = eventGen->GetEvent(0, &event);
CHECK_HR(hr, "Failed to get next event");
MediaEventType eventType;
hr = event->GetType(&eventType);
CHECK_HR(hr, "Failed to get event type");
switch (eventType)
{
case METransformNeedInput:
CHECK(!encoding, "Expected METransformHaveOutput");
encoding = true;
{
throttle = !(GetAsyncKeyState(uncapKey) & (1 << 15));
if (throttle)
{
// Calculate next frame time by quantizing time to the next value divisble by ticksPerFrame
QueryPerformanceCounter(&ticksInt);
ticks = ticksInt.QuadPart;
long long nextFrameTicks = (ticks / ticksPerFrame + 1) * ticksPerFrame;
// Wait for next frame
while (ticks < nextFrameTicks)
{
// Not accurate, but enough for this purpose
Sleep(1);
QueryPerformanceCounter(&ticksInt);
ticks = ticksInt.QuadPart;
}
}
// Create buffer
CComPtr<IMFMediaBuffer> inputBuffer;
hr = MFCreateDXGISurfaceBuffer(__uuidof(ID3D11Texture2D), surface, 0, FALSE, &inputBuffer);
CHECK_HR(hr, "Failed to create IMFMediaBuffer");
// Create sample
CComPtr<IMFSample> sample;
hr = MFCreateSample(&sample);
CHECK_HR(hr, "Failed to create IMFSample");
hr = sample->AddBuffer(inputBuffer);
CHECK_HR(hr, "Failed to add buffer to IMFSample");
// Start measuring encode time
QueryPerformanceCounter(&ticksInt);
encStartTicks = ticksInt.QuadPart;
hr = transform->ProcessInput(inputStreamID, sample, 0);
CHECK_HR(hr, "Failed to process input");
}
break;
case METransformHaveOutput:
CHECK(encoding, "Expected METransformNeedInput");
encoding = false;
{
DWORD status;
MFT_OUTPUT_DATA_BUFFER outputBuffer;
outputBuffer.dwStreamID = outputStreamID;
outputBuffer.pSample = nullptr;
outputBuffer.dwStatus = 0;
outputBuffer.pEvents = nullptr;
hr = transform->ProcessOutput(0, 1, &outputBuffer, &status);
CHECK_HR(hr, "ProcessOutput failed");
// Stop measuring encode time
QueryPerformanceCounter(&ticksInt);
ticks = ticksInt.QuadPart;
long double encTime_ms = (ticks - encStartTicks) * 1000 / (long double)ticksPerSecond;
long double appTime_s = (encStartTicks - appStartTicks) / (long double)ticksPerSecond;
// Report data
std::cout << appTime_s << " " << encTime_ms << " " << throttle << std::endl;
// Release sample as it is not processed any further.
if (outputBuffer.pSample)
outputBuffer.pSample->Release();
if (outputBuffer.pEvents)
outputBuffer.pEvents->Release();
CHECK_HR(hr, "Failed to process output");
}
break;
default:
CHECK(false, "Unknown event");
break;
}
}
// ------------------------------------------------------------------------
// Finish encoding
// ------------------------------------------------------------------------
hr = transform->ProcessMessage(MFT_MESSAGE_NOTIFY_END_OF_STREAM, NULL);
CHECK_HR(hr, "Failed to process END_OF_STREAM command on H.264 MFT");
hr = transform->ProcessMessage(MFT_MESSAGE_NOTIFY_END_STREAMING, NULL);
CHECK_HR(hr, "Failed to process END_STREAMING command on H.264 MFT");
hr = transform->ProcessMessage(MFT_MESSAGE_COMMAND_FLUSH, NULL);
CHECK_HR(hr, "Failed to process FLUSH command on H.264 MFT");
return 0;
}