FreeRDP
Loading...
Searching...
No Matches
h264_mf.c
1
19
20#include <winpr/winpr.h>
21#include <winpr/library.h>
22
23#include <freerdp/log.h>
24#include <freerdp/codec/h264.h>
25
26#include <ks.h>
27#include <codecapi.h>
28
29#include <mfapi.h>
30#include <mferror.h>
31#include <wmcodecdsp.h>
32#include <mftransform.h>
33
34#include "h264.h"
35
36#define TAG FREERDP_TAG("codec")
37
38static const GUID sCLSID_CMSH264DecoderMFT = {
39 0x62CE7E72, 0x4C71, 0x4d20, { 0xB1, 0x5D, 0x45, 0x28, 0x31, 0xA8, 0x7D, 0x9D }
40};
41static const GUID sIID_IMFTransform = {
42 0xbf94c121, 0x5b05, 0x4e6f, { 0x80, 0x00, 0xba, 0x59, 0x89, 0x61, 0x41, 0x4d }
43};
44static const GUID sMF_MT_MAJOR_TYPE = {
45 0x48eba18e, 0xf8c9, 0x4687, { 0xbf, 0x11, 0x0a, 0x74, 0xc9, 0xf9, 0x6a, 0x8f }
46};
47static const GUID sMF_MT_FRAME_SIZE = {
48 0x1652c33d, 0xd6b2, 0x4012, { 0xb8, 0x34, 0x72, 0x03, 0x08, 0x49, 0xa3, 0x7d }
49};
50static const GUID sMF_MT_DEFAULT_STRIDE = {
51 0x644b4e48, 0x1e02, 0x4516, { 0xb0, 0xeb, 0xc0, 0x1c, 0xa9, 0xd4, 0x9a, 0xc6 }
52};
53static const GUID sMF_MT_SUBTYPE = {
54 0xf7e34c9a, 0x42e8, 0x4714, { 0xb7, 0x4b, 0xcb, 0x29, 0xd7, 0x2c, 0x35, 0xe5 }
55};
56static const GUID sMFMediaType_Video = {
57 0x73646976, 0x0000, 0x0010, { 0x80, 0x00, 0x00, 0xAA, 0x00, 0x38, 0x9B, 0x71 }
58};
59static const GUID sMFVideoFormat_H264 = {
60 0x34363248, 0x0000, 0x0010, { 0x80, 0x00, 0x00, 0xaa, 0x00, 0x38, 0x9b, 0x71 }
61};
62static const GUID sMFVideoFormat_IYUV = {
63 0x56555949, 0x0000, 0x0010, { 0x80, 0x00, 0x00, 0xaa, 0x00, 0x38, 0x9b, 0x71 }
64};
65static const GUID sMFVideoFormat_HEVC = {
66 0x43564548, 0x0000, 0x0010, { 0x80, 0x00, 0x00, 0xaa, 0x00, 0x38, 0x9b, 0x71 }
67};
68static const GUID sMFT_CATEGORY_VIDEO_DECODER = {
69 0xd6c02d4b, 0x6833, 0x45b4, { 0x97, 0x1a, 0x05, 0xa4, 0xb0, 0x4b, 0xab, 0x91 }
70};
71static const GUID sIID_ICodecAPI = {
72 0x901db4c7, 0x31ce, 0x41a2, { 0x85, 0xdc, 0x8f, 0xa0, 0xbf, 0x41, 0xb8, 0xda }
73};
74static const GUID sCODECAPI_AVLowLatencyMode = {
75 0x9c27891a, 0xed7a, 0x40e1, { 0x88, 0xe8, 0xb2, 0x27, 0x27, 0xa0, 0x24, 0xee }
76};
77
78/* encoder */
79static const GUID sCLSID_CMSH264EncoderMFT = {
80 0x6ca50344, 0x051a, 0x4ded, { 0x97, 0x79, 0xa4, 0x33, 0x05, 0x16, 0x5e, 0x35 }
81};
82static const GUID sMFVideoFormat_NV12 = {
83 0x3231564e, 0x0000, 0x0010, { 0x80, 0x00, 0x00, 0xaa, 0x00, 0x38, 0x9b, 0x71 }
84};
85static const GUID sMF_MT_FRAME_RATE = {
86 0xc459a2e8, 0x3d2c, 0x4e44, { 0xb1, 0x32, 0xfe, 0xe5, 0x15, 0x6c, 0x7b, 0xb0 }
87};
88static const GUID sMF_MT_PIXEL_ASPECT_RATIO = {
89 0xc6376a1e, 0x8d0a, 0x4027, { 0xbe, 0x45, 0x6d, 0x9a, 0x0a, 0xd3, 0x9b, 0xb6 }
90};
91static const GUID sMF_MT_INTERLACE_MODE = {
92 0xe2724bb8, 0xe676, 0x4806, { 0xb4, 0xb2, 0xa8, 0xd6, 0xef, 0xb4, 0x4c, 0xcd }
93};
94static const GUID sMF_MT_AVG_BITRATE = {
95 0x20332624, 0xfb0d, 0x4d9e, { 0xbd, 0x0d, 0xcb, 0xf6, 0x78, 0x6c, 0x10, 0x2e }
96};
97static const GUID sMF_MT_MPEG2_PROFILE = {
98 0xad76a80b, 0x2d5c, 0x4e0b, { 0xb3, 0x75, 0x64, 0xe5, 0x20, 0x13, 0x70, 0x36 }
99};
100static const GUID sCODECAPI_AVEncCommonRateControlMode = {
101 0x1c0608e9, 0x370c, 0x4710, { 0x8a, 0x58, 0xcb, 0x61, 0x81, 0xc4, 0x24, 0x23 }
102};
103static const GUID sCODECAPI_AVEncCommonMeanBitRate = {
104 0xf7222374, 0x2144, 0x4815, { 0xb5, 0x50, 0xa3, 0x7f, 0x8e, 0x12, 0xee, 0x52 }
105};
106static const GUID sCODECAPI_AVEncCommonQuality = {
107 0xfcbf57a3, 0x7ea5, 0x4b0c, { 0x96, 0x44, 0x69, 0xb4, 0x0c, 0x39, 0xc3, 0x91 }
108};
109static const GUID sCODECAPI_AVEncVideoEncodeQP = {
110 0x2cb5696b, 0x23fb, 0x4ce1, { 0xa0, 0xf9, 0xef, 0x5b, 0x90, 0xfd, 0x55, 0xca }
111};
112static const GUID sCODECAPI_AVEncMPVGOPSize = {
113 0x95f31b26, 0x95a4, 0x41aa, { 0x93, 0x03, 0x24, 0x6a, 0x7f, 0xc6, 0xee, 0xf1 }
114};
115
116/* values from codecapi.h and mfobjects.h, spelled out like the GUIDs above */
117#define FREERDP_MF_RC_CBR 0 /* eAVEncCommonRateControlMode_CBR */
118#define FREERDP_MF_RC_QUALITY 3 /* eAVEncCommonRateControlMode_Quality */
119#define FREERDP_MF_PROFILE_BASELINE 66 /* eAVEncH264VProfile_Base */
120#define FREERDP_MF_INTERLACE_PROGRESSIVE 2 /* MFVideoInterlace_Progressive */
121
122typedef HRESULT(__stdcall* pfnMFStartup)(ULONG Version, DWORD dwFlags);
123typedef HRESULT(__stdcall* pfnMFShutdown)(void);
124typedef HRESULT(__stdcall* pfnMFCreateSample)(IMFSample** ppIMFSample);
125typedef HRESULT(__stdcall* pfnMFCreateMemoryBuffer)(DWORD cbMaxLength, IMFMediaBuffer** ppBuffer);
126typedef HRESULT(__stdcall* pfnMFCreateMediaType)(IMFMediaType** ppMFType);
127typedef HRESULT(__stdcall* pfnMFTEnumEx)(GUID guidCategory, UINT32 Flags,
128 const MFT_REGISTER_TYPE_INFO* pInputType,
129 const MFT_REGISTER_TYPE_INFO* pOutputType,
130 IMFActivate*** pppMFTActivate, UINT32* pnumMFTActivate);
131
132typedef struct
133{
134 ICodecAPI* codecApi;
135 IMFTransform* transform;
136 IMFMediaType* inputType;
137 IMFMediaType* outputType;
138 IMFSample* sample;
139 UINT32 frameWidth;
140 UINT32 frameHeight;
141 IMFSample* outputSample;
142 IMFMediaBuffer* outputBuffer;
143 HMODULE mfplat;
144 pfnMFStartup MFStartup;
145 pfnMFShutdown MFShutdown;
146 pfnMFCreateSample MFCreateSample;
147 pfnMFCreateMemoryBuffer MFCreateMemoryBuffer;
148 pfnMFCreateMediaType MFCreateMediaType;
149 pfnMFTEnumEx MFTEnumEx;
150 UINT32 stride;
151 BOOL bottomUp;
152 BOOL nv12; /* decoder output is NV12 (interleaved chroma) instead of IYUV */
153 LONGLONG decSampleTime;
154 BOOL hevcAudSent; /* the last input ended with the access unit delimiter of the next frame */
155
156 /* encoder state: the media types are set on the first frame and again on a size change */
157 BOOL encStreaming;
158 UINT32 encWidth;
159 UINT32 encHeight;
160 UINT32 encFrameRate;
161 UINT32 encBitRate;
162 UINT32 encQP;
163 H264_RATECONTROL_MODE encRateControl;
164 DWORD encOutputFlags;
165 DWORD encOutputSize;
166 LONGLONG encSampleTime;
167 BYTE* encData;
168 size_t encDataSize;
169 size_t encDataLength;
170 UINT32 encHeld;
171 BOOL encWarned;
172} H264_CONTEXT_MF;
173
174WINPR_ATTR_NODISCARD
175static HRESULT mf_find_output_type(H264_CONTEXT_MF* sys, const GUID* guid,
176 IMFMediaType** ppMediaType)
177{
178 DWORD idx = 0;
179 GUID mediaGuid = WINPR_C_ARRAY_INIT;
180 HRESULT hr = S_OK;
181 IMFMediaType* pMediaType = nullptr;
182
183 WINPR_ASSERT(sys);
184 WINPR_ASSERT(sys->transform);
185 WINPR_ASSERT(guid);
186 WINPR_ASSERT(ppMediaType);
187
188 while (1)
189 {
190 hr = sys->transform->lpVtbl->GetOutputAvailableType(sys->transform, 0, idx, &pMediaType);
191
192 if (FAILED(hr))
193 break;
194
195 /* a type without a subtype can't be the one we look for, try the next */
196 if (SUCCEEDED(pMediaType->lpVtbl->GetGUID(pMediaType, &sMF_MT_SUBTYPE, &mediaGuid)) &&
197 IsEqualGUID(&mediaGuid, guid))
198 {
199 *ppMediaType = pMediaType;
200 return S_OK;
201 }
202
203 pMediaType->lpVtbl->Release(pMediaType);
204 idx++;
205 }
206
207 return hr;
208}
209
210/* The H264 decoder offers IYUV, HEVC decoders (HEVC Video Extensions) usually only NV12 */
211WINPR_ATTR_NODISCARD
212static HRESULT mf_select_output_type(H264_CONTEXT_MF* sys)
213{
214 WINPR_ASSERT(sys);
215
216 if (sys->outputType)
217 {
218 sys->outputType->lpVtbl->Release(sys->outputType);
219 sys->outputType = nullptr;
220 }
221
222 HRESULT hr = mf_find_output_type(sys, &sMFVideoFormat_IYUV, &sys->outputType);
223 sys->nv12 = FALSE;
224 if (FAILED(hr))
225 {
226 hr = mf_find_output_type(sys, &sMFVideoFormat_NV12, &sys->outputType);
227 sys->nv12 = SUCCEEDED(hr);
228 }
229 if (FAILED(hr))
230 return hr;
231
232 return sys->transform->lpVtbl->SetOutputType(sys->transform, 0, sys->outputType, 0);
233}
234
235WINPR_ATTR_NODISCARD
236static HRESULT mf_create_output_sample(H264_CONTEXT* h264, H264_CONTEXT_MF* sys)
237{
238 HRESULT hr = S_OK;
239 MFT_OUTPUT_STREAM_INFO streamInfo;
240
241 WINPR_ASSERT(h264);
242 WINPR_ASSERT(sys);
243 WINPR_ASSERT(sys->transform);
244
245 if (sys->outputSample)
246 {
247 sys->outputSample->lpVtbl->Release(sys->outputSample);
248 sys->outputSample = nullptr;
249 }
250
251 hr = sys->MFCreateSample(&sys->outputSample);
252
253 if (FAILED(hr))
254 {
255 WLog_Print(h264->log, WLOG_ERROR, "MFCreateSample failure: 0x%08" PRIX32 "", hr);
256 goto error;
257 }
258
259 hr = sys->transform->lpVtbl->GetOutputStreamInfo(sys->transform, 0, &streamInfo);
260
261 if (FAILED(hr))
262 {
263 WLog_Print(h264->log, WLOG_ERROR, "GetOutputStreamInfo failure: 0x%08" PRIX32 "", hr);
264 goto error;
265 }
266
267 hr = sys->MFCreateMemoryBuffer(streamInfo.cbSize, &sys->outputBuffer);
268
269 if (FAILED(hr))
270 {
271 WLog_Print(h264->log, WLOG_ERROR, "MFCreateMemoryBuffer failure: 0x%08" PRIX32 "", hr);
272 goto error;
273 }
274
275 hr = sys->outputSample->lpVtbl->AddBuffer(sys->outputSample, sys->outputBuffer);
276
277 if (FAILED(hr))
278 {
279 WLog_Print(h264->log, WLOG_ERROR, "AddBuffer failure: 0x%08" PRIX32 "", hr);
280 goto error;
281 }
282
283 sys->outputBuffer->lpVtbl->Release(sys->outputBuffer);
284error:
285 return hr;
286}
287
288/* IYUV output: full size Y plane followed by the quarter size U and V planes
289 * NV12 output: full size Y plane followed by one half height plane of interleaved U/V samples,
290 * plane 1 addresses it, plane 2 is not used */
291WINPR_ATTR_NODISCARD
292static size_t getSrcOffset(const H264_CONTEXT_MF* sys, UINT32 line, size_t plane)
293{
294 WINPR_ASSERT(sys);
295
296 if (sys->nv12)
297 {
298 WINPR_ASSERT(plane < 2);
299 const size_t height = (plane == 0) ? sys->frameHeight : sys->frameHeight / 2u;
300 const size_t offset = (plane == 0) ? 0 : (size_t)sys->stride * sys->frameHeight;
301 WINPR_ASSERT(line < height);
302 const size_t row = sys->bottomUp ? height - line - 1u : line;
303 return offset + row * sys->stride;
304 }
305
306 const size_t stride = (plane == 0) ? sys->stride : sys->stride / 2u;
307 const size_t height = (plane == 0) ? sys->frameHeight : sys->frameHeight / 2u;
308 size_t offset = 0;
309 if (plane > 0)
310 offset += (size_t)sys->stride * sys->frameHeight;
311 if (plane > 1)
312 offset += stride * height;
313
314 WINPR_ASSERT(line < height);
315 const size_t row = sys->bottomUp ? height - line - 1u : line;
316 return offset + row * stride;
317}
318
319WINPR_ATTR_NODISCARD
320static HRESULT mf_process_output(H264_CONTEXT_MF* sys)
321{
322 DWORD status = 0;
323 MFT_OUTPUT_DATA_BUFFER buffer = WINPR_C_ARRAY_INIT;
324
325 WINPR_ASSERT(sys);
326 WINPR_ASSERT(sys->transform);
327
328 buffer.pSample = sys->outputSample;
329 const HRESULT hr =
330 sys->transform->lpVtbl->ProcessOutput(sys->transform, 0, 1, &buffer, &status);
331 if (buffer.pEvents)
332 buffer.pEvents->lpVtbl->Release(buffer.pEvents);
333 return hr;
334}
335
336/* HEVC access unit delimiter NAL (type 35, pic_type 2), as Windows servers start every frame */
337static const BYTE sHevcAud[] = { 0x00, 0x00, 0x00, 0x01, 0x46, 0x01, 0x50 };
338
339/* @return the length of an access unit delimiter NAL at the start of data, 0 if there is none */
340WINPR_ATTR_NODISCARD
341static size_t mf_hevc_aud_length(const BYTE* data, size_t length)
342{
343 size_t sc = 0;
344 if ((length >= 4) && (data[0] == 0) && (data[1] == 0) && (data[2] == 0) && (data[3] == 1))
345 sc = 4;
346 else if ((length >= 3) && (data[0] == 0) && (data[1] == 0) && (data[2] == 1))
347 sc = 3;
348
349 /* start code, 2 byte NAL header, 1 byte pic_type + rbsp stop bit */
350 if ((sc == 0) || (length < sc + 3) || (((data[sc] >> 1) & 0x3F) != 35))
351 return 0;
352 return sc + 3;
353}
354
355WINPR_ATTR_NODISCARD
356static int mf_decompress(H264_CONTEXT* WINPR_RESTRICT h264, const BYTE* WINPR_RESTRICT pSrcData,
357 UINT32 SrcSize)
358{
359 int rc = -1;
360 BYTE* pbBuffer = nullptr;
361 DWORD cbMaxLength = 0;
362 DWORD cbCurrentLength = 0;
363 IMFSample* inputSample = nullptr;
364 IMFMediaBuffer* inputBuffer = nullptr;
365 IMFMediaBuffer* outputBuffer = nullptr;
366
367 WINPR_ASSERT(h264);
368 WINPR_ASSERT(pSrcData);
369
370 H264_CONTEXT_MF* sys = (H264_CONTEXT_MF*)h264->pSystemData;
371 WINPR_ASSERT(sys);
372 UINT32* iStride = h264->iStride;
373 BYTE** pYUVData = h264->pYUVData;
374
375 /* The HEVC decoder only finishes a picture when the next access unit starts, which would
376 * show every frame one update late. RDP sends one complete frame per surface command:
377 * end each input with the delimiter of the next access unit and drop the delimiter the
378 * next frame starts with, the decoder sees the same bitstream split at other places. */
379 const BYTE* src = pSrcData;
380 UINT32 srcLength = SrcSize;
381 UINT32 appendLength = 0;
382 if (h264->hevc)
383 {
384 if (sys->hevcAudSent)
385 {
386 const size_t skip = mf_hevc_aud_length(pSrcData, SrcSize);
387 src += skip;
388 srcLength -= (UINT32)skip;
389 }
390 if (srcLength > UINT32_MAX - sizeof(sHevcAud))
391 return -1;
392 appendLength = sizeof(sHevcAud);
393 }
394
395 HRESULT hr = sys->MFCreateMemoryBuffer(srcLength + appendLength, &inputBuffer);
396
397 if (FAILED(hr))
398 {
399 WLog_Print(h264->log, WLOG_ERROR, "MFCreateMemoryBuffer failure: 0x%08" PRIX32 "", hr);
400 goto error;
401 }
402
403 hr = inputBuffer->lpVtbl->Lock(inputBuffer, &pbBuffer, &cbMaxLength, &cbCurrentLength);
404
405 if (FAILED(hr))
406 {
407 WLog_Print(h264->log, WLOG_ERROR, "Lock failure: 0x%08" PRIX32 "", hr);
408 goto error;
409 }
410
411 CopyMemory(pbBuffer, src, srcLength);
412 if (appendLength > 0)
413 CopyMemory(&pbBuffer[srcLength], sHevcAud, appendLength);
414 hr = inputBuffer->lpVtbl->SetCurrentLength(inputBuffer, srcLength + appendLength);
415
416 if (FAILED(hr))
417 {
418 WLog_Print(h264->log, WLOG_ERROR, "SetCurrentLength failure: 0x%08" PRIX32 "", hr);
419 goto error;
420 }
421
422 hr = inputBuffer->lpVtbl->Unlock(inputBuffer);
423
424 if (FAILED(hr))
425 {
426 WLog_Print(h264->log, WLOG_ERROR, "Unlock failure: 0x%08" PRIX32 "", hr);
427 goto error;
428 }
429
430 hr = sys->MFCreateSample(&inputSample);
431
432 if (FAILED(hr))
433 {
434 WLog_Print(h264->log, WLOG_ERROR, "MFCreateSample failure: 0x%08" PRIX32 "", hr);
435 goto error;
436 }
437
438 hr = inputSample->lpVtbl->AddBuffer(inputSample, inputBuffer);
439
440 if (FAILED(hr))
441 {
442 WLog_Print(h264->log, WLOG_ERROR, "AddBuffer failure: 0x%08" PRIX32 "", hr);
443 goto error;
444 }
445
446 /* some decoders (HEVC) want time stamps, RDP has none: count in 30 fps steps (100ns units) */
447 (void)inputSample->lpVtbl->SetSampleTime(inputSample, sys->decSampleTime);
448 (void)inputSample->lpVtbl->SetSampleDuration(inputSample, 333333);
449 sys->decSampleTime += 333333;
450
451 hr = sys->transform->lpVtbl->ProcessInput(sys->transform, 0, inputSample, 0);
452
453 if (FAILED(hr))
454 {
455 WLog_Print(h264->log, WLOG_ERROR, "ProcessInput failure: 0x%08" PRIX32 "", hr);
456 goto error;
457 }
458 sys->hevcAudSent = (appendLength > 0);
459
460 hr = mf_create_output_sample(h264, sys);
461
462 if (FAILED(hr))
463 {
464 WLog_Print(h264->log, WLOG_ERROR, "mf_create_output_sample failure: 0x%08" PRIX32 "", hr);
465 goto error;
466 }
467
468 hr = mf_process_output(sys);
469
470 if (hr == MF_E_TRANSFORM_STREAM_CHANGE)
471 {
472 UINT64 frameSize = 0;
473
474 hr = mf_select_output_type(sys);
475
476 if (FAILED(hr))
477 {
478 WLog_Print(h264->log, WLOG_ERROR, "mf_select_output_type failure: 0x%08" PRIX32 "", hr);
479 goto error;
480 }
481
482 hr = mf_create_output_sample(h264, sys);
483
484 if (FAILED(hr))
485 {
486 WLog_Print(h264->log, WLOG_ERROR, "mf_create_output_sample failure: 0x%08" PRIX32 "",
487 hr);
488 goto error;
489 }
490
491 hr = sys->outputType->lpVtbl->GetUINT64(sys->outputType, &sMF_MT_FRAME_SIZE, &frameSize);
492
493 if (FAILED(hr))
494 {
495 WLog_Print(h264->log, WLOG_ERROR,
496 "GetUINT64(MF_MT_FRAME_SIZE) failure: 0x%08" PRIX32 "", hr);
497 goto error;
498 }
499
500 sys->frameWidth = (UINT32)(frameSize >> 32);
501 sys->frameHeight = (UINT32)frameSize;
502 hr = sys->outputType->lpVtbl->GetUINT32(sys->outputType, &sMF_MT_DEFAULT_STRIDE,
503 &sys->stride);
504
505 if (FAILED(hr) && sys->nv12)
506 {
507 /* NV12 is a planar 8 bit format, the stride defaults to the width */
508 sys->stride = sys->frameWidth;
509 hr = S_OK;
510 }
511
512 if (FAILED(hr))
513 {
514 WLog_Print(h264->log, WLOG_ERROR,
515 "GetUINT32(MF_MT_DEFAULT_STRIDE) failure: 0x%08" PRIX32 "", hr);
516 goto error;
517 }
518
519 const INT32 istride = (INT32)sys->stride;
520 sys->bottomUp = (istride < 0);
521 if (sys->bottomUp)
522 sys->stride = istride * -1;
523
524 if (!avc420_ensure_buffer(h264, sys->stride, sys->frameWidth, sys->frameHeight))
525 goto error;
526
527 /* the decoder still holds the frame, fetch it with the new output type */
528 hr = mf_process_output(sys);
529 }
530
531 if (hr == MF_E_TRANSFORM_NEED_MORE_INPUT)
532 rc = 0;
533 else if (FAILED(hr))
534 {
535 WLog_Print(h264->log, WLOG_ERROR, "ProcessOutput failure: 0x%08" PRIX32 "", hr);
536 goto error;
537 }
538 else
539 {
540 BYTE* buffer = nullptr;
541 DWORD bufferCount = 0;
542 DWORD cbMaxLength = 0;
543 DWORD cbCurrentLength = 0;
544 hr = sys->outputSample->lpVtbl->GetBufferCount(sys->outputSample, &bufferCount);
545
546 if (FAILED(hr))
547 {
548 WLog_Print(h264->log, WLOG_ERROR, "GetBufferCount failure: 0x%08" PRIX32 "", hr);
549 goto error;
550 }
551
552 hr = sys->outputSample->lpVtbl->GetBufferByIndex(sys->outputSample, 0, &outputBuffer);
553
554 if (FAILED(hr))
555 {
556 WLog_Print(h264->log, WLOG_ERROR, "GetBufferByIndex failure: 0x%08" PRIX32 "", hr);
557 goto error;
558 }
559
560 hr = outputBuffer->lpVtbl->Lock(outputBuffer, &buffer, &cbMaxLength, &cbCurrentLength);
561
562 if (FAILED(hr))
563 {
564 WLog_Print(h264->log, WLOG_ERROR, "Lock failure: 0x%08" PRIX32 "", hr);
565 goto error;
566 }
567
568 if ((sys->stride == 0) || (cbCurrentLength / 3u / sys->stride < sys->frameHeight / 2u))
569 {
570 WLog_Print(h264->log, WLOG_ERROR, "output buffer too small: %" PRIu32 "",
571 cbCurrentLength);
572 (void)outputBuffer->lpVtbl->Unlock(outputBuffer);
573 goto error;
574 }
575
576 /* Copy data from decoder buffer to our YUV buffer.
577 * strides differ (the YUV buffer is always larger) so copy only data available from the
578 * decoder buffer but increment the YUV buffer with the YUV buffer strides.
579 */
580 for (UINT32 x = 0; x < sys->frameHeight; x++)
581 {
582 const size_t srcOffset = getSrcOffset(sys, x, 0);
583 const UINT32 dstOffset = (UINT32)iStride[0] * x;
584 CopyMemory(&pYUVData[0][dstOffset], &buffer[srcOffset], sys->stride);
585 }
586 for (UINT32 x = 0; x < sys->frameHeight / 2; x++)
587 {
588 const UINT32 dstUOffset = (UINT32)iStride[1] * x;
589 const UINT32 dstVOffset = (UINT32)iStride[2] * x;
590
591 if (sys->nv12)
592 {
593 const BYTE* uv = &buffer[getSrcOffset(sys, x, 1)];
594 BYTE* u = &pYUVData[1][dstUOffset];
595 BYTE* v = &pYUVData[2][dstVOffset];
596 for (UINT32 y = 0; y < sys->stride / 2ull; y++)
597 {
598 u[y] = uv[2ull * y];
599 v[y] = uv[2ull * y + 1ull];
600 }
601 }
602 else
603 {
604 const size_t srcUOffset = getSrcOffset(sys, x, 1);
605 const size_t srcVOffset = getSrcOffset(sys, x, 2);
606 CopyMemory(&pYUVData[1][dstUOffset], &buffer[srcUOffset], sys->stride / 2ull);
607 CopyMemory(&pYUVData[2][dstVOffset], &buffer[srcVOffset], sys->stride / 2ull);
608 }
609 }
610
611 hr = outputBuffer->lpVtbl->Unlock(outputBuffer);
612
613 if (FAILED(hr))
614 {
615 WLog_Print(h264->log, WLOG_ERROR, "Unlock failure: 0x%08" PRIX32 "", hr);
616 goto error;
617 }
618
619 h264->YUVWidth = sys->frameWidth;
620 h264->YUVHeight = sys->frameHeight;
621 rc = 1;
622 }
623
624error:
625 if (outputBuffer)
626 outputBuffer->lpVtbl->Release(outputBuffer);
627 if (inputSample)
628 inputSample->lpVtbl->Release(inputSample);
629 if (inputBuffer)
630 inputBuffer->lpVtbl->Release(inputBuffer);
631 if (rc < 0)
632 WLog_Print(h264->log, WLOG_ERROR, "decompression failed");
633 return rc;
634}
635
636WINPR_ATTR_NODISCARD
637static HRESULT mf_encoder_set_value(H264_CONTEXT* h264, H264_CONTEXT_MF* sys, const GUID* guid,
638 const char* name, VARTYPE vt, UINT64 value)
639{
640 VARIANT var = WINPR_C_ARRAY_INIT;
641
642 WINPR_ASSERT(h264);
643 WINPR_ASSERT(sys);
644 WINPR_ASSERT(guid);
645 WINPR_ASSERT(name);
646
647 if (!sys->codecApi)
648 return E_NOINTERFACE;
649
650 var.n1.n2.vt = vt;
651 if (vt == VT_UI8)
652 var.n1.n2.n3.ullVal = value;
653 else if (vt == VT_BOOL)
654 var.n1.n2.n3.boolVal = value ? VARIANT_TRUE : VARIANT_FALSE;
655 else
656 var.n1.n2.n3.ulVal = (ULONG)value;
657
658 const HRESULT hr = sys->codecApi->lpVtbl->SetValue(sys->codecApi, guid, &var);
659 if (FAILED(hr))
660 WLog_Print(h264->log, WLOG_DEBUG, "ICodecAPI::SetValue(%s) failure: 0x%08" PRIX32 "", name,
661 (UINT32)hr);
662 return hr;
663}
664
665/* Every ICodecAPI property below tunes the encoder on top of its media types, which carry what
666 * the stream needs (size, frame rate, bit rate, profile). An encoder without a property keeps
667 * its default and still produces a valid stream, so that is not an error: an encoder without
668 * ICodecAPI (E_NOINTERFACE here), or Wine's, which answers E_NOTIMPL to every property. An
669 * encoder that has the property (IsSupported) but refuses our value is an error. */
670WINPR_ATTR_NODISCARD
671static BOOL mf_encoder_check_value(H264_CONTEXT* h264, H264_CONTEXT_MF* sys, const GUID* guid,
672 const char* name, HRESULT hr)
673{
674 WINPR_ASSERT(h264);
675 WINPR_ASSERT(sys);
676 WINPR_ASSERT(guid);
677 WINPR_ASSERT(name);
678
679 if (SUCCEEDED(hr))
680 return TRUE;
681
682 if ((hr != E_NOTIMPL) && (hr != E_NOINTERFACE) && sys->codecApi &&
683 (sys->codecApi->lpVtbl->IsSupported(sys->codecApi, guid) == S_OK))
684 {
685 WLog_Print(h264->log, WLOG_ERROR,
686 "H264 encoder refuses ICodecAPI property %s: 0x%08" PRIX32 "", name, (UINT32)hr);
687 return FALSE;
688 }
689
690 WLog_Print(h264->log, WLOG_DEBUG, "H264 encoder does not support %s, using its default", name);
691 return TRUE;
692}
693
694WINPR_ATTR_NODISCARD
695static BOOL mf_encoder_set_optional(H264_CONTEXT* h264, H264_CONTEXT_MF* sys, const GUID* guid,
696 const char* name, VARTYPE vt, UINT64 value)
697{
698 const HRESULT hr = mf_encoder_set_value(h264, sys, guid, name, vt, value);
699 return mf_encoder_check_value(h264, sys, guid, name, hr);
700}
701
702static void mf_encoder_release(H264_CONTEXT_MF* sys)
703{
704 WINPR_ASSERT(sys);
705
706 if (sys->outputSample)
707 {
708 sys->outputSample->lpVtbl->Release(sys->outputSample);
709 sys->outputSample = nullptr;
710 }
711 if (sys->inputType)
712 {
713 sys->inputType->lpVtbl->Release(sys->inputType);
714 sys->inputType = nullptr;
715 }
716 if (sys->outputType)
717 {
718 sys->outputType->lpVtbl->Release(sys->outputType);
719 sys->outputType = nullptr;
720 }
721 if (sys->codecApi)
722 {
723 sys->codecApi->lpVtbl->Release(sys->codecApi);
724 sys->codecApi = nullptr;
725 }
726 if (sys->transform)
727 {
728 sys->transform->lpVtbl->Release(sys->transform);
729 sys->transform = nullptr;
730 }
731 sys->encStreaming = FALSE;
732}
733
734WINPR_ATTR_NODISCARD
735static BOOL mf_encoder_create(H264_CONTEXT* h264, H264_CONTEXT_MF* sys)
736{
737 WINPR_ASSERT(h264);
738 WINPR_ASSERT(sys);
739
740 HRESULT hr = CoCreateInstance(&sCLSID_CMSH264EncoderMFT, nullptr, CLSCTX_INPROC_SERVER,
741 &sIID_IMFTransform, (void**)&sys->transform);
742
743 if (FAILED(hr))
744 {
745 WLog_Print(h264->log, WLOG_DEBUG,
746 "CoCreateInstance(CLSID_CMSH264EncoderMFT) failure: 0x%08" PRIX32 "",
747 (UINT32)hr);
748 return FALSE;
749 }
750
751 /* rate control and latency are tuned through ICodecAPI; encode without it if it is missing */
752 hr = sys->transform->lpVtbl->QueryInterface(sys->transform, &sIID_ICodecAPI,
753 (void**)&sys->codecApi);
754 if (FAILED(hr))
755 {
756 WLog_Print(h264->log, WLOG_WARN,
757 "H264 encoder has no ICodecAPI (0x%08" PRIX32 "), using its defaults",
758 (UINT32)hr);
759 sys->codecApi = nullptr;
760 }
761
762 return TRUE;
763}
764
765WINPR_ATTR_NODISCARD
766static HRESULT mf_encoder_media_type(H264_CONTEXT_MF* sys, IMFMediaType** ppType,
767 const GUID* subtype, UINT32 width, UINT32 height,
768 UINT32 frameRate, UINT32 bitRate)
769{
770 IMFMediaType* type = nullptr;
771
772 WINPR_ASSERT(sys);
773 WINPR_ASSERT(sys->MFCreateMediaType);
774 WINPR_ASSERT(ppType);
775 WINPR_ASSERT(subtype);
776
777 HRESULT hr = sys->MFCreateMediaType(&type);
778
779 if (FAILED(hr))
780 return hr;
781
782 hr = type->lpVtbl->SetGUID(type, &sMF_MT_MAJOR_TYPE, &sMFMediaType_Video);
783 if (SUCCEEDED(hr))
784 hr = type->lpVtbl->SetGUID(type, &sMF_MT_SUBTYPE, subtype);
785 if (SUCCEEDED(hr))
786 hr = type->lpVtbl->SetUINT64(type, &sMF_MT_FRAME_SIZE, ((UINT64)width << 32) | height);
787 if (SUCCEEDED(hr))
788 hr = type->lpVtbl->SetUINT64(type, &sMF_MT_FRAME_RATE, ((UINT64)frameRate << 32) | 1);
789 if (SUCCEEDED(hr))
790 hr = type->lpVtbl->SetUINT64(type, &sMF_MT_PIXEL_ASPECT_RATIO, ((UINT64)1 << 32) | 1);
791 if (SUCCEEDED(hr))
792 hr =
793 type->lpVtbl->SetUINT32(type, &sMF_MT_INTERLACE_MODE, FREERDP_MF_INTERLACE_PROGRESSIVE);
794
795 if (SUCCEEDED(hr) && IsEqualGUID(subtype, &sMFVideoFormat_H264))
796 {
797 hr = type->lpVtbl->SetUINT32(type, &sMF_MT_AVG_BITRATE, bitRate);
798 /* constrained baseline: no B frames, CAVLC, so every FreeRDP client decoder can read it */
799 if (SUCCEEDED(hr))
800 hr = type->lpVtbl->SetUINT32(type, &sMF_MT_MPEG2_PROFILE, FREERDP_MF_PROFILE_BASELINE);
801 }
802
803 if (FAILED(hr))
804 {
805 type->lpVtbl->Release(type);
806 return hr;
807 }
808
809 *ppType = type;
810 return S_OK;
811}
812
813WINPR_ATTR_NODISCARD
814static BOOL mf_encoder_rate_control(H264_CONTEXT* h264, H264_CONTEXT_MF* sys, UINT32 bitRate)
815{
816 WINPR_ASSERT(h264);
817 WINPR_ASSERT(sys);
818
819 /* without it the encoder holds frames back (4 on Windows Server 2025); mf_compress copes
820 * with that, so the property is optional. It is a VT_BOOL; the encoder answers E_INVALIDARG
821 * to VT_UI4, which other MFTs (the decoder) take, so VT_UI4 is the second try */
822 HRESULT hr = mf_encoder_set_value(h264, sys, &sCODECAPI_AVLowLatencyMode, "AVLowLatencyMode",
823 VT_BOOL, 1);
824 if (FAILED(hr))
825 hr = mf_encoder_set_value(h264, sys, &sCODECAPI_AVLowLatencyMode, "AVLowLatencyMode",
826 VT_UI4, 1);
827 if (!mf_encoder_check_value(h264, sys, &sCODECAPI_AVLowLatencyMode, "AVLowLatencyMode", hr))
828 return FALSE;
829
830 if (!mf_encoder_set_optional(h264, sys, &sCODECAPI_AVEncMPVGOPSize, "AVEncMPVGOPSize", VT_UI4,
831 30))
832 return FALSE;
833
834 switch (h264->RateControlMode)
835 {
836 case H264_RATECONTROL_CQP:
837 {
838 if (!mf_encoder_set_optional(h264, sys, &sCODECAPI_AVEncCommonRateControlMode,
839 "AVEncCommonRateControlMode", VT_UI4,
840 FREERDP_MF_RC_QUALITY))
841 return FALSE;
842 /* AVEncVideoEncodeQP: the QP in the low 16 bits; older encoders only have the
843 * 0..100 quality scale, so when the QP is refused for any reason map it (0..51,
844 * lower is better) onto that scale; the quality scale's result decides */
845 if (FAILED(mf_encoder_set_value(h264, sys, &sCODECAPI_AVEncVideoEncodeQP,
846 "AVEncVideoEncodeQP", VT_UI8, h264->QP & 0xFFFF)))
847 {
848 const UINT32 qp = MIN(h264->QP, 51);
849 if (!mf_encoder_set_optional(h264, sys, &sCODECAPI_AVEncCommonQuality,
850 "AVEncCommonQuality", VT_UI4, 100 - (qp * 100 / 51)))
851 return FALSE;
852 }
853 }
854 break;
855
856 case H264_RATECONTROL_VBR:
857 default:
858 /* a target bit rate, like OpenH264's RC_BITRATE_MODE; the bit rate is also on the
859 * output type (MF_MT_AVG_BITRATE), which every encoder reads */
860 if (!mf_encoder_set_optional(h264, sys, &sCODECAPI_AVEncCommonRateControlMode,
861 "AVEncCommonRateControlMode", VT_UI4, FREERDP_MF_RC_CBR))
862 return FALSE;
863 if (!mf_encoder_set_optional(h264, sys, &sCODECAPI_AVEncCommonMeanBitRate,
864 "AVEncCommonMeanBitRate", VT_UI4, bitRate))
865 return FALSE;
866 break;
867 }
868
869 return TRUE;
870}
871
872WINPR_ATTR_NODISCARD
873static BOOL mf_encoder_configure(H264_CONTEXT* h264, H264_CONTEXT_MF* sys, UINT32 width,
874 UINT32 height, UINT32 frameRate, UINT32 bitRate)
875{
876 MFT_OUTPUT_STREAM_INFO streamInfo = WINPR_C_ARRAY_INIT;
877
878 WINPR_ASSERT(h264);
879 WINPR_ASSERT(sys);
880
881 /* the types of a running encoder can't change, start a new one */
882 if (sys->encStreaming || !sys->transform)
883 {
884 mf_encoder_release(sys);
885 if (!mf_encoder_create(h264, sys))
886 return FALSE;
887 }
888
889 /* rate control is read when the output type is set, so it goes first */
890 if (!mf_encoder_rate_control(h264, sys, bitRate))
891 goto fail;
892
893 /* the H.264 encoder wants the output type before the input type */
894 HRESULT hr = mf_encoder_media_type(sys, &sys->outputType, &sMFVideoFormat_H264, width, height,
895 frameRate, bitRate);
896 if (FAILED(hr))
897 {
898 WLog_Print(h264->log, WLOG_ERROR, "encoder output type failure: 0x%08" PRIX32 "",
899 (UINT32)hr);
900 goto fail;
901 }
902
903 hr = sys->transform->lpVtbl->SetOutputType(sys->transform, 0, sys->outputType, 0);
904 if (FAILED(hr))
905 {
906 WLog_Print(h264->log, WLOG_ERROR, "encoder SetOutputType failure: 0x%08" PRIX32 "",
907 (UINT32)hr);
908 goto fail;
909 }
910
911 hr = mf_encoder_media_type(sys, &sys->inputType, &sMFVideoFormat_NV12, width, height, frameRate,
912 bitRate);
913 if (FAILED(hr))
914 {
915 WLog_Print(h264->log, WLOG_ERROR, "encoder input type failure: 0x%08" PRIX32 "",
916 (UINT32)hr);
917 goto fail;
918 }
919
920 hr = sys->transform->lpVtbl->SetInputType(sys->transform, 0, sys->inputType, 0);
921 if (FAILED(hr))
922 {
923 WLog_Print(h264->log, WLOG_ERROR, "encoder SetInputType failure: 0x%08" PRIX32 "",
924 (UINT32)hr);
925 goto fail;
926 }
927
928 hr = sys->transform->lpVtbl->GetOutputStreamInfo(sys->transform, 0, &streamInfo);
929 if (FAILED(hr))
930 {
931 WLog_Print(h264->log, WLOG_ERROR, "encoder GetOutputStreamInfo failure: 0x%08" PRIX32 "",
932 (UINT32)hr);
933 goto fail;
934 }
935
936 sys->encOutputFlags = streamInfo.dwFlags;
937 sys->encOutputSize = streamInfo.cbSize;
938 if (sys->encOutputSize == 0)
939 sys->encOutputSize = (DWORD)(3ull * width * height / 2); /* checked by mf_compress */
940
941 if ((sys->encOutputFlags & MFT_OUTPUT_STREAM_PROVIDES_SAMPLES) == 0)
942 {
943 IMFMediaBuffer* buffer = nullptr;
944
945 hr = sys->MFCreateSample(&sys->outputSample);
946 if (SUCCEEDED(hr))
947 hr = sys->MFCreateMemoryBuffer(sys->encOutputSize, &buffer);
948 if (SUCCEEDED(hr))
949 hr = sys->outputSample->lpVtbl->AddBuffer(sys->outputSample, buffer);
950 if (buffer)
951 buffer->lpVtbl->Release(buffer);
952 if (FAILED(hr))
953 {
954 WLog_Print(h264->log, WLOG_ERROR, "encoder output sample failure: 0x%08" PRIX32 "",
955 (UINT32)hr);
956 goto fail;
957 }
958 }
959
960 hr = sys->transform->lpVtbl->ProcessMessage(sys->transform, MFT_MESSAGE_NOTIFY_BEGIN_STREAMING,
961 0);
962 if (SUCCEEDED(hr))
963 hr = sys->transform->lpVtbl->ProcessMessage(sys->transform,
964 MFT_MESSAGE_NOTIFY_START_OF_STREAM, 0);
965 if (FAILED(hr))
966 {
967 WLog_Print(h264->log, WLOG_ERROR, "encoder ProcessMessage failure: 0x%08" PRIX32 "",
968 (UINT32)hr);
969 goto fail;
970 }
971
972 sys->encStreaming = TRUE;
973 sys->encWidth = width;
974 sys->encHeight = height;
975 sys->encFrameRate = frameRate;
976 sys->encBitRate = bitRate;
977 sys->encQP = h264->QP;
978 sys->encRateControl = h264->RateControlMode;
979 sys->encSampleTime = 0;
980 sys->encHeld = 0;
981 WLog_Print(h264->log, WLOG_DEBUG,
982 "MediaFoundation H264 encoder: %" PRIu32 "x%" PRIu32 " %" PRIu32
983 " fps, output flags 0x%08" PRIx32 "",
984 width, height, frameRate, (UINT32)sys->encOutputFlags);
985 return TRUE;
986
987fail:
988 mf_encoder_release(sys);
989 return FALSE;
990}
991
992WINPR_ATTR_NODISCARD
993static BOOL mf_encoder_append(H264_CONTEXT* h264, H264_CONTEXT_MF* sys, IMFSample* sample)
994{
995 IMFMediaBuffer* buffer = nullptr;
996 BYTE* data = nullptr;
997 DWORD maxLength = 0;
998 DWORD length = 0;
999 BOOL rc = FALSE;
1000
1001 WINPR_ASSERT(h264);
1002 WINPR_ASSERT(sys);
1003 WINPR_ASSERT(sample);
1004
1005 HRESULT hr = sample->lpVtbl->ConvertToContiguousBuffer(sample, &buffer);
1006 if (FAILED(hr))
1007 {
1008 WLog_Print(h264->log, WLOG_ERROR, "ConvertToContiguousBuffer failure: 0x%08" PRIX32 "",
1009 (UINT32)hr);
1010 return FALSE;
1011 }
1012
1013 hr = buffer->lpVtbl->Lock(buffer, &data, &maxLength, &length);
1014 if (FAILED(hr))
1015 {
1016 WLog_Print(h264->log, WLOG_ERROR, "Lock failure: 0x%08" PRIX32 "", (UINT32)hr);
1017 goto out;
1018 }
1019
1020 BOOL copied = FALSE;
1021 const size_t needed = sys->encDataLength + length;
1022 if (needed > sys->encDataSize)
1023 {
1024 BYTE* tmp = realloc(sys->encData, needed);
1025 if (tmp)
1026 {
1027 sys->encData = tmp;
1028 sys->encDataSize = needed;
1029 }
1030 }
1031 if (needed <= sys->encDataSize)
1032 {
1033 if (length > 0)
1034 memcpy(&sys->encData[sys->encDataLength], data, length);
1035 sys->encDataLength = needed;
1036 copied = TRUE;
1037 }
1038
1039 /* one Unlock for both outcomes, so its result is checked on every path */
1040 hr = buffer->lpVtbl->Unlock(buffer);
1041 if (FAILED(hr))
1042 WLog_Print(h264->log, WLOG_ERROR, "Unlock failure: 0x%08" PRIX32 "", (UINT32)hr);
1043 else if (!copied)
1044 WLog_Print(h264->log, WLOG_ERROR, "encoder output: out of memory (%" PRIuz " bytes)",
1045 needed);
1046 else
1047 rc = TRUE;
1048
1049out:
1050 buffer->lpVtbl->Release(buffer);
1051 return rc;
1052}
1053
1054/* collect everything the encoder has ready; MF_E_TRANSFORM_NEED_MORE_INPUT ends it */
1055WINPR_ATTR_NODISCARD
1056static HRESULT mf_encoder_drain(H264_CONTEXT* h264, H264_CONTEXT_MF* sys)
1057{
1058 WINPR_ASSERT(h264);
1059 WINPR_ASSERT(sys);
1060 WINPR_ASSERT(sys->transform);
1061
1062 const BOOL provides = (sys->encOutputFlags & MFT_OUTPUT_STREAM_PROVIDES_SAMPLES) != 0;
1063
1064 for (size_t i = 0; i < 16; i++)
1065 {
1066 DWORD status = 0;
1067 MFT_OUTPUT_DATA_BUFFER output = WINPR_C_ARRAY_INIT;
1068
1069 if (!provides)
1070 {
1071 /* the encoder writes into our sample: give it an empty buffer each time */
1072 IMFMediaBuffer* buffer = nullptr;
1073
1074 WINPR_ASSERT(sys->outputSample);
1075 HRESULT hr = sys->outputSample->lpVtbl->GetBufferByIndex(sys->outputSample, 0, &buffer);
1076 if (SUCCEEDED(hr))
1077 {
1078 hr = buffer->lpVtbl->SetCurrentLength(buffer, 0);
1079 buffer->lpVtbl->Release(buffer);
1080 }
1081 if (FAILED(hr))
1082 {
1083 WLog_Print(h264->log, WLOG_ERROR,
1084 "encoder output buffer reset failure: 0x%08" PRIX32 "", (UINT32)hr);
1085 return hr;
1086 }
1087 output.pSample = sys->outputSample;
1088 }
1089
1090 const HRESULT hr =
1091 sys->transform->lpVtbl->ProcessOutput(sys->transform, 0, 1, &output, &status);
1092 if (output.pEvents)
1093 output.pEvents->lpVtbl->Release(output.pEvents);
1094
1095 if (hr == MF_E_TRANSFORM_NEED_MORE_INPUT)
1096 return S_OK;
1097
1098 if (FAILED(hr))
1099 {
1100 if (provides && output.pSample)
1101 output.pSample->lpVtbl->Release(output.pSample);
1102 WLog_Print(h264->log, WLOG_ERROR, "encoder ProcessOutput failure: 0x%08" PRIX32 "",
1103 (UINT32)hr);
1104 return hr;
1105 }
1106
1107 const BOOL ok = output.pSample ? mf_encoder_append(h264, sys, output.pSample) : TRUE;
1108 if (provides && output.pSample)
1109 output.pSample->lpVtbl->Release(output.pSample);
1110 if (!ok)
1111 return E_FAIL; /* mf_encoder_append logged why */
1112 }
1113
1114 return S_OK;
1115}
1116
1117WINPR_ATTR_NODISCARD
1118static BOOL mf_encoder_update(H264_CONTEXT* h264, H264_CONTEXT_MF* sys, UINT32 width, UINT32 height,
1119 UINT32 frameRate, UINT32 bitRate)
1120{
1121 WINPR_ASSERT(h264);
1122 WINPR_ASSERT(sys);
1123
1124 if (!sys->encStreaming || (sys->encWidth != width) || (sys->encHeight != height) ||
1125 (sys->encFrameRate != frameRate) || (sys->encRateControl != h264->RateControlMode))
1126 return mf_encoder_configure(h264, sys, width, height, frameRate, bitRate);
1127
1128 /* bit rate and QP can change while the encoder runs; start over where they can't */
1129 if ((h264->RateControlMode == H264_RATECONTROL_VBR) && (sys->encBitRate != bitRate))
1130 {
1131 if (FAILED(mf_encoder_set_value(h264, sys, &sCODECAPI_AVEncCommonMeanBitRate,
1132 "AVEncCommonMeanBitRate", VT_UI4, bitRate)))
1133 return mf_encoder_configure(h264, sys, width, height, frameRate, bitRate);
1134 sys->encBitRate = bitRate;
1135 }
1136
1137 if ((h264->RateControlMode == H264_RATECONTROL_CQP) && (sys->encQP != h264->QP))
1138 {
1139 if (FAILED(mf_encoder_set_value(h264, sys, &sCODECAPI_AVEncVideoEncodeQP,
1140 "AVEncVideoEncodeQP", VT_UI8, h264->QP & 0xFFFF)))
1141 return mf_encoder_configure(h264, sys, width, height, frameRate, bitRate);
1142 sys->encQP = h264->QP;
1143 }
1144
1145 return TRUE;
1146}
1147
1148/* I420 planes as FreeRDP holds them -> one NV12 buffer of width x height */
1149static void mf_encoder_copy_nv12(BYTE* WINPR_RESTRICT dst, const BYTE** WINPR_RESTRICT pSrcYuv,
1150 const UINT32* WINPR_RESTRICT pStride, UINT32 width, UINT32 height)
1151{
1152 WINPR_ASSERT(dst);
1153 WINPR_ASSERT(pSrcYuv);
1154 WINPR_ASSERT(pSrcYuv[0]);
1155 WINPR_ASSERT(pSrcYuv[1]);
1156 WINPR_ASSERT(pSrcYuv[2]);
1157 WINPR_ASSERT(pStride);
1158
1159 for (UINT32 y = 0; y < height; y++)
1160 memcpy(&dst[1ull * y * width], &pSrcYuv[0][1ull * y * pStride[0]], width);
1161
1162 BYTE* uv = &dst[1ull * width * height];
1163 for (UINT32 y = 0; y < height / 2; y++)
1164 {
1165 const BYTE* u = &pSrcYuv[1][1ull * y * pStride[1]];
1166 const BYTE* v = &pSrcYuv[2][1ull * y * pStride[2]];
1167 BYTE* line = &uv[1ull * y * width];
1168
1169 for (UINT32 x = 0; x < width / 2; x++)
1170 {
1171 line[2 * x] = u[x];
1172 line[2 * x + 1] = v[x];
1173 }
1174 }
1175}
1176
1177WINPR_ATTR_NODISCARD
1178static int mf_compress(H264_CONTEXT* WINPR_RESTRICT h264, const BYTE** WINPR_RESTRICT ppSrcYuv,
1179 const UINT32* WINPR_RESTRICT pStride, BYTE** WINPR_RESTRICT ppDstData,
1180 UINT32* WINPR_RESTRICT pDstSize)
1181{
1182 int rc = -1;
1183 BYTE* data = nullptr;
1184 DWORD maxLength = 0;
1185 DWORD curLength = 0;
1186 IMFSample* sample = nullptr;
1187 IMFMediaBuffer* buffer = nullptr;
1188
1189 WINPR_ASSERT(h264);
1190 WINPR_ASSERT(ppSrcYuv);
1191 WINPR_ASSERT(pStride);
1192 WINPR_ASSERT(ppDstData);
1193 WINPR_ASSERT(pDstSize);
1194
1195 H264_CONTEXT_MF* sys = (H264_CONTEXT_MF*)h264->pSystemData;
1196 if (!sys || !ppSrcYuv[0] || !ppSrcYuv[1] || !ppSrcYuv[2])
1197 return -1;
1198
1199 if ((h264->width == 0) || (h264->height == 0) || (h264->width > UINT16_MAX) ||
1200 (h264->height > UINT16_MAX))
1201 return -1;
1202
1203 /* 4:2:0 needs even sizes; the YUV buffers are padded (yuv_ensure_buffer), so one more
1204 * column or row is readable */
1205 const UINT32 width = (h264->width + 1) & ~1u;
1206 const UINT32 height = (h264->height + 1) & ~1u;
1207 const UINT32 frameRate = (h264->FrameRate > 0) ? h264->FrameRate : 30;
1208 const UINT32 bitRate = (h264->BitRate > 0) ? h264->BitRate : 1000000;
1209
1210 /* one NV12 frame; the encoder's output buffer is sized the same way */
1211 const UINT64 size64 = 3ull * width * height / 2;
1212 if (size64 > UINT32_MAX)
1213 return -1;
1214 const DWORD size = (DWORD)size64;
1215
1216 if (!mf_encoder_update(h264, sys, width, height, frameRate, bitRate))
1217 return -1;
1218
1219 HRESULT hr = sys->MFCreateMemoryBuffer(size, &buffer);
1220 if (FAILED(hr))
1221 {
1222 WLog_Print(h264->log, WLOG_ERROR, "MFCreateMemoryBuffer failure: 0x%08" PRIX32 "",
1223 (UINT32)hr);
1224 goto out;
1225 }
1226
1227 hr = buffer->lpVtbl->Lock(buffer, &data, &maxLength, &curLength);
1228 if (FAILED(hr))
1229 {
1230 WLog_Print(h264->log, WLOG_ERROR, "Lock failure: 0x%08" PRIX32 "", (UINT32)hr);
1231 goto out;
1232 }
1233
1234 const BOOL fits = (maxLength >= size);
1235 if (fits)
1236 mf_encoder_copy_nv12(data, ppSrcYuv, pStride, width, height);
1237
1238 /* one Unlock for both outcomes, so its result is checked on every path */
1239 hr = buffer->lpVtbl->Unlock(buffer);
1240 if (FAILED(hr))
1241 {
1242 WLog_Print(h264->log, WLOG_ERROR, "Unlock failure: 0x%08" PRIX32 "", (UINT32)hr);
1243 goto out;
1244 }
1245 if (!fits)
1246 {
1247 WLog_Print(h264->log, WLOG_ERROR,
1248 "encoder input buffer too small: %" PRIu32 " < %" PRIu32 " bytes",
1249 (UINT32)maxLength, (UINT32)size);
1250 goto out;
1251 }
1252
1253 hr = buffer->lpVtbl->SetCurrentLength(buffer, size);
1254 if (SUCCEEDED(hr))
1255 hr = sys->MFCreateSample(&sample);
1256 if (SUCCEEDED(hr))
1257 hr = sample->lpVtbl->AddBuffer(sample, buffer);
1258
1259 /* 100 ns units; the encoder's rate control works from these */
1260 const LONGLONG duration = 10000000LL / frameRate;
1261 if (SUCCEEDED(hr))
1262 hr = sample->lpVtbl->SetSampleTime(sample, sys->encSampleTime);
1263 if (SUCCEEDED(hr))
1264 hr = sample->lpVtbl->SetSampleDuration(sample, duration);
1265 if (FAILED(hr))
1266 {
1267 WLog_Print(h264->log, WLOG_ERROR, "encoder input sample failure: 0x%08" PRIX32 "",
1268 (UINT32)hr);
1269 goto out;
1270 }
1271 sys->encSampleTime += duration;
1272
1273 sys->encDataLength = 0;
1274 hr = sys->transform->lpVtbl->ProcessInput(sys->transform, 0, sample, 0);
1275 if (hr == MF_E_NOTACCEPTING)
1276 {
1277 /* output is waiting first: take it, then the input fits */
1278 hr = mf_encoder_drain(h264, sys);
1279 if (SUCCEEDED(hr))
1280 hr = sys->transform->lpVtbl->ProcessInput(sys->transform, 0, sample, 0);
1281 }
1282 if (FAILED(hr))
1283 {
1284 WLog_Print(h264->log, WLOG_ERROR, "encoder ProcessInput failure: 0x%08" PRIX32 "",
1285 (UINT32)hr);
1286 goto out;
1287 }
1288
1289 hr = mf_encoder_drain(h264, sys);
1290 if (FAILED(hr))
1291 goto out;
1292
1293 if (sys->encDataLength > UINT32_MAX)
1294 goto out;
1295
1296 if (sys->encDataLength == 0)
1297 {
1298 /* the encoder kept the frame (pipeline delay); nothing to send yet. Microsoft's
1299 * encoder in low latency mode never does; an encoder that ignores the mode (look
1300 * ahead, B frames) shows every change late, so say so once */
1301 sys->encHeld++;
1302 if ((sys->encHeld == 4) && !sys->encWarned)
1303 {
1304 WLog_Print(h264->log, WLOG_WARN,
1305 "MediaFoundation H264 encoder holds frames back (low latency mode not "
1306 "honoured), the client will see changes late");
1307 sys->encWarned = TRUE;
1308 }
1309 rc = 0;
1310 goto out;
1311 }
1312
1313 sys->encHeld = 0;
1314 *ppDstData = sys->encData;
1315 *pDstSize = (UINT32)sys->encDataLength;
1316 rc = 1;
1317
1318out:
1319 if (sample)
1320 sample->lpVtbl->Release(sample);
1321 if (buffer)
1322 buffer->lpVtbl->Release(buffer);
1323 return rc;
1324}
1325
1326WINPR_ATTR_NODISCARD
1327static BOOL mf_plat_loaded(H264_CONTEXT_MF* sys)
1328{
1329 WINPR_ASSERT(sys);
1330 return sys->MFStartup && sys->MFShutdown && sys->MFCreateSample && sys->MFCreateMemoryBuffer &&
1331 sys->MFCreateMediaType;
1332}
1333
1334static void mf_uninit(H264_CONTEXT* h264)
1335{
1336 WINPR_ASSERT(h264);
1337
1338 H264_CONTEXT_MF* sys = (H264_CONTEXT_MF*)h264->pSystemData;
1339
1340 if (sys)
1341 {
1342 if (sys->transform)
1343 {
1344 sys->transform->lpVtbl->Release(sys->transform);
1345 sys->transform = nullptr;
1346 }
1347
1348 if (sys->codecApi)
1349 {
1350 sys->codecApi->lpVtbl->Release(sys->codecApi);
1351 sys->codecApi = nullptr;
1352 }
1353
1354 if (sys->inputType)
1355 {
1356 sys->inputType->lpVtbl->Release(sys->inputType);
1357 sys->inputType = nullptr;
1358 }
1359
1360 if (sys->outputType)
1361 {
1362 sys->outputType->lpVtbl->Release(sys->outputType);
1363 sys->outputType = nullptr;
1364 }
1365
1366 if (sys->outputSample)
1367 {
1368 sys->outputSample->lpVtbl->Release(sys->outputSample);
1369 sys->outputSample = nullptr;
1370 }
1371
1372 if (sys->mfplat)
1373 {
1374 if (mf_plat_loaded(sys))
1375 {
1376 /* nothing to undo in a cleanup path, say so and go on */
1377 const HRESULT hr = sys->MFShutdown();
1378 if (FAILED(hr))
1379 WLog_Print(h264->log, WLOG_WARN, "MFShutdown failure: 0x%08" PRIX32 "",
1380 (UINT32)hr);
1381 }
1382
1383 FreeLibrary(sys->mfplat);
1384 sys->mfplat = nullptr;
1385
1386 if (mf_plat_loaded(sys))
1387 CoUninitialize();
1388 }
1389
1390 for (size_t x = 0; x < sizeof(h264->pYUVData) / sizeof(h264->pYUVData[0]); x++)
1391 winpr_aligned_free(h264->pYUVData[x]);
1392
1393 memset(h264->pYUVData, 0, sizeof(h264->pYUVData));
1394 memset(h264->iStride, 0, sizeof(h264->iStride));
1395
1396 free(sys->encData);
1397 free(sys);
1398 h264->pSystemData = nullptr;
1399 }
1400}
1401
1402/* There is no fixed CLSID for an HEVC decoder: Windows ships it with the HEVC Video Extensions
1403 * (or a GPU vendor package), so enumerate the registered synchronous decoders. */
1404WINPR_ATTR_NODISCARD
1405static HRESULT mf_decoder_create_hevc(H264_CONTEXT* h264, H264_CONTEXT_MF* sys)
1406{
1407 WINPR_ASSERT(h264);
1408 WINPR_ASSERT(sys);
1409
1410 if (!sys->MFTEnumEx)
1411 return E_NOTIMPL;
1412
1413 const MFT_REGISTER_TYPE_INFO input = { sMFMediaType_Video, sMFVideoFormat_HEVC };
1414 IMFActivate** activates = nullptr;
1415 UINT32 count = 0;
1416 HRESULT hr =
1417 sys->MFTEnumEx(sMFT_CATEGORY_VIDEO_DECODER,
1418 MFT_ENUM_FLAG_SYNCMFT | MFT_ENUM_FLAG_LOCALMFT | MFT_ENUM_FLAG_SORTANDFILTER,
1419 &input, nullptr, &activates, &count);
1420 if (FAILED(hr))
1421 {
1422 WLog_Print(h264->log, WLOG_ERROR, "MFTEnumEx(HEVC decoder) failure: 0x%08" PRIX32 "",
1423 (UINT32)hr);
1424 return hr;
1425 }
1426
1427 hr = MF_E_TOPO_CODEC_NOT_FOUND;
1428 for (UINT32 x = 0; x < count; x++)
1429 {
1430 IMFActivate* activate = activates[x];
1431 if (FAILED(hr))
1432 hr = activate->lpVtbl->ActivateObject(activate, &sIID_IMFTransform,
1433 (void**)&sys->transform);
1434 activate->lpVtbl->Release(activate);
1435 }
1436 CoTaskMemFree((void*)activates);
1437
1438 if (count == 0)
1439 WLog_Print(h264->log, WLOG_WARN,
1440 "no MediaFoundation HEVC decoder found, install the HEVC Video Extensions");
1441 else if (FAILED(hr))
1442 WLog_Print(h264->log, WLOG_ERROR, "ActivateObject(HEVC decoder) failure: 0x%08" PRIX32 "",
1443 (UINT32)hr);
1444 return hr;
1445}
1446
1447WINPR_ATTR_NODISCARD
1448static BOOL mf_init(H264_CONTEXT* h264)
1449{
1450 HRESULT hr;
1451
1452 WINPR_ASSERT(h264);
1453
1454 H264_CONTEXT_MF* sys = (H264_CONTEXT_MF*)calloc(1, sizeof(H264_CONTEXT_MF));
1455
1456 if (!sys)
1457 goto error;
1458
1459 h264->pSystemData = (void*)sys;
1460 /* http://decklink-sdk-delphi.googlecode.com/svn/trunk/Blackmagic%20DeckLink%20SDK%209.7/Win/Samples/Streaming/StreamingPreview/DecoderMF.cpp
1461 */
1462 sys->mfplat = LoadLibraryA("mfplat.dll");
1463
1464 if (!sys->mfplat)
1465 goto error;
1466
1467 sys->MFStartup = GetProcAddressAs(sys->mfplat, "MFStartup", pfnMFStartup);
1468 sys->MFShutdown = GetProcAddressAs(sys->mfplat, "MFShutdown", pfnMFShutdown);
1469 sys->MFCreateSample = GetProcAddressAs(sys->mfplat, "MFCreateSample", pfnMFCreateSample);
1470 sys->MFCreateMemoryBuffer =
1471 GetProcAddressAs(sys->mfplat, "MFCreateMemoryBuffer", pfnMFCreateMemoryBuffer);
1472 sys->MFCreateMediaType =
1473 GetProcAddressAs(sys->mfplat, "MFCreateMediaType", pfnMFCreateMediaType);
1474 /* only needed for HEVC */
1475 sys->MFTEnumEx = GetProcAddressAs(sys->mfplat, "MFTEnumEx", pfnMFTEnumEx);
1476
1477 if (!mf_plat_loaded(sys))
1478 goto error;
1479
1480 CoInitializeEx(nullptr, COINIT_APARTMENTTHREADED);
1481
1482 if (h264->Compressor)
1483 {
1484 hr = sys->MFStartup(MF_VERSION, 0);
1485
1486 if (FAILED(hr))
1487 {
1488 WLog_Print(h264->log, WLOG_ERROR, "MFStartup failure: 0x%08" PRIX32 "", hr);
1489 goto error;
1490 }
1491
1492 /* the media types need the frame size: they are set on the first frame (mf_compress).
1493 * Creating the encoder now lets h264_context_init() try the next subsystem when this
1494 * Windows has none (N editions, Server without the Media Foundation feature). */
1495 if (!mf_encoder_create(h264, sys))
1496 {
1497 WLog_Print(h264->log, WLOG_WARN, "MediaFoundation H264 encoder not available");
1498 goto error;
1499 }
1500 }
1501 else
1502 {
1503 VARIANT var = WINPR_C_ARRAY_INIT;
1504 hr = sys->MFStartup(MF_VERSION, 0);
1505
1506 if (FAILED(hr))
1507 {
1508 WLog_Print(h264->log, WLOG_ERROR, "MFStartup failure: 0x%08" PRIX32 "", hr);
1509 goto error;
1510 }
1511
1512 if (h264->hevc)
1513 {
1514 hr = mf_decoder_create_hevc(h264, sys);
1515 if (FAILED(hr))
1516 goto error;
1517 }
1518 else
1519 {
1520 hr = CoCreateInstance(&sCLSID_CMSH264DecoderMFT, nullptr, CLSCTX_INPROC_SERVER,
1521 &sIID_IMFTransform, (void**)&sys->transform);
1522
1523 if (FAILED(hr))
1524 {
1525 WLog_Print(h264->log, WLOG_ERROR,
1526 "CoCreateInstance(CLSID_CMSH264DecoderMFT) failure: 0x%08" PRIX32 "",
1527 hr);
1528 goto error;
1529 }
1530 }
1531
1532 /* MF_LOW_LATENCY (same GUID as CODECAPI_AVLowLatencyMode) on the transform attributes:
1533 * without it the HEVC decoder never returns a picture. Not fatal, ICodecAPI follows. */
1534 {
1535 IMFAttributes* attributes = nullptr;
1536 hr = sys->transform->lpVtbl->GetAttributes(sys->transform, &attributes);
1537 if (SUCCEEDED(hr) && attributes)
1538 {
1539 hr = attributes->lpVtbl->SetUINT32(attributes, &sCODECAPI_AVLowLatencyMode, TRUE);
1540 attributes->lpVtbl->Release(attributes);
1541 }
1542 if (FAILED(hr))
1543 WLog_Print(h264->log, WLOG_DEBUG,
1544 "MF_LOW_LATENCY transform attribute failure: 0x%08" PRIX32, (UINT32)hr);
1545 }
1546
1547 /* The H264 decoder must run in low latency mode, else it holds back frames.
1548 * Other decoders may not offer ICodecAPI, they decode with their defaults. */
1549 hr = sys->transform->lpVtbl->QueryInterface(sys->transform, &sIID_ICodecAPI,
1550 (void**)&sys->codecApi);
1551
1552 if (FAILED(hr) && !h264->hevc)
1553 {
1554 WLog_Print(h264->log, WLOG_ERROR,
1555 "QueryInterface(IID_ICodecAPI) failure: 0x%08" PRIX32 "", hr);
1556 goto error;
1557 }
1558
1559 if (sys->codecApi)
1560 {
1561 var.n1.n2.vt = VT_UI4;
1562 var.n1.n2.n3.ulVal = 1;
1563 hr = sys->codecApi->lpVtbl->SetValue(sys->codecApi, &sCODECAPI_AVLowLatencyMode, &var);
1564
1565 if (FAILED(hr))
1566 {
1567 WLog_Print(h264->log, h264->hevc ? WLOG_WARN : WLOG_ERROR,
1568 "SetValue(CODECAPI_AVLowLatencyMode) failure: 0x%08" PRIX32 "", hr);
1569 if (!h264->hevc)
1570 goto error;
1571 }
1572 }
1573
1574 hr = sys->MFCreateMediaType(&sys->inputType);
1575
1576 if (FAILED(hr))
1577 {
1578 WLog_Print(h264->log, WLOG_ERROR, "MFCreateMediaType failure: 0x%08" PRIX32 "", hr);
1579 goto error;
1580 }
1581
1582 hr = sys->inputType->lpVtbl->SetGUID(sys->inputType, &sMF_MT_MAJOR_TYPE,
1583 &sMFMediaType_Video);
1584
1585 if (FAILED(hr))
1586 {
1587 WLog_Print(h264->log, WLOG_ERROR, "SetGUID(MF_MT_MAJOR_TYPE) failure: 0x%08" PRIX32 "",
1588 hr);
1589 goto error;
1590 }
1591
1592 hr = sys->inputType->lpVtbl->SetGUID(sys->inputType, &sMF_MT_SUBTYPE,
1593 h264->hevc ? &sMFVideoFormat_HEVC
1594 : &sMFVideoFormat_H264);
1595
1596 if (FAILED(hr))
1597 {
1598 WLog_Print(h264->log, WLOG_ERROR, "SetGUID(MF_MT_SUBTYPE) failure: 0x%08" PRIX32 "",
1599 hr);
1600 goto error;
1601 }
1602
1603 /* HEVC decoders only offer output types once they know the frame size */
1604 if (h264->hevc && (h264->width > 0) && (h264->height > 0))
1605 {
1606 const UINT64 frameSize = ((UINT64)h264->width << 32) | h264->height;
1607 hr = sys->inputType->lpVtbl->SetUINT64(sys->inputType, &sMF_MT_FRAME_SIZE, frameSize);
1608
1609 if (FAILED(hr))
1610 {
1611 WLog_Print(h264->log, WLOG_ERROR,
1612 "SetUINT64(MF_MT_FRAME_SIZE) failure: 0x%08" PRIX32 "", hr);
1613 goto error;
1614 }
1615 }
1616
1617 hr = sys->transform->lpVtbl->SetInputType(sys->transform, 0, sys->inputType, 0);
1618
1619 if (FAILED(hr))
1620 {
1621 WLog_Print(h264->log, WLOG_ERROR, "SetInputType failure: 0x%08" PRIX32 "", hr);
1622 goto error;
1623 }
1624
1625 if (h264->hevc && ((h264->width == 0) || (h264->height == 0)))
1626 {
1627 /* h264_context_reset() initializes again with the surface size */
1628 WLog_Print(h264->log, WLOG_DEBUG, "HEVC decoder created, frame size not yet known");
1629 }
1630 else
1631 {
1632 hr = mf_select_output_type(sys);
1633
1634 if (FAILED(hr))
1635 {
1636 WLog_Print(h264->log, WLOG_ERROR, "mf_select_output_type failure: 0x%08" PRIX32 "",
1637 hr);
1638 goto error;
1639 }
1640
1641 hr = mf_create_output_sample(h264, sys);
1642
1643 if (FAILED(hr))
1644 {
1645 WLog_Print(h264->log, WLOG_ERROR,
1646 "mf_create_output_sample failure: 0x%08" PRIX32 "", hr);
1647 goto error;
1648 }
1649 }
1650 }
1651
1652 /* the decoder writes and the encoder reads I420, not the NV12 YUV buffers of HW_ACCEL */
1653 h264->hwAccel = FALSE; /* not supported */
1654 return TRUE;
1655error:
1656 WLog_Print(h264->log, WLOG_ERROR, "mf_init failure");
1657 mf_uninit(h264);
1658 return FALSE;
1659}
1660
1661const H264_CONTEXT_SUBSYSTEM g_Subsystem_MF = { "MediaFoundation", mf_init, mf_uninit,
1662 mf_decompress, mf_compress };