• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 /*
2  * Copyright © Microsoft Corporation
3  *
4  * Permission is hereby granted, free of charge, to any person obtaining a
5  * copy of this software and associated documentation files (the "Software"),
6  * to deal in the Software without restriction, including without limitation
7  * the rights to use, copy, modify, merge, publish, distribute, sublicense,
8  * and/or sell copies of the Software, and to permit persons to whom the
9  * Software is furnished to do so, subject to the following conditions:
10  *
11  * The above copyright notice and this permission notice (including the next
12  * paragraph) shall be included in all copies or substantial portions of the
13  * Software.
14  *
15  * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16  * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17  * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.  IN NO EVENT SHALL
18  * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19  * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
20  * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
21  * IN THE SOFTWARE.
22  */
23 
24 #include "d3d12_context.h"
25 #include "d3d12_screen.h"
26 #include "d3d12_video_proc.h"
27 #include "d3d12_residency.h"
28 #include "d3d12_util.h"
29 #include "d3d12_resource.h"
30 #include "d3d12_video_buffer.h"
31 #include "d3d12_format.h"
32 
33 void
d3d12_video_processor_begin_frame(struct pipe_video_codec * codec,struct pipe_video_buffer * target,struct pipe_picture_desc * picture)34 d3d12_video_processor_begin_frame(struct pipe_video_codec * codec,
35                                 struct pipe_video_buffer *target,
36                                 struct pipe_picture_desc *picture)
37 {
38     struct d3d12_video_processor * pD3D12Proc = (struct d3d12_video_processor *) codec;
39     debug_printf("[d3d12_video_processor] d3d12_video_processor_begin_frame - "
40                 "fenceValue: %d\n",
41                 pD3D12Proc->m_fenceValue);
42 
43     ///
44     /// Wait here to make sure the next in flight resource set is empty before using it
45     ///
46     uint64_t fenceValueToWaitOn = static_cast<uint64_t>(std::max(static_cast<int64_t>(0l), static_cast<int64_t>(pD3D12Proc->m_fenceValue) - static_cast<int64_t>(D3D12_VIDEO_PROC_ASYNC_DEPTH) ));
47 
48     debug_printf("[d3d12_video_processor] d3d12_video_processor_begin_frame Waiting for completion of in flight resource sets with previous work with fenceValue: %" PRIu64 "\n",
49                     fenceValueToWaitOn);
50 
51     ASSERTED bool wait_res = d3d12_video_processor_sync_completion(codec, fenceValueToWaitOn, OS_TIMEOUT_INFINITE);
52     assert(wait_res);
53 
54     HRESULT hr = pD3D12Proc->m_spCommandList->Reset(pD3D12Proc->m_spCommandAllocators[d3d12_video_processor_pool_current_index(pD3D12Proc)].Get());
55     if (FAILED(hr)) {
56         debug_printf(
57             "[d3d12_video_processor] resetting ID3D12GraphicsCommandList failed with HR %x\n",
58             hr);
59         assert(false);
60     }
61 
62     // Setup process frame arguments for output/target texture.
63     struct d3d12_video_buffer *pOutputVideoBuffer = (struct d3d12_video_buffer *) target;
64 
65     ID3D12Resource *pDstD3D12Res = d3d12_resource_resource(pOutputVideoBuffer->texture);
66     auto dstDesc = GetDesc(pDstD3D12Res);
67     pD3D12Proc->m_OutputArguments = {
68         //struct D3D12_VIDEO_PROCESS_OUTPUT_STREAM_ARGUMENTS args;
69         {
70             {
71                 {
72                         pDstD3D12Res, // ID3D12Resource *pTexture2D;
73                         0, // UINT Subresource;
74                 },
75                 {
76                         NULL, // ID3D12Resource *pTexture2D;
77                         0 // UINT Subresource;
78                 }
79             },
80             { 0, 0, (int) dstDesc.Width, (int) dstDesc.Height }
81         },
82         // struct d3d12_resource* buffer;
83         pOutputVideoBuffer,
84     };
85 
86     debug_printf("d3d12_video_processor_begin_frame: Beginning new scene with Output ID3D12Resource: %p (%d %d)\n", pDstD3D12Res, (int) dstDesc.Width, (int) dstDesc.Height);
87 }
88 
89 void
d3d12_video_processor_end_frame(struct pipe_video_codec * codec,struct pipe_video_buffer * target,struct pipe_picture_desc * picture)90 d3d12_video_processor_end_frame(struct pipe_video_codec * codec,
91                               struct pipe_video_buffer *target,
92                               struct pipe_picture_desc *picture)
93 {
94     struct d3d12_video_processor * pD3D12Proc = (struct d3d12_video_processor *) codec;
95     debug_printf("[d3d12_video_processor] d3d12_video_processor_end_frame - "
96                 "fenceValue: %d\n",
97                 pD3D12Proc->m_fenceValue);
98 
99     if(pD3D12Proc->m_ProcessInputs.size() > pD3D12Proc->m_vpMaxInputStreams.MaxInputStreams) {
100       debug_printf("[d3d12_video_processor] ERROR: Requested number of input surfaces (%" PRIu64 ") exceeds underlying D3D12 driver capabilities (%d)\n", (uint64_t) pD3D12Proc->m_ProcessInputs.size(), pD3D12Proc->m_vpMaxInputStreams.MaxInputStreams);
101       assert(false);
102     }
103 
104     auto curOutputDesc = GetOutputStreamDesc(pD3D12Proc->m_spVideoProcessor.Get());
105     auto curOutputTexFmt = GetDesc(pD3D12Proc->m_OutputArguments.args.OutputStream[0].pTexture2D).Format;
106 
107     bool inputFmtsMatch = pD3D12Proc->m_inputStreamDescs.size() == pD3D12Proc->m_ProcessInputs.size();
108     unsigned curInputIdx = 0;
109     while( (curInputIdx < pD3D12Proc->m_inputStreamDescs.size()) && inputFmtsMatch)
110     {
111         inputFmtsMatch = inputFmtsMatch && (pD3D12Proc->m_inputStreamDescs[curInputIdx].Format == GetDesc(pD3D12Proc->m_ProcessInputs[curInputIdx].InputStream[0].pTexture2D).Format);
112         curInputIdx++;
113     }
114 
115     bool inputCountMatches = (pD3D12Proc->m_ProcessInputs.size() == pD3D12Proc->m_spVideoProcessor->GetNumInputStreamDescs());
116     bool outputFmtMatches = (curOutputDesc.Format == curOutputTexFmt);
117     bool needsVPRecreation = (
118         !inputCountMatches // Requested batch has different number of Inputs to be blit'd
119         || !outputFmtMatches // output texture format different than vid proc object expects
120         || !inputFmtsMatch // inputs texture formats different than vid proc object expects
121     );
122 
123     if(needsVPRecreation) {
124         debug_printf("[d3d12_video_processor] d3d12_video_processor_end_frame - Attempting to re-create ID3D12VideoProcessor "
125                       "input count matches %d inputFmtsMatch: %d outputFmtsMatch %d \n", inputCountMatches, inputFmtsMatch, outputFmtMatches);
126 
127         DXGI_COLOR_SPACE_TYPE OutputColorSpace = d3d12_convert_from_legacy_color_space(
128           !util_format_is_yuv(d3d12_get_pipe_format(curOutputTexFmt)),
129           util_format_get_blocksize(d3d12_get_pipe_format(curOutputTexFmt)) * 8 /*bytes to bits conversion*/,
130           /* StudioRGB= */ false,
131           /* P709= */ true,
132           /* StudioYUV= */ true);
133 
134         std::vector<DXGI_FORMAT> InputFormats;
135         for(D3D12_VIDEO_PROCESS_INPUT_STREAM_ARGUMENTS1 curInput : pD3D12Proc->m_ProcessInputs)
136         {
137             InputFormats.push_back(GetDesc(curInput.InputStream[0].pTexture2D).Format);
138         }
139         DXGI_COLOR_SPACE_TYPE InputColorSpace = d3d12_convert_from_legacy_color_space(
140           !util_format_is_yuv(d3d12_get_pipe_format(InputFormats[0])),
141           util_format_get_blocksize(d3d12_get_pipe_format(InputFormats[0])) * 8 /*bytes to bits conversion*/,
142           /* StudioRGB= */ false,
143           /* P709= */ true,
144           /* StudioYUV= */ true);
145 
146         // Release previous allocation
147         pD3D12Proc->m_spVideoProcessor.Reset();
148         if(!d3d12_video_processor_check_caps_and_create_processor(pD3D12Proc, InputFormats, InputColorSpace, curOutputTexFmt, OutputColorSpace))
149         {
150             debug_printf("[d3d12_video_processor] d3d12_video_processor_end_frame - Failure when "
151                       " trying to re-create the ID3D12VideoProcessor for current batch streams configuration\n");
152             assert(false);
153         }
154     }
155 
156     // Schedule barrier transitions
157     std::vector<D3D12_RESOURCE_BARRIER> barrier_transitions;
158     barrier_transitions.push_back(CD3DX12_RESOURCE_BARRIER::Transition(
159                                 pD3D12Proc->m_OutputArguments.args.OutputStream[0].pTexture2D,
160                                 D3D12_RESOURCE_STATE_COMMON,
161                                 D3D12_RESOURCE_STATE_VIDEO_PROCESS_WRITE));
162 
163     for(D3D12_VIDEO_PROCESS_INPUT_STREAM_ARGUMENTS1 curInput : pD3D12Proc->m_ProcessInputs)
164         barrier_transitions.push_back(CD3DX12_RESOURCE_BARRIER::Transition(
165                                     curInput.InputStream[0].pTexture2D,
166                                     D3D12_RESOURCE_STATE_COMMON,
167                                     D3D12_RESOURCE_STATE_VIDEO_PROCESS_READ));
168 
169     pD3D12Proc->m_spCommandList->ResourceBarrier(static_cast<uint32_t>(barrier_transitions.size()), barrier_transitions.data());
170 
171     // Schedule process operation
172 
173     pD3D12Proc->m_spCommandList->ProcessFrames1(pD3D12Proc->m_spVideoProcessor.Get(), &pD3D12Proc->m_OutputArguments.args, pD3D12Proc->m_ProcessInputs.size(), pD3D12Proc->m_ProcessInputs.data());
174 
175     // Schedule reverse (back to common) transitions before command list closes for current frame
176 
177     for (auto &BarrierDesc : barrier_transitions)
178         std::swap(BarrierDesc.Transition.StateBefore, BarrierDesc.Transition.StateAfter);
179 
180     pD3D12Proc->m_spCommandList->ResourceBarrier(static_cast<uint32_t>(barrier_transitions.size()), barrier_transitions.data());
181 
182     pD3D12Proc->m_PendingFences[d3d12_video_processor_pool_current_index(pD3D12Proc)].value = pD3D12Proc->m_fenceValue;
183     pD3D12Proc->m_PendingFences[d3d12_video_processor_pool_current_index(pD3D12Proc)].cmdqueue_fence = pD3D12Proc->m_spFence.Get();
184     *picture->fence = (pipe_fence_handle*) &pD3D12Proc->m_PendingFences[d3d12_video_processor_pool_current_index(pD3D12Proc)];
185 }
186 
187 void
d3d12_video_processor_process_frame(struct pipe_video_codec * codec,struct pipe_video_buffer * input_texture,const struct pipe_vpp_desc * process_properties)188 d3d12_video_processor_process_frame(struct pipe_video_codec *codec,
189                         struct pipe_video_buffer *input_texture,
190                         const struct pipe_vpp_desc *process_properties)
191 {
192     struct d3d12_video_processor * pD3D12Proc = (struct d3d12_video_processor *) codec;
193 
194     // begin_frame gets only called once so wouldn't update process_properties->src_surface_fence correctly
195     pD3D12Proc->input_surface_fence = (struct d3d12_fence*) process_properties->src_surface_fence;
196 
197     // Get the underlying resources from the pipe_video_buffers
198     struct d3d12_video_buffer *pInputVideoBuffer = (struct d3d12_video_buffer *) input_texture;
199 
200     ID3D12Resource *pSrcD3D12Res = d3d12_resource_resource(pInputVideoBuffer->texture);
201 
202     // y0 = top
203     // x0 = left
204     // x1 = right
205     // y1 = bottom
206 
207     debug_printf("d3d12_video_processor_process_frame: Adding Input ID3D12Resource: %p to scene (Output target %p)\n", pSrcD3D12Res, pD3D12Proc->m_OutputArguments.args.OutputStream[0].pTexture2D);
208     debug_printf("d3d12_video_processor_process_frame: Input box: top: %d left: %d right: %d bottom: %d\n", process_properties->src_region.y0, process_properties->src_region.x0, process_properties->src_region.x1, process_properties->src_region.y1);
209     debug_printf("d3d12_video_processor_process_frame: Output box: top: %d left: %d right: %d bottom: %d\n", process_properties->dst_region.y0, process_properties->dst_region.x0, process_properties->dst_region.x1, process_properties->dst_region.y1);
210     debug_printf("d3d12_video_processor_process_frame: Requested alpha blend mode %d global alpha: %f \n", process_properties->blend.mode, process_properties->blend.global_alpha);
211 
212     // Setup process frame arguments for current input texture.
213 
214     D3D12_VIDEO_PROCESS_INPUT_STREAM_ARGUMENTS1 InputArguments = {
215         {
216         { // D3D12_VIDEO_PROCESS_INPUT_STREAM InputStream[0];
217                 pSrcD3D12Res, // ID3D12Resource *pTexture2D;
218                 0, // UINT Subresource
219                 {//D3D12_VIDEO_PROCESS_REFERENCE_SET ReferenceSet;
220                     0, //UINT NumPastFrames;
221                     NULL, //ID3D12Resource **ppPastFrames;
222                     NULL, // UINT *pPastSubresources;
223                     0, //UINT NumFutureFrames;
224                     NULL, //ID3D12Resource **ppFutureFrames;
225                     NULL //UINT *pFutureSubresources;
226                 }
227         },
228         { // D3D12_VIDEO_PROCESS_INPUT_STREAM InputStream[1];
229                 NULL, //ID3D12Resource *pTexture2D;
230                 0, //UINT Subresource;
231                 {//D3D12_VIDEO_PROCESS_REFERENCE_SET ReferenceSet;
232                     0, //UINT NumPastFrames;
233                     NULL, //ID3D12Resource **ppPastFrames;
234                     NULL, // UINT *pPastSubresources;
235                     0, //UINT NumFutureFrames;
236                     NULL, //ID3D12Resource **ppFutureFrames;
237                     NULL //UINT *pFutureSubresources;
238                 }
239         }
240         },
241         { // D3D12_VIDEO_PROCESS_TRANSFORM Transform;
242             // y0 = top
243             // x0 = left
244             // x1 = right
245             // y1 = bottom
246             // typedef struct _RECT
247             // {
248             //     int left;
249             //     int top;
250             //     int right;
251             //     int bottom;
252             // } RECT;
253             { process_properties->src_region.x0/*left*/, process_properties->src_region.y0/*top*/, process_properties->src_region.x1/*right*/, process_properties->src_region.y1/*bottom*/ },
254             { process_properties->dst_region.x0/*left*/, process_properties->dst_region.y0/*top*/, process_properties->dst_region.x1/*right*/, process_properties->dst_region.y1/*bottom*/ }, // D3D12_RECT DestinationRectangle;
255             pD3D12Proc->m_inputStreamDescs[0].EnableOrientation ? d3d12_video_processor_convert_pipe_rotation(process_properties->orientation) : D3D12_VIDEO_PROCESS_ORIENTATION_DEFAULT, // D3D12_VIDEO_PROCESS_ORIENTATION Orientation;
256         },
257         D3D12_VIDEO_PROCESS_INPUT_STREAM_FLAG_NONE,
258         { // D3D12_VIDEO_PROCESS_INPUT_STREAM_RATE RateInfo;
259             0,
260             0,
261         },
262         // INT                                    FilterLevels[32];
263         {
264             0, // Trailing zeroes on the rest
265         },
266         //D3D12_VIDEO_PROCESS_ALPHA_BLENDING;
267         {
268             (process_properties->blend.mode == PIPE_VIDEO_VPP_BLEND_MODE_GLOBAL_ALPHA),
269             process_properties->blend.global_alpha
270         },
271         // D3D12_VIDEO_FIELD_TYPE FieldType
272         D3D12_VIDEO_FIELD_TYPE_NONE,
273     };
274 
275     debug_printf("ProcessFrame InArgs Orientation %d \n\tSrc top: %d left: %d right: %d bottom: %d\n\tDst top: %d left: %d right: %d bottom: %d\n", InputArguments.Transform.Orientation,
276         InputArguments.Transform.SourceRectangle.top, InputArguments.Transform.SourceRectangle.left, InputArguments.Transform.SourceRectangle.right, InputArguments.Transform.SourceRectangle.bottom,
277         InputArguments.Transform.DestinationRectangle.top, InputArguments.Transform.DestinationRectangle.left, InputArguments.Transform.DestinationRectangle.right, InputArguments.Transform.DestinationRectangle.bottom);
278 
279     pD3D12Proc->m_ProcessInputs.push_back(InputArguments);
280     pD3D12Proc->m_InputBuffers.push_back(pInputVideoBuffer);
281 
282     ///
283     /// Flush work to the GPU and blocking wait until GPU finishes
284     ///
285     pD3D12Proc->m_needsGPUFlush = true;
286 }
287 
288 void
d3d12_video_processor_destroy(struct pipe_video_codec * codec)289 d3d12_video_processor_destroy(struct pipe_video_codec * codec)
290 {
291     if (codec == nullptr) {
292         return;
293     }
294     // Flush pending work before destroying.
295     struct d3d12_video_processor *pD3D12Proc = (struct d3d12_video_processor *) codec;
296 
297     uint64_t curBatchFence = pD3D12Proc->m_fenceValue;
298     if (pD3D12Proc->m_needsGPUFlush)
299     {
300         d3d12_video_processor_flush(codec);
301         d3d12_video_processor_sync_completion(codec, curBatchFence, OS_TIMEOUT_INFINITE);
302     }
303 
304     // Call dtor to make ComPtr work
305     delete pD3D12Proc;
306 }
307 
308 void
d3d12_video_processor_flush(struct pipe_video_codec * codec)309 d3d12_video_processor_flush(struct pipe_video_codec * codec)
310 {
311     struct d3d12_video_processor * pD3D12Proc = (struct d3d12_video_processor *) codec;
312     assert(pD3D12Proc);
313     assert(pD3D12Proc->m_spD3D12VideoDevice);
314     assert(pD3D12Proc->m_spCommandQueue);
315 
316     debug_printf("[d3d12_video_processor] d3d12_video_processor_flush started. Will flush video queue work and CPU wait on "
317                     "fenceValue: %d\n",
318                     pD3D12Proc->m_fenceValue);
319 
320     if (!pD3D12Proc->m_needsGPUFlush) {
321         debug_printf("[d3d12_video_processor] d3d12_video_processor_flush started. Nothing to flush, all up to date.\n");
322     } else {
323         debug_printf("[d3d12_video_processor] d3d12_video_processor_flush - Promoting the output texture %p to d3d12_permanently_resident.\n",
324                      pD3D12Proc->m_OutputArguments.buffer->texture);
325 
326         // Make the resources permanently resident for video use
327         d3d12_promote_to_permanent_residency(pD3D12Proc->m_pD3D12Screen, pD3D12Proc->m_OutputArguments.buffer->texture);
328 
329         for(auto curInput : pD3D12Proc->m_InputBuffers)
330         {
331             debug_printf("[d3d12_video_processor] d3d12_video_processor_flush - Promoting the input texture %p to d3d12_permanently_resident.\n",
332                          curInput->texture);
333             // Make the resources permanently resident for video use
334             d3d12_promote_to_permanent_residency(pD3D12Proc->m_pD3D12Screen, curInput->texture);
335         }
336 
337         HRESULT hr = pD3D12Proc->m_pD3D12Screen->dev->GetDeviceRemovedReason();
338         if (hr != S_OK) {
339             debug_printf("[d3d12_video_processor] d3d12_video_processor_flush"
340                             " - D3D12Device was removed BEFORE commandlist "
341                             "execution with HR %x.\n",
342                             hr);
343             goto flush_fail;
344         }
345 
346         // Close and execute command list and wait for idle on CPU blocking
347         // this method before resetting list and allocator for next submission.
348 
349         if (pD3D12Proc->m_transitionsBeforeCloseCmdList.size() > 0) {
350             pD3D12Proc->m_spCommandList->ResourceBarrier(pD3D12Proc->m_transitionsBeforeCloseCmdList.size(),
351                                                             pD3D12Proc->m_transitionsBeforeCloseCmdList.data());
352             pD3D12Proc->m_transitionsBeforeCloseCmdList.clear();
353         }
354 
355         hr = pD3D12Proc->m_spCommandList->Close();
356         if (FAILED(hr)) {
357             debug_printf("[d3d12_video_processor] d3d12_video_processor_flush - Can't close command list with HR %x\n", hr);
358             goto flush_fail;
359         }
360 
361         // Flush any work batched in the d3d12_screen and Wait on the m_spCommandQueue
362         struct pipe_fence_handle *completion_fence = NULL;
363         pD3D12Proc->base.context->flush(pD3D12Proc->base.context, &completion_fence, PIPE_FLUSH_ASYNC | PIPE_FLUSH_HINT_FINISH);
364         struct d3d12_fence *casted_completion_fence = d3d12_fence(completion_fence);
365         pD3D12Proc->m_spCommandQueue->Wait(casted_completion_fence->cmdqueue_fence, casted_completion_fence->value);
366         pD3D12Proc->m_pD3D12Screen->base.fence_reference(&pD3D12Proc->m_pD3D12Screen->base, &completion_fence, NULL);
367 
368         struct d3d12_fence *input_surface_fence = pD3D12Proc->input_surface_fence;
369         if (input_surface_fence)
370             pD3D12Proc->m_spCommandQueue->Wait(input_surface_fence->cmdqueue_fence, input_surface_fence->value);
371 
372         ID3D12CommandList *ppCommandLists[1] = { pD3D12Proc->m_spCommandList.Get() };
373         pD3D12Proc->m_spCommandQueue->ExecuteCommandLists(1, ppCommandLists);
374         pD3D12Proc->m_spCommandQueue->Signal(pD3D12Proc->m_spFence.Get(), pD3D12Proc->m_fenceValue);
375 
376         // Validate device was not removed
377         hr = pD3D12Proc->m_pD3D12Screen->dev->GetDeviceRemovedReason();
378         if (hr != S_OK) {
379             debug_printf("[d3d12_video_processor] d3d12_video_processor_flush"
380                             " - D3D12Device was removed AFTER commandlist "
381                             "execution with HR %x, but wasn't before.\n",
382                             hr);
383             goto flush_fail;
384         }
385 
386         debug_printf(
387             "[d3d12_video_processor] d3d12_video_processor_flush - GPU signaled execution finalized for fenceValue: %d\n",
388             pD3D12Proc->m_fenceValue);
389 
390         pD3D12Proc->m_fenceValue++;
391         pD3D12Proc->m_needsGPUFlush = false;
392     }
393     pD3D12Proc->m_ProcessInputs.clear();
394     pD3D12Proc->m_InputBuffers.clear();
395     // Free the fence after completion finished
396 
397     return;
398 
399 flush_fail:
400     debug_printf("[d3d12_video_processor] d3d12_video_processor_flush failed for fenceValue: %d\n", pD3D12Proc->m_fenceValue);
401     assert(false);
402 }
403 
404 struct pipe_video_codec *
d3d12_video_processor_create(struct pipe_context * context,const struct pipe_video_codec * codec)405 d3d12_video_processor_create(struct pipe_context *context, const struct pipe_video_codec *codec)
406 {
407    ///
408    /// Initialize d3d12_video_processor
409    ///
410 
411    // Not using new doesn't call ctor and the initializations in the class declaration are lost
412    struct d3d12_video_processor *pD3D12Proc = new d3d12_video_processor;
413 
414    pD3D12Proc->m_PendingFences.resize(D3D12_VIDEO_PROC_ASYNC_DEPTH);
415    pD3D12Proc->base = *codec;
416 
417    pD3D12Proc->base.context = context;
418    pD3D12Proc->base.width = codec->width;
419    pD3D12Proc->base.height = codec->height;
420    pD3D12Proc->base.destroy = d3d12_video_processor_destroy;
421    pD3D12Proc->base.begin_frame = d3d12_video_processor_begin_frame;
422    pD3D12Proc->base.process_frame = d3d12_video_processor_process_frame;
423    pD3D12Proc->base.end_frame = d3d12_video_processor_end_frame;
424    pD3D12Proc->base.flush = d3d12_video_processor_flush;
425    pD3D12Proc->base.get_processor_fence = d3d12_video_processor_get_processor_fence;
426 
427    ///
428 
429    ///
430    /// Try initializing D3D12 Video device and check for device caps
431    ///
432 
433    struct d3d12_context *pD3D12Ctx = (struct d3d12_context *) context;
434    pD3D12Proc->m_pD3D12Context = pD3D12Ctx;
435    pD3D12Proc->m_pD3D12Screen = d3d12_screen(pD3D12Ctx->base.screen);
436 
437     // Assume defaults for now, can re-create if necessary when d3d12_video_processor_end_frame kicks off the processing
438     DXGI_COLOR_SPACE_TYPE InputColorSpace = DXGI_COLOR_SPACE_YCBCR_STUDIO_G22_LEFT_P709;
439     std::vector<DXGI_FORMAT> InputFormats = { DXGI_FORMAT_NV12 };
440     DXGI_FORMAT OutputFormat = DXGI_FORMAT_NV12;
441     DXGI_COLOR_SPACE_TYPE OutputColorSpace = DXGI_COLOR_SPACE_YCBCR_STUDIO_G22_LEFT_P709;
442 
443    ///
444    /// Create processor objects
445    ///
446    if (FAILED(pD3D12Proc->m_pD3D12Screen->dev->QueryInterface(
447           IID_PPV_ARGS(pD3D12Proc->m_spD3D12VideoDevice.GetAddressOf())))) {
448       debug_printf("[d3d12_video_processor] d3d12_video_create_processor - D3D12 Device has no Video support\n");
449       goto failed;
450    }
451 
452    if (FAILED(pD3D12Proc->m_spD3D12VideoDevice->CheckFeatureSupport(D3D12_FEATURE_VIDEO_PROCESS_MAX_INPUT_STREAMS, &pD3D12Proc->m_vpMaxInputStreams, sizeof(pD3D12Proc->m_vpMaxInputStreams)))) {
453       debug_printf("[d3d12_video_processor] d3d12_video_create_processor - Failed to query D3D12_FEATURE_VIDEO_PROCESS_MAX_INPUT_STREAMS\n");
454       goto failed;
455    }
456 
457    if (!d3d12_video_processor_check_caps_and_create_processor(pD3D12Proc, InputFormats, InputColorSpace, OutputFormat, OutputColorSpace)) {
458       debug_printf("[d3d12_video_processor] d3d12_video_create_processor - Failure on "
459                       "d3d12_video_processor_check_caps_and_create_processor\n");
460       goto failed;
461    }
462 
463    if (!d3d12_video_processor_create_command_objects(pD3D12Proc)) {
464       debug_printf(
465          "[d3d12_video_processor] d3d12_video_create_processor - Failure on d3d12_video_processor_create_command_objects\n");
466       goto failed;
467    }
468 
469     debug_printf("[d3d12_video_processor] d3d12_video_create_processor - Created successfully!\n");
470 
471    return &pD3D12Proc->base;
472 
473 failed:
474    if (pD3D12Proc != nullptr) {
475       d3d12_video_processor_destroy(&pD3D12Proc->base);
476    }
477 
478    return nullptr;
479 }
480 
481 bool
d3d12_video_processor_check_caps_and_create_processor(struct d3d12_video_processor * pD3D12Proc,std::vector<DXGI_FORMAT> InputFormats,DXGI_COLOR_SPACE_TYPE InputColorSpace,DXGI_FORMAT OutputFormat,DXGI_COLOR_SPACE_TYPE OutputColorSpace)482 d3d12_video_processor_check_caps_and_create_processor(struct d3d12_video_processor *pD3D12Proc,
483                                                         std::vector<DXGI_FORMAT> InputFormats,
484                                                         DXGI_COLOR_SPACE_TYPE InputColorSpace,
485                                                         DXGI_FORMAT OutputFormat,
486                                                         DXGI_COLOR_SPACE_TYPE OutputColorSpace)
487 {
488     HRESULT hr = S_OK;
489 
490     D3D12_VIDEO_FIELD_TYPE FieldType = D3D12_VIDEO_FIELD_TYPE_NONE;
491     D3D12_VIDEO_FRAME_STEREO_FORMAT StereoFormat = D3D12_VIDEO_FRAME_STEREO_FORMAT_NONE;
492     DXGI_RATIONAL FrameRate = { 30, 1 };
493     DXGI_RATIONAL AspectRatio = { 1, 1 };
494 
495     struct ResolStruct {
496         uint Width;
497         uint Height;
498     };
499 
500     ResolStruct resolutionsList[] = {
501         { 8192, 8192 },   // 8k
502         { 8192, 4320 },   // 8k - alternative
503         { 7680, 4800 },   // 8k - alternative
504         { 7680, 4320 },   // 8k - alternative
505         { 4096, 2304 },   // 2160p (4K)
506         { 4096, 2160 },   // 2160p (4K) - alternative
507         { 2560, 1440 },   // 1440p
508         { 1920, 1200 },   // 1200p
509         { 1920, 1080 },   // 1080p
510         { 1280, 720 },    // 720p
511         { 800, 600 },
512     };
513 
514     pD3D12Proc->m_SupportCaps =
515     {
516         0, // NodeIndex
517         { resolutionsList[0].Width, resolutionsList[0].Height, { InputFormats[0], InputColorSpace } },
518         FieldType,
519         StereoFormat,
520         FrameRate,
521         { OutputFormat, OutputColorSpace },
522         StereoFormat,
523         FrameRate,
524     };
525 
526     uint32_t idxResol = 0;
527     bool bSupportsAny = false;
528     while ((idxResol < ARRAY_SIZE(resolutionsList)) && !bSupportsAny) {
529         pD3D12Proc->m_SupportCaps.InputSample.Width = resolutionsList[idxResol].Width;
530         pD3D12Proc->m_SupportCaps.InputSample.Height = resolutionsList[idxResol].Height;
531         if (SUCCEEDED(pD3D12Proc->m_spD3D12VideoDevice->CheckFeatureSupport(D3D12_FEATURE_VIDEO_PROCESS_SUPPORT, &pD3D12Proc->m_SupportCaps, sizeof(pD3D12Proc->m_SupportCaps)))) {
532             bSupportsAny = ((pD3D12Proc->m_SupportCaps.SupportFlags & D3D12_VIDEO_PROCESS_SUPPORT_FLAG_SUPPORTED) != 0);
533         }
534         idxResol++;
535     }
536 
537     if ((pD3D12Proc->m_SupportCaps.SupportFlags & D3D12_VIDEO_PROCESS_SUPPORT_FLAG_SUPPORTED) != D3D12_VIDEO_PROCESS_SUPPORT_FLAG_SUPPORTED)
538     {
539         if((pD3D12Proc->m_SupportCaps.SupportFlags & D3D12_VIDEO_PROCESS_SUPPORT_FLAG_SUPPORTED) != D3D12_VIDEO_PROCESS_SUPPORT_FLAG_SUPPORTED) {
540         debug_printf("[d3d12_video_processor] d3d12_video_processor_check_caps_and_create_processor - D3D12_VIDEO_PROCESS_SUPPORT_FLAG_SUPPORTED not returned by driver. "
541                             "failed with SupportFlags %x\n",
542                             pD3D12Proc->m_SupportCaps.SupportFlags);
543         }
544     }
545 
546     D3D12_VIDEO_PROCESS_FILTER_FLAGS enabledFilterFlags = D3D12_VIDEO_PROCESS_FILTER_FLAG_NONE;
547 
548     bool enableOrientation = (
549         ((pD3D12Proc->m_SupportCaps.FeatureSupport & D3D12_VIDEO_PROCESS_FEATURE_FLAG_ROTATION) != 0)
550         || ((pD3D12Proc->m_SupportCaps.FeatureSupport & D3D12_VIDEO_PROCESS_FEATURE_FLAG_FLIP) != 0)
551     );
552 
553     D3D12_VIDEO_PROCESS_INPUT_STREAM_DESC inputStreamDesc = {
554         InputFormats[0],
555         InputColorSpace,
556         AspectRatio,                            // SourceAspectRatio;
557         AspectRatio,                            // DestinationAspectRatio;
558         FrameRate,                              // FrameRate
559         pD3D12Proc->m_SupportCaps.ScaleSupport.OutputSizeRange, // SourceSizeRange
560         pD3D12Proc->m_SupportCaps.ScaleSupport.OutputSizeRange, // DestinationSizeRange
561         enableOrientation,
562         enabledFilterFlags,
563         StereoFormat,
564         FieldType,
565         D3D12_VIDEO_PROCESS_DEINTERLACE_FLAG_NONE,
566         ((pD3D12Proc->m_SupportCaps.FeatureSupport & D3D12_VIDEO_PROCESS_FEATURE_FLAG_ALPHA_BLENDING) != 0)
567         && ((pD3D12Proc->m_SupportCaps.FeatureSupport & D3D12_VIDEO_PROCESS_FEATURE_FLAG_ALPHA_FILL) != 0), // EnableAlphaBlending
568         {},                                     // LumaKey
569         0,                                      // NumPastFrames
570         0,                                      // NumFutureFrames
571         false                                   // EnableAutoProcessing
572     };
573 
574     D3D12_VIDEO_PROCESS_OUTPUT_STREAM_DESC outputStreamDesc =
575     {
576         pD3D12Proc->m_SupportCaps.OutputFormat.Format,
577         OutputColorSpace,
578         D3D12_VIDEO_PROCESS_ALPHA_FILL_MODE_OPAQUE, // AlphaFillMode
579         0u,                                         // AlphaFillModeSourceStreamIndex
580         {0, 0, 0, 0},                               // BackgroundColor
581         FrameRate,                                  // FrameRate
582         false                                       // EnableStereo
583     };
584 
585     // gets the required past/future frames for VP creation
586     {
587         D3D12_FEATURE_DATA_VIDEO_PROCESS_REFERENCE_INFO referenceInfo = {};
588         referenceInfo.NodeIndex = 0;
589         D3D12_VIDEO_PROCESS_FEATURE_FLAGS featureFlags = D3D12_VIDEO_PROCESS_FEATURE_FLAG_NONE;
590         featureFlags |= outputStreamDesc.AlphaFillMode ? D3D12_VIDEO_PROCESS_FEATURE_FLAG_ALPHA_FILL : D3D12_VIDEO_PROCESS_FEATURE_FLAG_NONE;
591         featureFlags |= inputStreamDesc.LumaKey.Enable ? D3D12_VIDEO_PROCESS_FEATURE_FLAG_LUMA_KEY : D3D12_VIDEO_PROCESS_FEATURE_FLAG_NONE;
592         featureFlags |= (inputStreamDesc.StereoFormat != D3D12_VIDEO_FRAME_STEREO_FORMAT_NONE || outputStreamDesc.EnableStereo) ? D3D12_VIDEO_PROCESS_FEATURE_FLAG_STEREO : D3D12_VIDEO_PROCESS_FEATURE_FLAG_NONE;
593         featureFlags |= inputStreamDesc.EnableOrientation ? D3D12_VIDEO_PROCESS_FEATURE_FLAG_ROTATION | D3D12_VIDEO_PROCESS_FEATURE_FLAG_FLIP : D3D12_VIDEO_PROCESS_FEATURE_FLAG_NONE;
594         featureFlags |= inputStreamDesc.EnableAlphaBlending ? D3D12_VIDEO_PROCESS_FEATURE_FLAG_ALPHA_BLENDING : D3D12_VIDEO_PROCESS_FEATURE_FLAG_NONE;
595 
596         referenceInfo.DeinterlaceMode = inputStreamDesc.DeinterlaceMode;
597         referenceInfo.Filters = inputStreamDesc.FilterFlags;
598         referenceInfo.FeatureSupport = featureFlags;
599         referenceInfo.InputFrameRate = inputStreamDesc.FrameRate;
600         referenceInfo.OutputFrameRate = outputStreamDesc.FrameRate;
601         referenceInfo.EnableAutoProcessing = inputStreamDesc.EnableAutoProcessing;
602 
603         hr = pD3D12Proc->m_spD3D12VideoDevice->CheckFeatureSupport(D3D12_FEATURE_VIDEO_PROCESS_REFERENCE_INFO, &referenceInfo, sizeof(referenceInfo));
604         if (FAILED(hr)) {
605         debug_printf("[d3d12_video_processor] d3d12_video_processor_check_caps_and_create_processor - CheckFeatureSupport "
606                         "failed with HR %x\n",
607                         hr);
608         return false;
609         }
610 
611         inputStreamDesc.NumPastFrames = referenceInfo.PastFrames;
612         inputStreamDesc.NumFutureFrames = referenceInfo.FutureFrames;
613     }
614 
615     pD3D12Proc->m_outputStreamDesc = outputStreamDesc;
616 
617     debug_printf("[d3d12_video_processor]\t Creating Video Processor\n");
618     debug_printf("[d3d12_video_processor]\t NumInputs: %d\n", (int) InputFormats.size());
619 
620     pD3D12Proc->m_inputStreamDescs.clear();
621     for (unsigned i = 0; i < InputFormats.size(); i++)
622     {
623         inputStreamDesc.Format = InputFormats[i];
624         pD3D12Proc->m_inputStreamDescs.push_back(inputStreamDesc);
625         debug_printf("[d3d12_video_processor]\t Input Stream #%d Format: %d\n", i, inputStreamDesc.Format);
626     }
627     debug_printf("[d3d12_video_processor]\t Output Stream Format: %d\n", pD3D12Proc->m_outputStreamDesc.Format);
628 
629     hr = pD3D12Proc->m_spD3D12VideoDevice->CreateVideoProcessor(pD3D12Proc->m_NodeMask,
630                                                             &pD3D12Proc->m_outputStreamDesc,
631                                                             pD3D12Proc->m_inputStreamDescs.size(),
632                                                             pD3D12Proc->m_inputStreamDescs.data(),
633                                                             IID_PPV_ARGS(pD3D12Proc->m_spVideoProcessor.GetAddressOf()));
634     if (FAILED(hr)) {
635         debug_printf("[d3d12_video_processor] d3d12_video_processor_check_caps_and_create_processor - CreateVideoProcessor "
636                     "failed with HR %x\n",
637                     hr);
638         return false;
639     }
640 
641    return true;
642 }
643 
644 bool
d3d12_video_processor_create_command_objects(struct d3d12_video_processor * pD3D12Proc)645 d3d12_video_processor_create_command_objects(struct d3d12_video_processor *pD3D12Proc)
646 {
647     assert(pD3D12Proc->m_spD3D12VideoDevice);
648 
649     D3D12_COMMAND_QUEUE_DESC commandQueueDesc = { D3D12_COMMAND_LIST_TYPE_VIDEO_PROCESS };
650     HRESULT hr = pD3D12Proc->m_pD3D12Screen->dev->CreateCommandQueue(
651                 &commandQueueDesc,
652                 IID_PPV_ARGS(pD3D12Proc->m_spCommandQueue.GetAddressOf()));
653 
654     if (FAILED(hr)) {
655         debug_printf("[d3d12_video_processor] d3d12_video_processor_create_command_objects - Call to CreateCommandQueue "
656                         "failed with HR %x\n",
657                         hr);
658         return false;
659     }
660 
661     hr = pD3D12Proc->m_pD3D12Screen->dev->CreateFence(0,
662          D3D12_FENCE_FLAG_SHARED,
663          IID_PPV_ARGS(&pD3D12Proc->m_spFence));
664 
665     if (FAILED(hr)) {
666         debug_printf(
667             "[d3d12_video_processor] d3d12_video_processor_create_command_objects - Call to CreateFence failed with HR %x\n",
668             hr);
669         return false;
670     }
671 
672     pD3D12Proc->m_spCommandAllocators.resize(D3D12_VIDEO_PROC_ASYNC_DEPTH);
673     for (uint32_t i = 0; i < pD3D12Proc->m_spCommandAllocators.size() ; i++) {
674         hr = pD3D12Proc->m_pD3D12Screen->dev->CreateCommandAllocator(
675             D3D12_COMMAND_LIST_TYPE_VIDEO_PROCESS,
676             IID_PPV_ARGS(pD3D12Proc->m_spCommandAllocators[i].GetAddressOf()));
677 
678         if (FAILED(hr)) {
679             debug_printf("[d3d12_video_processor] d3d12_video_processor_create_command_objects - Call to "
680                             "CreateCommandAllocator failed with HR %x\n",
681                             hr);
682             return false;
683         }
684     }
685 
686     ComPtr<ID3D12Device4> spD3D12Device4;
687     if (FAILED(pD3D12Proc->m_pD3D12Screen->dev->QueryInterface(
688             IID_PPV_ARGS(spD3D12Device4.GetAddressOf())))) {
689         debug_printf(
690             "[d3d12_video_processor] d3d12_video_processor_create_processor - D3D12 Device has no ID3D12Device4 support\n");
691         return false;
692     }
693 
694     hr = spD3D12Device4->CreateCommandList1(0,
695                                             D3D12_COMMAND_LIST_TYPE_VIDEO_PROCESS,
696                                             D3D12_COMMAND_LIST_FLAG_NONE,
697                                             IID_PPV_ARGS(pD3D12Proc->m_spCommandList.GetAddressOf()));
698 
699     if (FAILED(hr)) {
700         debug_printf("[d3d12_video_processor] d3d12_video_processor_create_command_objects - Call to CreateCommandList "
701                         "failed with HR %x\n",
702                         hr);
703         return false;
704     }
705 
706     return true;
707 }
708 
709 D3D12_VIDEO_PROCESS_ORIENTATION
d3d12_video_processor_convert_pipe_rotation(enum pipe_video_vpp_orientation orientation_flags)710 d3d12_video_processor_convert_pipe_rotation(enum pipe_video_vpp_orientation orientation_flags)
711 {
712     D3D12_VIDEO_PROCESS_ORIENTATION result = D3D12_VIDEO_PROCESS_ORIENTATION_DEFAULT;
713 
714     if(orientation_flags & PIPE_VIDEO_VPP_ROTATION_90)
715     {
716         result = (orientation_flags & PIPE_VIDEO_VPP_FLIP_HORIZONTAL) ? D3D12_VIDEO_PROCESS_ORIENTATION_CLOCKWISE_90_FLIP_HORIZONTAL : D3D12_VIDEO_PROCESS_ORIENTATION_CLOCKWISE_90;
717         debug_printf("d3d12_video_processor_process_frame: Orientation Mode: %s\n", (orientation_flags & PIPE_VIDEO_VPP_FLIP_HORIZONTAL) ? "D3D12_VIDEO_PROCESS_ORIENTATION_CLOCKWISE_90_FLIP_HORIZONTAL" : "D3D12_VIDEO_PROCESS_ORIENTATION_CLOCKWISE_90");
718     }
719     else if(orientation_flags & PIPE_VIDEO_VPP_ROTATION_180)
720     {
721         result = D3D12_VIDEO_PROCESS_ORIENTATION_CLOCKWISE_180;
722         debug_printf("d3d12_video_processor_process_frame: Orientation Mode: D3D12_VIDEO_PROCESS_ORIENTATION_CLOCKWISE_180\n");
723     }
724     else if(orientation_flags & PIPE_VIDEO_VPP_ROTATION_270)
725     {
726         result = (orientation_flags & PIPE_VIDEO_VPP_FLIP_HORIZONTAL) ? D3D12_VIDEO_PROCESS_ORIENTATION_CLOCKWISE_270_FLIP_HORIZONTAL : D3D12_VIDEO_PROCESS_ORIENTATION_CLOCKWISE_270;
727         debug_printf("d3d12_video_processor_process_frame: Orientation Mode: %s\n", (orientation_flags & PIPE_VIDEO_VPP_FLIP_HORIZONTAL) ? "D3D12_VIDEO_PROCESS_ORIENTATION_CLOCKWISE_270_FLIP_HORIZONTAL" : "D3D12_VIDEO_PROCESS_ORIENTATION_CLOCKWISE_270");
728     }
729     else if(orientation_flags & PIPE_VIDEO_VPP_FLIP_HORIZONTAL)
730     {
731         result = D3D12_VIDEO_PROCESS_ORIENTATION_FLIP_HORIZONTAL;
732         debug_printf("d3d12_video_processor_process_frame: Orientation Mode: D3D12_VIDEO_PROCESS_ORIENTATION_FLIP_HORIZONTAL\n");
733     }
734     else if(orientation_flags & PIPE_VIDEO_VPP_FLIP_VERTICAL)
735     {
736         result = D3D12_VIDEO_PROCESS_ORIENTATION_FLIP_VERTICAL;
737         debug_printf("d3d12_video_processor_process_frame: Orientation Mode: D3D12_VIDEO_PROCESS_ORIENTATION_FLIP_VERTICAL\n");
738     }
739 
740     return result;
741 }
742 
743 uint64_t
d3d12_video_processor_pool_current_index(struct d3d12_video_processor * pD3D12Proc)744 d3d12_video_processor_pool_current_index(struct d3d12_video_processor *pD3D12Proc)
745 {
746    return pD3D12Proc->m_fenceValue % D3D12_VIDEO_PROC_ASYNC_DEPTH;
747 }
748 
749 
750 bool
d3d12_video_processor_ensure_fence_finished(struct pipe_video_codec * codec,uint64_t fenceValueToWaitOn,uint64_t timeout_ns)751 d3d12_video_processor_ensure_fence_finished(struct pipe_video_codec *codec,
752                                           uint64_t fenceValueToWaitOn,
753                                           uint64_t timeout_ns)
754 {
755    bool wait_result = true;
756    struct d3d12_video_processor *pD3D12Proc = (struct d3d12_video_processor *) codec;
757    HRESULT hr = S_OK;
758    uint64_t completedValue = pD3D12Proc->m_spFence->GetCompletedValue();
759 
760    debug_printf(
761       "[d3d12_video_processor] d3d12_video_processor_ensure_fence_finished - Waiting for fence (with timeout_ns %" PRIu64
762       ") to finish with "
763       "fenceValue: %" PRIu64 " - Current Fence Completed Value %" PRIu64 "\n",
764       timeout_ns,
765       fenceValueToWaitOn,
766       completedValue);
767 
768    if (completedValue < fenceValueToWaitOn) {
769 
770       HANDLE event = {};
771       int event_fd = 0;
772       event = d3d12_fence_create_event(&event_fd);
773 
774       hr = pD3D12Proc->m_spFence->SetEventOnCompletion(fenceValueToWaitOn, event);
775       if (FAILED(hr)) {
776          debug_printf("[d3d12_video_processor] d3d12_video_processor_ensure_fence_finished - SetEventOnCompletion for "
777                       "fenceValue %" PRIu64 " failed with HR %x\n",
778                       fenceValueToWaitOn,
779                       hr);
780          goto ensure_fence_finished_fail;
781       }
782 
783       wait_result = d3d12_fence_wait_event(event, event_fd, timeout_ns);
784       d3d12_fence_close_event(event, event_fd);
785 
786       debug_printf("[d3d12_video_processor] d3d12_video_processor_ensure_fence_finished - Waiting on fence to be done with "
787                    "fenceValue: %" PRIu64 " - current CompletedValue: %" PRIu64 "\n",
788                    fenceValueToWaitOn,
789                    completedValue);
790    } else {
791       debug_printf("[d3d12_video_processor] d3d12_video_processor_ensure_fence_finished - Fence already done with "
792                    "fenceValue: %" PRIu64 " - current CompletedValue: %" PRIu64 "\n",
793                    fenceValueToWaitOn,
794                    completedValue);
795    }
796    return wait_result;
797 
798 ensure_fence_finished_fail:
799    debug_printf("[d3d12_video_processor] d3d12_video_processor_sync_completion failed for fenceValue: %" PRIu64 "\n",
800                 fenceValueToWaitOn);
801    assert(false);
802    return false;
803 }
804 
805 bool
d3d12_video_processor_sync_completion(struct pipe_video_codec * codec,uint64_t fenceValueToWaitOn,uint64_t timeout_ns)806 d3d12_video_processor_sync_completion(struct pipe_video_codec *codec, uint64_t fenceValueToWaitOn, uint64_t timeout_ns)
807 {
808    struct d3d12_video_processor *pD3D12Proc = (struct d3d12_video_processor *) codec;
809    assert(pD3D12Proc);
810    assert(pD3D12Proc->m_spD3D12VideoDevice);
811    assert(pD3D12Proc->m_spCommandQueue);
812    HRESULT hr = S_OK;
813 
814    ASSERTED bool wait_result = d3d12_video_processor_ensure_fence_finished(codec, fenceValueToWaitOn, timeout_ns);
815    assert(wait_result);
816 
817    hr =
818       pD3D12Proc->m_spCommandAllocators[fenceValueToWaitOn % D3D12_VIDEO_PROC_ASYNC_DEPTH]->Reset();
819    if (FAILED(hr)) {
820       debug_printf("m_spCommandAllocator->Reset() failed with %x.\n", hr);
821       goto sync_with_token_fail;
822    }
823 
824    // Validate device was not removed
825    hr = pD3D12Proc->m_pD3D12Screen->dev->GetDeviceRemovedReason();
826    if (hr != S_OK) {
827       debug_printf("[d3d12_video_processor] d3d12_video_processor_sync_completion"
828                    " - D3D12Device was removed AFTER d3d12_video_processor_ensure_fence_finished "
829                    "execution with HR %x, but wasn't before.\n",
830                    hr);
831       goto sync_with_token_fail;
832    }
833 
834    debug_printf(
835       "[d3d12_video_processor] d3d12_video_processor_sync_completion - GPU execution finalized for fenceValue: %" PRIu64
836       "\n",
837       fenceValueToWaitOn);
838 
839    return wait_result;
840 
841 sync_with_token_fail:
842    debug_printf("[d3d12_video_processor] d3d12_video_processor_sync_completion failed for fenceValue: %" PRIu64 "\n",
843                 fenceValueToWaitOn);
844    assert(false);
845    return false;
846 }
847 
d3d12_video_processor_get_processor_fence(struct pipe_video_codec * codec,struct pipe_fence_handle * fence,uint64_t timeout)848 int d3d12_video_processor_get_processor_fence(struct pipe_video_codec *codec,
849                                               struct pipe_fence_handle *fence,
850                                               uint64_t timeout)
851 {
852    struct d3d12_fence *fenceValueToWaitOn = (struct d3d12_fence *) fence;
853    assert(fenceValueToWaitOn);
854 
855    ASSERTED bool wait_res = d3d12_video_processor_sync_completion(codec, fenceValueToWaitOn->value, timeout);
856 
857    // Return semantics based on p_video_codec interface
858    // ret == 0 -> work in progress
859    // ret != 0 -> work completed
860    return wait_res ? 1 : 0;
861 }
862