d3d11decoder: Work around Intel DXVA driver crash
[platform/upstream/gstreamer.git] / subprojects / gst-plugins-bad / gst-libs / gst / d3d11 / gstd3d11memory.cpp
1 /* GStreamer
2  * Copyright (C) 2019 Seungha Yang <seungha.yang@navercorp.com>
3  * Copyright (C) 2020 Seungha Yang <seungha@centricular.com>
4  *
5  * This library is free software; you can redistribute it and/or
6  * modify it under the terms of the GNU Library General Public
7  * License as published by the Free Software Foundation; either
8  * version 2 of the License, or (at your option) any later version.
9  *
10  * This library is distributed in the hope that it will be useful,
11  * but WITHOUT ANY WARRANTY; without even the implied warranty of
12  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
13  * Library General Public License for more details.
14  *
15  * You should have received a copy of the GNU Library General Public
16  * License along with this library; if not, write to the
17  * Free Software Foundation, Inc., 51 Franklin St, Fifth Floor,
18  * Boston, MA 02110-1301, USA.
19  */
20
21 #ifdef HAVE_CONFIG_H
22 #include "config.h"
23 #endif
24
25 #include <string.h>
26 #include "gstd3d11memory.h"
27 #include "gstd3d11device.h"
28 #include "gstd3d11utils.h"
29 #include "gstd3d11_private.h"
30
31 GST_DEBUG_CATEGORY_STATIC (gst_d3d11_allocator_debug);
32 #define GST_CAT_DEFAULT gst_d3d11_allocator_debug
33
34 static GstAllocator *_d3d11_memory_allocator;
35
36 /* GstD3D11AllocationParams */
37 static void gst_d3d11_allocation_params_init (GType type);
38 G_DEFINE_BOXED_TYPE_WITH_CODE (GstD3D11AllocationParams,
39     gst_d3d11_allocation_params,
40     (GBoxedCopyFunc) gst_d3d11_allocation_params_copy,
41     (GBoxedFreeFunc) gst_d3d11_allocation_params_free,
42     gst_d3d11_allocation_params_init (g_define_type_id));
43
44 /**
45  * gst_d3d11_allocation_params_new:
46  * @device: a #GstD3D11Device
47  * @info: a #GstVideoInfo
48  * @flags: a #GstD3D11AllocationFlags
49  * @bind_flags: D3D11_BIND_FLAG value used for creating Direct3D11 texture
50  *
51  * Create #GstD3D11AllocationParams object which is used by #GstD3D11BufferPool
52  * and #GstD3D11Allocator in order to allocate new ID3D11Texture2D
53  * object with given configuration
54  *
55  * Returns: a #GstD3D11AllocationParams or %NULL if @info is not supported
56  *
57  * Since: 1.20
58  */
59 GstD3D11AllocationParams *
60 gst_d3d11_allocation_params_new (GstD3D11Device * device, GstVideoInfo * info,
61     GstD3D11AllocationFlags flags, guint bind_flags)
62 {
63   GstD3D11AllocationParams *ret;
64   GstD3D11Format d3d11_format;
65   guint i;
66
67   g_return_val_if_fail (info != NULL, NULL);
68
69   if (!gst_d3d11_device_get_format (device, GST_VIDEO_INFO_FORMAT (info),
70           &d3d11_format)) {
71     GST_WARNING ("Couldn't get d3d11 format");
72     return NULL;
73   }
74
75   ret = g_new0 (GstD3D11AllocationParams, 1);
76
77   ret->info = *info;
78   ret->aligned_info = *info;
79   ret->d3d11_format = d3d11_format;
80
81   /* Usage Flag
82    * https://docs.microsoft.com/en-us/windows/win32/api/d3d11/ne-d3d11-d3d11_usage
83    *
84    * +----------------------------------------------------------+
85    * | Resource Usage | Default | Dynamic | Immutable | Staging |
86    * +----------------+---------+---------+-----------+---------+
87    * | GPU-Read       | Yes     | Yes     | Yes       | Yes     |
88    * | GPU-Write      | Yes     |         |           | Yes     |
89    * | CPU-Read       |         |         |           | Yes     |
90    * | CPU-Write      |         | Yes     |           | Yes     |
91    * +----------------------------------------------------------+
92    */
93
94   /* If corresponding dxgi format is undefined, use resource format instead */
95   if (d3d11_format.dxgi_format == DXGI_FORMAT_UNKNOWN) {
96     for (i = 0; i < GST_VIDEO_INFO_N_PLANES (info); i++) {
97       g_assert (d3d11_format.resource_format[i] != DXGI_FORMAT_UNKNOWN);
98
99       ret->desc[i].Width = GST_VIDEO_INFO_COMP_WIDTH (info, i);
100       ret->desc[i].Height = GST_VIDEO_INFO_COMP_HEIGHT (info, i);
101       ret->desc[i].MipLevels = 1;
102       ret->desc[i].ArraySize = 1;
103       ret->desc[i].Format = d3d11_format.resource_format[i];
104       ret->desc[i].SampleDesc.Count = 1;
105       ret->desc[i].SampleDesc.Quality = 0;
106       ret->desc[i].Usage = D3D11_USAGE_DEFAULT;
107       ret->desc[i].BindFlags = bind_flags;
108     }
109   } else {
110     ret->desc[0].Width = GST_VIDEO_INFO_WIDTH (info);
111     ret->desc[0].Height = GST_VIDEO_INFO_HEIGHT (info);
112     ret->desc[0].MipLevels = 1;
113     ret->desc[0].ArraySize = 1;
114     ret->desc[0].Format = d3d11_format.dxgi_format;
115     ret->desc[0].SampleDesc.Count = 1;
116     ret->desc[0].SampleDesc.Quality = 0;
117     ret->desc[0].Usage = D3D11_USAGE_DEFAULT;
118     ret->desc[0].BindFlags = bind_flags;
119   }
120
121   ret->flags = flags;
122
123   return ret;
124 }
125
126 /**
127  * gst_d3d11_allocation_params_alignment:
128  * @params: a #GstD3D11AllocationParams
129  * @align: a #GstVideoAlignment
130  *
131  * Adjust Width and Height fields of D3D11_TEXTURE2D_DESC with given
132  * @align
133  *
134  * Returns: %TRUE if alignment could be applied
135  *
136  * Since: 1.20
137  */
138 gboolean
139 gst_d3d11_allocation_params_alignment (GstD3D11AllocationParams * params,
140     GstVideoAlignment * align)
141 {
142   guint i;
143   guint padding_width, padding_height;
144   GstVideoInfo *info;
145   GstVideoInfo new_info;
146
147   g_return_val_if_fail (params != NULL, FALSE);
148   g_return_val_if_fail (align != NULL, FALSE);
149
150   /* d3d11 does not support stride align. Consider padding only */
151   padding_width = align->padding_left + align->padding_right;
152   padding_height = align->padding_top + align->padding_bottom;
153
154   info = &params->info;
155
156   if (!gst_video_info_set_format (&new_info, GST_VIDEO_INFO_FORMAT (info),
157           GST_VIDEO_INFO_WIDTH (info) + padding_width,
158           GST_VIDEO_INFO_HEIGHT (info) + padding_height)) {
159     GST_WARNING ("Set format fail");
160     return FALSE;
161   }
162
163   params->aligned_info = new_info;
164
165   for (i = 0; i < GST_VIDEO_INFO_N_PLANES (info); i++) {
166     params->desc[i].Width = GST_VIDEO_INFO_COMP_WIDTH (&new_info, i);
167     params->desc[i].Height = GST_VIDEO_INFO_COMP_HEIGHT (&new_info, i);
168   }
169
170   return TRUE;
171 }
172
173 /**
174  * gst_d3d11_allocation_params_copy:
175  * @src: a #GstD3D11AllocationParams
176  *
177  * Returns: a copy of @src
178  *
179  * Since: 1.20
180  */
181 GstD3D11AllocationParams *
182 gst_d3d11_allocation_params_copy (GstD3D11AllocationParams * src)
183 {
184   GstD3D11AllocationParams *dst;
185
186   g_return_val_if_fail (src != NULL, NULL);
187
188   dst = g_new0 (GstD3D11AllocationParams, 1);
189   memcpy (dst, src, sizeof (GstD3D11AllocationParams));
190
191   return dst;
192 }
193
194 /**
195  * gst_d3d11_allocation_params_free:
196  * @params: a #GstD3D11AllocationParams
197  *
198  * Free @params
199  *
200  * Since: 1.20
201  */
202 void
203 gst_d3d11_allocation_params_free (GstD3D11AllocationParams * params)
204 {
205   g_free (params);
206 }
207
208 static gint
209 gst_d3d11_allocation_params_compare (const GstD3D11AllocationParams * p1,
210     const GstD3D11AllocationParams * p2)
211 {
212   g_return_val_if_fail (p1 != NULL, -1);
213   g_return_val_if_fail (p2 != NULL, -1);
214
215   if (p1 == p2)
216     return 0;
217
218   return -1;
219 }
220
221 static void
222 gst_d3d11_allocation_params_init (GType type)
223 {
224   static GstValueTable table = {
225     0, (GstValueCompareFunc) gst_d3d11_allocation_params_compare,
226     NULL, NULL
227   };
228
229   table.type = type;
230   gst_value_register (&table);
231 }
232
233 /* GstD3D11Memory */
234 #define GST_D3D11_MEMORY_GET_LOCK(m) (&(GST_D3D11_MEMORY_CAST(m)->priv->lock))
235 #define GST_D3D11_MEMORY_LOCK(m) G_STMT_START { \
236   GST_TRACE("Locking %p from thread %p", (m), g_thread_self()); \
237   g_mutex_lock(GST_D3D11_MEMORY_GET_LOCK(m)); \
238   GST_TRACE("Locked %p from thread %p", (m), g_thread_self()); \
239 } G_STMT_END
240
241 #define GST_D3D11_MEMORY_UNLOCK(m) G_STMT_START { \
242   GST_TRACE("Unlocking %p from thread %p", (m), g_thread_self()); \
243   g_mutex_unlock(GST_D3D11_MEMORY_GET_LOCK(m)); \
244 } G_STMT_END
245
246 struct _GstD3D11MemoryPrivate
247 {
248   ID3D11Texture2D *texture;
249   ID3D11Buffer *buffer;
250
251   ID3D11Resource *staging;
252
253   D3D11_TEXTURE2D_DESC desc;
254   D3D11_BUFFER_DESC buffer_desc;
255
256   guint subresource_index;
257
258   ID3D11ShaderResourceView *shader_resource_view[GST_VIDEO_MAX_PLANES];
259   guint num_shader_resource_views;
260
261   ID3D11RenderTargetView *render_target_view[GST_VIDEO_MAX_PLANES];
262   guint num_render_target_views;
263
264   ID3D11VideoDecoderOutputView *decoder_output_view;
265   ID3D11VideoDecoder *decoder_handle;
266
267   ID3D11VideoProcessorInputView *processor_input_view;
268   ID3D11VideoProcessorOutputView *processor_output_view;
269
270   D3D11_MAPPED_SUBRESOURCE map;
271
272   GstD3D11MemoryNativeType native_type;
273
274   GMutex lock;
275   gint cpu_map_count;
276 };
277
278 static inline D3D11_MAP
279 gst_d3d11_map_flags_to_d3d11 (GstMapFlags flags)
280 {
281   if ((flags & GST_MAP_READWRITE) == GST_MAP_READWRITE)
282     return D3D11_MAP_READ_WRITE;
283   else if ((flags & GST_MAP_WRITE) == GST_MAP_WRITE)
284     return D3D11_MAP_WRITE;
285   else if ((flags & GST_MAP_READ) == GST_MAP_READ)
286     return D3D11_MAP_READ;
287   else
288     g_assert_not_reached ();
289
290   return D3D11_MAP_READ;
291 }
292
293 static ID3D11Texture2D *
294 gst_d3d11_allocate_staging_texture (GstD3D11Device * device,
295     const D3D11_TEXTURE2D_DESC * ref)
296 {
297   D3D11_TEXTURE2D_DESC desc = { 0, };
298   ID3D11Texture2D *texture = NULL;
299   ID3D11Device *device_handle = gst_d3d11_device_get_device_handle (device);
300   HRESULT hr;
301
302   desc.Width = ref->Width;
303   desc.Height = ref->Height;
304   desc.MipLevels = 1;
305   desc.Format = ref->Format;
306   desc.SampleDesc.Count = 1;
307   desc.ArraySize = 1;
308   desc.Usage = D3D11_USAGE_STAGING;
309   desc.CPUAccessFlags = (D3D11_CPU_ACCESS_READ | D3D11_CPU_ACCESS_WRITE);
310
311   hr = device_handle->CreateTexture2D (&desc, NULL, &texture);
312   if (!gst_d3d11_result (hr, device)) {
313     GST_ERROR_OBJECT (device, "Failed to create texture");
314     return NULL;
315   }
316
317   return texture;
318 }
319
320 /* Must be called with d3d11 device lock */
321 static gboolean
322 gst_d3d11_memory_map_cpu_access (GstD3D11Memory * dmem, D3D11_MAP map_type)
323 {
324   GstD3D11MemoryPrivate *priv = dmem->priv;
325   HRESULT hr;
326   ID3D11DeviceContext *device_context =
327       gst_d3d11_device_get_device_context_handle (dmem->device);
328
329   hr = device_context->Map (priv->staging, 0, map_type, 0, &priv->map);
330
331   if (!gst_d3d11_result (hr, dmem->device)) {
332     GST_ERROR_OBJECT (GST_MEMORY_CAST (dmem)->allocator,
333         "Failed to map staging texture (0x%x)", (guint) hr);
334     return FALSE;
335   }
336
337   return TRUE;
338 }
339
340 /* Must be called with d3d11 device lock */
341 static void
342 gst_d3d11_memory_upload (GstD3D11Memory * dmem)
343 {
344   GstD3D11MemoryPrivate *priv = dmem->priv;
345   ID3D11DeviceContext *device_context;
346
347   if (!priv->staging ||
348       !GST_MEMORY_FLAG_IS_SET (dmem, GST_D3D11_MEMORY_TRANSFER_NEED_UPLOAD))
349     return;
350
351   device_context = gst_d3d11_device_get_device_context_handle (dmem->device);
352   device_context->CopySubresourceRegion (priv->texture, priv->subresource_index,
353       0, 0, 0, priv->staging, 0, NULL);
354 }
355
356 /* Must be called with d3d11 device lock */
357 static void
358 gst_d3d11_memory_download (GstD3D11Memory * dmem)
359 {
360   GstD3D11MemoryPrivate *priv = dmem->priv;
361   ID3D11DeviceContext *device_context;
362
363   if (!priv->staging ||
364       !GST_MEMORY_FLAG_IS_SET (dmem, GST_D3D11_MEMORY_TRANSFER_NEED_DOWNLOAD))
365     return;
366
367   device_context = gst_d3d11_device_get_device_context_handle (dmem->device);
368   device_context->CopySubresourceRegion (priv->staging, 0, 0, 0, 0,
369       priv->texture, priv->subresource_index, NULL);
370 }
371
372 static gpointer
373 gst_d3d11_memory_map_full (GstMemory * mem, GstMapInfo * info, gsize maxsize)
374 {
375   GstD3D11Memory *dmem = GST_D3D11_MEMORY_CAST (mem);
376   GstD3D11MemoryPrivate *priv = dmem->priv;
377   GstMapFlags flags = info->flags;
378   gpointer ret = NULL;
379
380   gst_d3d11_device_lock (dmem->device);
381   GST_D3D11_MEMORY_LOCK (dmem);
382
383   memset (info->user_data, 0, sizeof (info->user_data));
384   info->user_data[0] = GUINT_TO_POINTER (dmem->priv->subresource_index);
385
386   if ((flags & GST_MAP_D3D11) == GST_MAP_D3D11) {
387     if (priv->native_type == GST_D3D11_MEMORY_NATIVE_TYPE_BUFFER) {
388       /* FIXME: handle non-staging buffer */
389       g_assert (priv->buffer != nullptr);
390       ret = priv->buffer;
391     } else {
392       gst_d3d11_memory_upload (dmem);
393       GST_MEMORY_FLAG_UNSET (dmem, GST_D3D11_MEMORY_TRANSFER_NEED_UPLOAD);
394
395       if ((flags & GST_MAP_WRITE) == GST_MAP_WRITE)
396         GST_MINI_OBJECT_FLAG_SET (dmem,
397             GST_D3D11_MEMORY_TRANSFER_NEED_DOWNLOAD);
398
399       g_assert (priv->texture != NULL);
400       ret = priv->texture;
401       goto out;
402     }
403   }
404
405   if (priv->cpu_map_count == 0) {
406     D3D11_MAP map_type;
407
408     /* FIXME: handle non-staging buffer */
409     if (priv->native_type == GST_D3D11_MEMORY_NATIVE_TYPE_TEXTURE_2D) {
410       /* Allocate staging texture for CPU access */
411       if (!priv->staging) {
412         priv->staging = gst_d3d11_allocate_staging_texture (dmem->device,
413             &priv->desc);
414         if (!priv->staging) {
415           GST_ERROR_OBJECT (mem->allocator, "Couldn't create staging texture");
416           goto out;
417         }
418
419         /* first memory, always need download to staging */
420         GST_MINI_OBJECT_FLAG_SET (mem, GST_D3D11_MEMORY_TRANSFER_NEED_DOWNLOAD);
421       }
422
423       gst_d3d11_memory_download (dmem);
424     }
425
426     map_type = gst_d3d11_map_flags_to_d3d11 (flags);
427     if (!gst_d3d11_memory_map_cpu_access (dmem, map_type)) {
428       GST_ERROR_OBJECT (mem->allocator, "Couldn't map staging texture");
429       goto out;
430     }
431   }
432
433   if ((flags & GST_MAP_WRITE) == GST_MAP_WRITE) {
434     GST_MINI_OBJECT_FLAG_SET (mem, GST_D3D11_MEMORY_TRANSFER_NEED_UPLOAD);
435   }
436
437   GST_MEMORY_FLAG_UNSET (mem, GST_D3D11_MEMORY_TRANSFER_NEED_DOWNLOAD);
438
439   priv->cpu_map_count++;
440   ret = dmem->priv->map.pData;
441
442 out:
443   GST_D3D11_MEMORY_UNLOCK (dmem);
444   gst_d3d11_device_unlock (dmem->device);
445
446   return ret;
447 }
448
449 /* Must be called with d3d11 device lock */
450 static void
451 gst_d3d11_memory_unmap_cpu_access (GstD3D11Memory * dmem)
452 {
453   GstD3D11MemoryPrivate *priv = dmem->priv;
454   ID3D11DeviceContext *device_context =
455       gst_d3d11_device_get_device_context_handle (dmem->device);
456
457   device_context->Unmap (priv->staging, 0);
458 }
459
460 static void
461 gst_d3d11_memory_unmap_full (GstMemory * mem, GstMapInfo * info)
462 {
463   GstD3D11Memory *dmem = GST_D3D11_MEMORY_CAST (mem);
464   GstD3D11MemoryPrivate *priv = dmem->priv;
465
466   gst_d3d11_device_lock (dmem->device);
467   GST_D3D11_MEMORY_LOCK (dmem);
468
469   if ((info->flags & GST_MAP_D3D11) == GST_MAP_D3D11) {
470     if ((info->flags & GST_MAP_WRITE) == GST_MAP_WRITE)
471       GST_MINI_OBJECT_FLAG_SET (mem, GST_D3D11_MEMORY_TRANSFER_NEED_DOWNLOAD);
472
473     goto out;
474   }
475
476   if ((info->flags & GST_MAP_WRITE) == GST_MAP_WRITE)
477     GST_MINI_OBJECT_FLAG_SET (mem, GST_D3D11_MEMORY_TRANSFER_NEED_UPLOAD);
478
479   priv->cpu_map_count--;
480   if (priv->cpu_map_count > 0)
481     goto out;
482
483   gst_d3d11_memory_unmap_cpu_access (dmem);
484
485 out:
486   GST_D3D11_MEMORY_UNLOCK (dmem);
487   gst_d3d11_device_unlock (dmem->device);
488 }
489
490 static GstMemory *
491 gst_d3d11_memory_share (GstMemory * mem, gssize offset, gssize size)
492 {
493   /* TODO: impl. */
494   return NULL;
495 }
496
497 static gboolean
498 gst_d3d11_memory_update_size (GstMemory * mem)
499 {
500   GstD3D11Memory *dmem = GST_D3D11_MEMORY_CAST (mem);
501   GstD3D11MemoryPrivate *priv = dmem->priv;
502   gsize offset[GST_VIDEO_MAX_PLANES];
503   gint stride[GST_VIDEO_MAX_PLANES];
504   gsize size;
505   D3D11_TEXTURE2D_DESC *desc = &priv->desc;
506   gboolean ret = FALSE;
507
508   if (!priv->staging) {
509     priv->staging = gst_d3d11_allocate_staging_texture (dmem->device,
510         &priv->desc);
511     if (!priv->staging) {
512       GST_ERROR_OBJECT (mem->allocator, "Couldn't create staging texture");
513       return FALSE;
514     }
515
516     GST_MINI_OBJECT_FLAG_SET (mem, GST_D3D11_MEMORY_TRANSFER_NEED_DOWNLOAD);
517   }
518
519   gst_d3d11_device_lock (dmem->device);
520   if (!gst_d3d11_memory_map_cpu_access (dmem, D3D11_MAP_READ_WRITE)) {
521     GST_ERROR_OBJECT (mem->allocator, "Couldn't map staging texture");
522     return FALSE;
523   }
524
525   gst_d3d11_memory_unmap_cpu_access (dmem);
526
527   if (!gst_d3d11_dxgi_format_get_size (desc->Format, desc->Width, desc->Height,
528           priv->map.RowPitch, offset, stride, &size)) {
529     GST_ERROR_OBJECT (mem->allocator, "Couldn't calculate memory size");
530     goto out;
531   }
532
533   mem->maxsize = mem->size = size;
534   ret = TRUE;
535
536 out:
537   gst_d3d11_device_unlock (dmem->device);
538   return ret;
539 }
540
541 /**
542  * gst_is_d3d11_memory:
543  * @mem: a #GstMemory
544  *
545  * Returns: whether @mem is a #GstD3D11Memory
546  *
547  * Since: 1.20
548  */
549 gboolean
550 gst_is_d3d11_memory (GstMemory * mem)
551 {
552   return mem != NULL && mem->allocator != NULL &&
553       (GST_IS_D3D11_ALLOCATOR (mem->allocator) ||
554       GST_IS_D3D11_POOL_ALLOCATOR (mem->allocator));
555 }
556
557 /**
558  * gst_d3d11_memory_get_native_type:
559  * @mem: a #GstD3D11Memory
560  *
561  * Returns: a #GstD3D11MemoryNativeType
562  *
563  * Since: 1.22
564  */
565 GstD3D11MemoryNativeType
566 gst_d3d11_memory_get_native_type (GstD3D11Memory * mem)
567 {
568   if (!gst_is_d3d11_memory (GST_MEMORY_CAST (mem)))
569     return GST_D3D11_MEMORY_NATIVE_TYPE_INVALID;
570
571   return mem->priv->native_type;
572 }
573
574 /**
575  * gst_d3d11_memory_init_once:
576  *
577  * Initializes the Direct3D11 Texture allocator. It is safe to call
578  * this function multiple times. This must be called before any other
579  * GstD3D11Memory operation.
580  *
581  * Since: 1.20
582  */
583 void
584 gst_d3d11_memory_init_once (void)
585 {
586   static gsize _init = 0;
587
588   if (g_once_init_enter (&_init)) {
589
590     GST_DEBUG_CATEGORY_INIT (gst_d3d11_allocator_debug, "d3d11allocator", 0,
591         "Direct3D11 Texture Allocator");
592
593     _d3d11_memory_allocator =
594         (GstAllocator *) g_object_new (GST_TYPE_D3D11_ALLOCATOR, NULL);
595     gst_object_ref_sink (_d3d11_memory_allocator);
596
597     gst_allocator_register (GST_D3D11_MEMORY_NAME, _d3d11_memory_allocator);
598     g_once_init_leave (&_init, 1);
599   }
600 }
601
602 /**
603  * gst_d3d11_memory_get_resource_handle:
604  * @mem: a #GstD3D11Memory
605  *
606  * Returns: (transfer none): a ID3D11Resource handle. Caller must not release
607  * returned handle.
608  *
609  * Since: 1.22
610  */
611 ID3D11Resource *
612 gst_d3d11_memory_get_resource_handle (GstD3D11Memory * mem)
613 {
614   g_return_val_if_fail (gst_is_d3d11_memory (GST_MEMORY_CAST (mem)), NULL);
615
616   switch (mem->priv->native_type) {
617     case GST_D3D11_MEMORY_NATIVE_TYPE_BUFFER:
618       return mem->priv->buffer;
619     case GST_D3D11_MEMORY_NATIVE_TYPE_TEXTURE_2D:
620       return mem->priv->texture;
621     default:
622       break;
623   }
624
625   return nullptr;
626 }
627
628 /**
629  * gst_d3d11_memory_get_subresource_index:
630  * @mem: a #GstD3D11Memory
631  *
632  * Returns: subresource index corresponding to @mem.
633  *
634  * Since: 1.20
635  */
636 guint
637 gst_d3d11_memory_get_subresource_index (GstD3D11Memory * mem)
638 {
639   g_return_val_if_fail (gst_is_d3d11_memory (GST_MEMORY_CAST (mem)), 0);
640
641   if (mem->priv->native_type != GST_D3D11_MEMORY_NATIVE_TYPE_TEXTURE_2D)
642     return 0;
643
644   return mem->priv->subresource_index;
645 }
646
647 /**
648  * gst_d3d11_memory_get_texture_desc:
649  * @mem: a #GstD3D11Memory
650  * @desc: (out): a D3D11_TEXTURE2D_DESC
651  *
652  * Fill @desc with D3D11_TEXTURE2D_DESC for ID3D11Texture2D
653  *
654  * Returns: %TRUE if successeed
655  *
656  * Since: 1.20
657  */
658 gboolean
659 gst_d3d11_memory_get_texture_desc (GstD3D11Memory * mem,
660     D3D11_TEXTURE2D_DESC * desc)
661 {
662   g_return_val_if_fail (gst_is_d3d11_memory (GST_MEMORY_CAST (mem)), FALSE);
663   g_return_val_if_fail (desc != NULL, FALSE);
664
665   if (mem->priv->native_type != GST_D3D11_MEMORY_NATIVE_TYPE_TEXTURE_2D)
666     return FALSE;
667
668   *desc = mem->priv->desc;
669
670   return TRUE;
671 }
672
673 /**
674  * gst_d3d11_memory_get_buffer_desc:
675  * @mem: a #GstD3D11Memory
676  * @desc: (out): a D3D11_BUFFER_DESC
677  *
678  * Fill @desc with D3D11_BUFFER_DESC for ID3D11Buffer
679  *
680  * Returns: %TRUE if successeed
681  *
682  * Since: 1.22
683  */
684 gboolean
685 gst_d3d11_memory_get_buffer_desc (GstD3D11Memory * mem,
686     D3D11_BUFFER_DESC * desc)
687 {
688   g_return_val_if_fail (gst_is_d3d11_memory (GST_MEMORY_CAST (mem)), FALSE);
689   g_return_val_if_fail (desc != NULL, FALSE);
690
691   if (mem->priv->native_type != GST_D3D11_MEMORY_NATIVE_TYPE_BUFFER)
692     return FALSE;
693
694   *desc = mem->priv->buffer_desc;
695
696   return TRUE;
697 }
698
699 /**
700  * gst_d3d11_memory_get_resource_stride:
701  * @mem: a #GstD3D11Memory
702  * @stride: (out): stride of resource
703  *
704  * Returns: %TRUE if successeed
705  *
706  * Since: 1.22
707  */
708 gboolean
709 gst_d3d11_memory_get_resource_stride (GstD3D11Memory * mem, guint * stride)
710 {
711   g_return_val_if_fail (gst_is_d3d11_memory (GST_MEMORY_CAST (mem)), FALSE);
712   g_return_val_if_fail (stride != NULL, FALSE);
713
714   *stride = mem->priv->map.RowPitch;
715
716   return TRUE;
717 }
718
719 static gboolean
720 create_shader_resource_views (GstD3D11Memory * mem)
721 {
722   GstD3D11MemoryPrivate *priv = mem->priv;
723   guint i;
724   HRESULT hr;
725   guint num_views = 0;
726   ID3D11Device *device_handle;
727   D3D11_SHADER_RESOURCE_VIEW_DESC resource_desc;
728   DXGI_FORMAT formats[GST_VIDEO_MAX_PLANES] = { DXGI_FORMAT_UNKNOWN, };
729
730   memset (&resource_desc, 0, sizeof (D3D11_SHADER_RESOURCE_VIEW_DESC));
731
732   device_handle = gst_d3d11_device_get_device_handle (mem->device);
733
734   num_views = gst_d3d11_dxgi_format_get_resource_format (priv->desc.Format,
735       formats);
736   if (!num_views) {
737     GST_ERROR_OBJECT (GST_MEMORY_CAST (mem)->allocator,
738         "Unknown resource formats for DXGI format %s (%d)",
739         gst_d3d11_dxgi_format_to_string (priv->desc.Format), priv->desc.Format);
740     return FALSE;
741   }
742
743   if ((priv->desc.BindFlags & D3D11_BIND_SHADER_RESOURCE) != 0) {
744     resource_desc.ViewDimension = D3D11_SRV_DIMENSION_TEXTURE2D;
745     resource_desc.Texture2D.MipLevels = 1;
746
747     for (i = 0; i < num_views; i++) {
748       resource_desc.Format = formats[i];
749       hr = device_handle->CreateShaderResourceView (priv->texture,
750           &resource_desc, &priv->shader_resource_view[i]);
751
752       if (!gst_d3d11_result (hr, mem->device)) {
753         GST_ERROR_OBJECT (GST_MEMORY_CAST (mem)->allocator,
754             "Failed to create resource DXGI format %s (%d) for plane %d"
755             " view (0x%x)", gst_d3d11_dxgi_format_to_string (formats[i]),
756             formats[i], i, (guint) hr);
757         goto error;
758       }
759     }
760
761     priv->num_shader_resource_views = num_views;
762
763     return TRUE;
764   }
765
766   return FALSE;
767
768 error:
769   for (i = 0; i < num_views; i++)
770     GST_D3D11_CLEAR_COM (priv->shader_resource_view[i]);
771
772   priv->num_shader_resource_views = 0;
773
774   return FALSE;
775 }
776
777 static gboolean
778 gst_d3d11_memory_ensure_shader_resource_view (GstD3D11Memory * mem)
779 {
780   GstD3D11MemoryPrivate *priv = mem->priv;
781   gboolean ret = FALSE;
782
783   if (mem->priv->native_type != GST_D3D11_MEMORY_NATIVE_TYPE_TEXTURE_2D)
784     return FALSE;
785
786   if (!(priv->desc.BindFlags & D3D11_BIND_SHADER_RESOURCE)) {
787     GST_LOG_OBJECT (GST_MEMORY_CAST (mem)->allocator,
788         "Need BindFlags, current flag 0x%x", priv->desc.BindFlags);
789     return FALSE;
790   }
791
792   GST_D3D11_MEMORY_LOCK (mem);
793   if (priv->num_shader_resource_views) {
794     ret = TRUE;
795     goto done;
796   }
797
798   ret = create_shader_resource_views (mem);
799
800 done:
801   GST_D3D11_MEMORY_UNLOCK (mem);
802
803   return ret;
804 }
805
806 /**
807  * gst_d3d11_memory_get_shader_resource_view_size:
808  * @mem: a #GstD3D11Memory
809  *
810  * Returns: the number of ID3D11ShaderResourceView that can be used
811  * for processing GPU operation with @mem
812  *
813  * Since: 1.20
814  */
815 guint
816 gst_d3d11_memory_get_shader_resource_view_size (GstD3D11Memory * mem)
817 {
818   g_return_val_if_fail (gst_is_d3d11_memory (GST_MEMORY_CAST (mem)), 0);
819
820   if (!gst_d3d11_memory_ensure_shader_resource_view (mem))
821     return 0;
822
823   return mem->priv->num_shader_resource_views;
824 }
825
826 /**
827  * gst_d3d11_memory_get_shader_resource_view:
828  * @mem: a #GstD3D11Memory
829  * @index: the index of the ID3D11ShaderResourceView
830  *
831  * Returns: (transfer none) (nullable): a pointer to the
832  * ID3D11ShaderResourceView or %NULL if ID3D11ShaderResourceView is unavailable
833  * for @index
834  *
835  * Since: 1.20
836  */
837 ID3D11ShaderResourceView *
838 gst_d3d11_memory_get_shader_resource_view (GstD3D11Memory * mem, guint index)
839 {
840   GstD3D11MemoryPrivate *priv;
841
842   g_return_val_if_fail (gst_is_d3d11_memory (GST_MEMORY_CAST (mem)), NULL);
843
844   if (!gst_d3d11_memory_ensure_shader_resource_view (mem))
845     return NULL;
846
847   priv = mem->priv;
848
849   if (index >= priv->num_shader_resource_views) {
850     GST_ERROR ("Invalid SRV index %d", index);
851     return NULL;
852   }
853
854   return priv->shader_resource_view[index];
855 }
856
857 static gboolean
858 create_render_target_views (GstD3D11Memory * mem)
859 {
860   GstD3D11MemoryPrivate *priv = mem->priv;
861   guint i;
862   HRESULT hr;
863   guint num_views = 0;
864   ID3D11Device *device_handle;
865   D3D11_RENDER_TARGET_VIEW_DESC render_desc;
866   DXGI_FORMAT formats[GST_VIDEO_MAX_PLANES] = { DXGI_FORMAT_UNKNOWN, };
867
868   memset (&render_desc, 0, sizeof (D3D11_RENDER_TARGET_VIEW_DESC));
869
870   device_handle = gst_d3d11_device_get_device_handle (mem->device);
871
872   num_views = gst_d3d11_dxgi_format_get_resource_format (priv->desc.Format,
873       formats);
874   if (!num_views) {
875     GST_ERROR_OBJECT (GST_MEMORY_CAST (mem)->allocator,
876         "Unknown resource formats for DXGI format %s (%d)",
877         gst_d3d11_dxgi_format_to_string (priv->desc.Format), priv->desc.Format);
878     return FALSE;
879   }
880
881   if ((priv->desc.BindFlags & D3D11_BIND_RENDER_TARGET) != 0) {
882     render_desc.ViewDimension = D3D11_RTV_DIMENSION_TEXTURE2D;
883     render_desc.Texture2D.MipSlice = 0;
884
885     for (i = 0; i < num_views; i++) {
886       render_desc.Format = formats[i];
887
888       hr = device_handle->CreateRenderTargetView (priv->texture, &render_desc,
889           &priv->render_target_view[i]);
890       if (!gst_d3d11_result (hr, mem->device)) {
891         GST_ERROR_OBJECT (GST_MEMORY_CAST (mem)->allocator,
892             "Failed to create resource DXGI format %s (%d) for plane %d"
893             " view (0x%x)", gst_d3d11_dxgi_format_to_string (formats[i]),
894             formats[i], i, (guint) hr);
895         goto error;
896       }
897     }
898
899     priv->num_render_target_views = num_views;
900
901     return TRUE;
902   }
903
904   return FALSE;
905
906 error:
907   for (i = 0; i < num_views; i++)
908     GST_D3D11_CLEAR_COM (priv->render_target_view[i]);
909
910   priv->num_render_target_views = 0;
911
912   return FALSE;
913 }
914
915 static gboolean
916 gst_d3d11_memory_ensure_render_target_view (GstD3D11Memory * mem)
917 {
918   GstD3D11MemoryPrivate *priv = mem->priv;
919   gboolean ret = FALSE;
920
921   if (mem->priv->native_type != GST_D3D11_MEMORY_NATIVE_TYPE_TEXTURE_2D)
922     return FALSE;
923
924   if (!(priv->desc.BindFlags & D3D11_BIND_RENDER_TARGET)) {
925     GST_WARNING_OBJECT (GST_MEMORY_CAST (mem)->allocator,
926         "Need BindFlags, current flag 0x%x", priv->desc.BindFlags);
927     return FALSE;
928   }
929
930   GST_D3D11_MEMORY_LOCK (mem);
931   if (priv->num_render_target_views) {
932     ret = TRUE;
933     goto done;
934   }
935
936   ret = create_render_target_views (mem);
937
938 done:
939   GST_D3D11_MEMORY_UNLOCK (mem);
940
941   return ret;
942 }
943
944 /**
945  * gst_d3d11_memory_get_render_target_view_size:
946  * @mem: a #GstD3D11Memory
947  *
948  * Returns: the number of ID3D11RenderTargetView that can be used
949  * for processing GPU operation with @mem
950  *
951  * Since: 1.20
952  */
953 guint
954 gst_d3d11_memory_get_render_target_view_size (GstD3D11Memory * mem)
955 {
956   g_return_val_if_fail (gst_is_d3d11_memory (GST_MEMORY_CAST (mem)), 0);
957
958   if (!gst_d3d11_memory_ensure_render_target_view (mem))
959     return 0;
960
961   return mem->priv->num_render_target_views;
962 }
963
964 /**
965  * gst_d3d11_memory_get_render_target_view:
966  * @mem: a #GstD3D11Memory
967  * @index: the index of the ID3D11RenderTargetView
968  *
969  * Returns: (transfer none) (nullable): a pointer to the
970  * ID3D11RenderTargetView or %NULL if ID3D11RenderTargetView is unavailable
971  * for @index
972  *
973  * Since: 1.20
974  */
975 ID3D11RenderTargetView *
976 gst_d3d11_memory_get_render_target_view (GstD3D11Memory * mem, guint index)
977 {
978   GstD3D11MemoryPrivate *priv;
979
980   g_return_val_if_fail (gst_is_d3d11_memory (GST_MEMORY_CAST (mem)), NULL);
981
982   if (!gst_d3d11_memory_ensure_render_target_view (mem))
983     return NULL;
984
985   priv = mem->priv;
986
987   if (index >= priv->num_render_target_views) {
988     GST_ERROR ("Invalid RTV index %d", index);
989     return NULL;
990   }
991
992   return priv->render_target_view[index];
993 }
994
995 static gboolean
996 gst_d3d11_memory_ensure_decoder_output_view (GstD3D11Memory * mem,
997     ID3D11VideoDevice * video_device, ID3D11VideoDecoder * decoder,
998     const GUID * decoder_profile)
999 {
1000   GstD3D11MemoryPrivate *dmem_priv = mem->priv;
1001   GstD3D11Allocator *allocator;
1002   D3D11_VIDEO_DECODER_OUTPUT_VIEW_DESC desc;
1003   HRESULT hr;
1004   gboolean ret = FALSE;
1005
1006   if (mem->priv->native_type != GST_D3D11_MEMORY_NATIVE_TYPE_TEXTURE_2D)
1007     return FALSE;
1008
1009   allocator = GST_D3D11_ALLOCATOR (GST_MEMORY_CAST (mem)->allocator);
1010
1011   if (!(dmem_priv->desc.BindFlags & D3D11_BIND_DECODER)) {
1012     GST_LOG_OBJECT (allocator,
1013         "Need BindFlags, current flag 0x%x", dmem_priv->desc.BindFlags);
1014     return FALSE;
1015   }
1016
1017   GST_D3D11_MEMORY_LOCK (mem);
1018   if (dmem_priv->decoder_output_view) {
1019     dmem_priv->decoder_output_view->GetDesc (&desc);
1020     if (IsEqualGUID (desc.DecodeProfile, *decoder_profile) &&
1021         dmem_priv->decoder_handle == decoder) {
1022       goto succeeded;
1023     } else {
1024       /* Shouldn't happen, but try again anyway */
1025       GST_WARNING_OBJECT (allocator,
1026           "Existing view has different decoder profile");
1027       GST_D3D11_CLEAR_COM (dmem_priv->decoder_output_view);
1028       GST_D3D11_CLEAR_COM (dmem_priv->decoder_handle);
1029     }
1030   }
1031
1032   if (dmem_priv->decoder_output_view)
1033     goto succeeded;
1034
1035   desc.DecodeProfile = *decoder_profile;
1036   desc.ViewDimension = D3D11_VDOV_DIMENSION_TEXTURE2D;
1037   desc.Texture2D.ArraySlice = dmem_priv->subresource_index;
1038
1039   hr = video_device->CreateVideoDecoderOutputView (dmem_priv->texture, &desc,
1040       &dmem_priv->decoder_output_view);
1041   if (!gst_d3d11_result (hr, mem->device)) {
1042     GST_ERROR_OBJECT (allocator,
1043         "Could not create decoder output view, hr: 0x%x", (guint) hr);
1044     goto done;
1045   }
1046
1047   /* XXX: decoder output view is bound to video device, not decoder handle
1048    * from API point of view. But some driver seems to be unhappy
1049    * when decoder handle is released while there are outstanding view objects */
1050   dmem_priv->decoder_handle = decoder;
1051   decoder->AddRef ();
1052
1053 succeeded:
1054   ret = TRUE;
1055
1056 done:
1057   GST_D3D11_MEMORY_UNLOCK (mem);
1058
1059   return ret;
1060 }
1061
1062 /**
1063  * gst_d3d11_memory_get_decoder_output_view:
1064  * @mem: a #GstD3D11Memory
1065  * @video_device: (transfer none): a ID3D11VideoDevice handle
1066  * @decoder: (transfer none): a ID3D11VideoDecoder handle
1067  * @decoder_profile: a DXVA decoder profile GUID
1068  *
1069  * Returns: (transfer none) (nullable): a pointer to the
1070  * ID3D11VideoDecoderOutputView or %NULL if ID3D11VideoDecoderOutputView is
1071  * unavailable
1072  *
1073  * Since: 1.20
1074  */
1075 ID3D11VideoDecoderOutputView *
1076 gst_d3d11_memory_get_decoder_output_view (GstD3D11Memory * mem,
1077     ID3D11VideoDevice * video_device, ID3D11VideoDecoder * decoder,
1078     const GUID * decoder_profile)
1079 {
1080   g_return_val_if_fail (gst_is_d3d11_memory (GST_MEMORY_CAST (mem)), NULL);
1081   g_return_val_if_fail (video_device != NULL, NULL);
1082   g_return_val_if_fail (decoder != NULL, NULL);
1083   g_return_val_if_fail (decoder_profile != NULL, NULL);
1084
1085   if (!gst_d3d11_memory_ensure_decoder_output_view (mem,
1086           video_device, decoder, decoder_profile))
1087     return NULL;
1088
1089   return mem->priv->decoder_output_view;
1090 }
1091
1092 static gboolean
1093 check_bind_flags_for_processor_input_view (guint bind_flags)
1094 {
1095   static const guint compatible_flags = (D3D11_BIND_DECODER |
1096       D3D11_BIND_VIDEO_ENCODER | D3D11_BIND_RENDER_TARGET |
1097       D3D11_BIND_UNORDERED_ACCESS);
1098
1099   if (bind_flags == 0)
1100     return TRUE;
1101
1102   if ((bind_flags & compatible_flags) != 0)
1103     return TRUE;
1104
1105   return FALSE;
1106 }
1107
1108 static gboolean
1109 gst_d3d11_memory_ensure_processor_input_view (GstD3D11Memory * mem,
1110     ID3D11VideoDevice * video_device,
1111     ID3D11VideoProcessorEnumerator * enumerator)
1112 {
1113   GstD3D11MemoryPrivate *dmem_priv = mem->priv;
1114   GstD3D11Allocator *allocator;
1115   D3D11_VIDEO_PROCESSOR_INPUT_VIEW_DESC desc;
1116   HRESULT hr;
1117   gboolean ret = FALSE;
1118
1119   if (mem->priv->native_type != GST_D3D11_MEMORY_NATIVE_TYPE_TEXTURE_2D)
1120     return FALSE;
1121
1122   allocator = GST_D3D11_ALLOCATOR (GST_MEMORY_CAST (mem)->allocator);
1123
1124   if (!check_bind_flags_for_processor_input_view (dmem_priv->desc.BindFlags)) {
1125     GST_LOG_OBJECT (allocator,
1126         "Need BindFlags, current flag 0x%x", dmem_priv->desc.BindFlags);
1127     return FALSE;
1128   }
1129
1130   GST_D3D11_MEMORY_LOCK (mem);
1131   if (dmem_priv->processor_input_view)
1132     goto succeeded;
1133
1134   desc.FourCC = 0;
1135   desc.ViewDimension = D3D11_VPIV_DIMENSION_TEXTURE2D;
1136   desc.Texture2D.MipSlice = 0;
1137   desc.Texture2D.ArraySlice = dmem_priv->subresource_index;
1138
1139   hr = video_device->CreateVideoProcessorInputView (dmem_priv->texture,
1140       enumerator, &desc, &dmem_priv->processor_input_view);
1141   if (!gst_d3d11_result (hr, mem->device)) {
1142     GST_ERROR_OBJECT (allocator,
1143         "Could not create processor input view, hr: 0x%x", (guint) hr);
1144     goto done;
1145   }
1146
1147 succeeded:
1148   ret = TRUE;
1149
1150 done:
1151   GST_D3D11_MEMORY_UNLOCK (mem);
1152
1153   return ret;
1154 }
1155
1156 /**
1157  * gst_d3d11_memory_get_processor_input_view:
1158  * @mem: a #GstD3D11Memory
1159  * @video_device: a #ID3D11VideoDevice
1160  * @enumerator: a #ID3D11VideoProcessorEnumerator
1161  *
1162  * Returns: (transfer none) (nullable): a pointer to the
1163  * ID3D11VideoProcessorInputView or %NULL if ID3D11VideoProcessorInputView is
1164  * unavailable
1165  *
1166  * Since: 1.20
1167  */
1168 ID3D11VideoProcessorInputView *
1169 gst_d3d11_memory_get_processor_input_view (GstD3D11Memory * mem,
1170     ID3D11VideoDevice * video_device,
1171     ID3D11VideoProcessorEnumerator * enumerator)
1172 {
1173   g_return_val_if_fail (gst_is_d3d11_memory (GST_MEMORY_CAST (mem)), NULL);
1174   g_return_val_if_fail (video_device != NULL, NULL);
1175   g_return_val_if_fail (enumerator != NULL, NULL);
1176
1177   if (!gst_d3d11_memory_ensure_processor_input_view (mem, video_device,
1178           enumerator))
1179     return NULL;
1180
1181   return mem->priv->processor_input_view;
1182 }
1183
1184 static gboolean
1185 gst_d3d11_memory_ensure_processor_output_view (GstD3D11Memory * mem,
1186     ID3D11VideoDevice * video_device,
1187     ID3D11VideoProcessorEnumerator * enumerator)
1188 {
1189   GstD3D11MemoryPrivate *priv = mem->priv;
1190   GstD3D11Allocator *allocator;
1191   D3D11_VIDEO_PROCESSOR_OUTPUT_VIEW_DESC desc;
1192   HRESULT hr;
1193   gboolean ret;
1194
1195   if (mem->priv->native_type != GST_D3D11_MEMORY_NATIVE_TYPE_TEXTURE_2D)
1196     return FALSE;
1197
1198   memset (&desc, 0, sizeof (D3D11_VIDEO_PROCESSOR_OUTPUT_VIEW_DESC));
1199
1200   allocator = GST_D3D11_ALLOCATOR (GST_MEMORY_CAST (mem)->allocator);
1201
1202   if (!(priv->desc.BindFlags & D3D11_BIND_RENDER_TARGET)) {
1203     GST_LOG_OBJECT (allocator,
1204         "Need BindFlags, current flag 0x%x", priv->desc.BindFlags);
1205     return FALSE;
1206   }
1207
1208   /* FIXME: texture array should be supported at some point */
1209   if (priv->subresource_index != 0) {
1210     GST_FIXME_OBJECT (allocator,
1211         "Texture array is not suppoted for processor output view");
1212     return FALSE;
1213   }
1214
1215   GST_D3D11_MEMORY_LOCK (mem);
1216   if (priv->processor_output_view)
1217     goto succeeded;
1218
1219   desc.ViewDimension = D3D11_VPOV_DIMENSION_TEXTURE2D;
1220   desc.Texture2D.MipSlice = 0;
1221
1222   hr = video_device->CreateVideoProcessorOutputView (priv->texture,
1223       enumerator, &desc, &priv->processor_output_view);
1224   if (!gst_d3d11_result (hr, mem->device)) {
1225     GST_ERROR_OBJECT (allocator,
1226         "Could not create processor input view, hr: 0x%x", (guint) hr);
1227     goto done;
1228   }
1229
1230 succeeded:
1231   ret = TRUE;
1232
1233 done:
1234   GST_D3D11_MEMORY_UNLOCK (mem);
1235
1236   return ret;
1237 }
1238
1239 /**
1240  * gst_d3d11_memory_get_processor_output_view:
1241  * @mem: a #GstD3D11Memory
1242  * @video_device: a #ID3D11VideoDevice
1243  * @enumerator: a #ID3D11VideoProcessorEnumerator
1244  *
1245  * Returns: (transfer none) (nullable): a pointer to the
1246  * ID3D11VideoProcessorOutputView or %NULL if ID3D11VideoProcessorOutputView is
1247  * unavailable
1248  *
1249  * Since: 1.20
1250  */
1251 ID3D11VideoProcessorOutputView *
1252 gst_d3d11_memory_get_processor_output_view (GstD3D11Memory * mem,
1253     ID3D11VideoDevice * video_device,
1254     ID3D11VideoProcessorEnumerator * enumerator)
1255 {
1256   g_return_val_if_fail (gst_is_d3d11_memory (GST_MEMORY_CAST (mem)), NULL);
1257   g_return_val_if_fail (video_device != NULL, NULL);
1258   g_return_val_if_fail (enumerator != NULL, NULL);
1259
1260   if (!gst_d3d11_memory_ensure_processor_output_view (mem, video_device,
1261           enumerator))
1262     return NULL;
1263
1264   return mem->priv->processor_output_view;
1265 }
1266
1267 /* GstD3D11Allocator */
1268 struct _GstD3D11AllocatorPrivate
1269 {
1270   GstMemoryCopyFunction fallback_copy;
1271 };
1272
1273 #define gst_d3d11_allocator_parent_class alloc_parent_class
1274 G_DEFINE_TYPE_WITH_PRIVATE (GstD3D11Allocator,
1275     gst_d3d11_allocator, GST_TYPE_ALLOCATOR);
1276
1277 static GstMemory *gst_d3d11_allocator_dummy_alloc (GstAllocator * allocator,
1278     gsize size, GstAllocationParams * params);
1279 static GstMemory *gst_d3d11_allocator_alloc_internal (GstD3D11Allocator * self,
1280     GstD3D11Device * device, const D3D11_TEXTURE2D_DESC * desc);
1281 static void gst_d3d11_allocator_free (GstAllocator * allocator,
1282     GstMemory * mem);
1283
1284 static void
1285 gst_d3d11_allocator_class_init (GstD3D11AllocatorClass * klass)
1286 {
1287   GstAllocatorClass *allocator_class = GST_ALLOCATOR_CLASS (klass);
1288
1289   allocator_class->alloc = gst_d3d11_allocator_dummy_alloc;
1290   allocator_class->free = gst_d3d11_allocator_free;
1291 }
1292
1293 static GstMemory *
1294 gst_d3d11_memory_copy (GstMemory * mem, gssize offset, gssize size)
1295 {
1296   GstD3D11Allocator *alloc = GST_D3D11_ALLOCATOR (mem->allocator);
1297   GstD3D11AllocatorPrivate *priv = alloc->priv;
1298   GstD3D11Memory *dmem = GST_D3D11_MEMORY_CAST (mem);
1299   GstD3D11Memory *copy_dmem;
1300   GstD3D11Device *device = dmem->device;
1301   ID3D11Device *device_handle = gst_d3d11_device_get_device_handle (device);
1302   ID3D11DeviceContext *device_context =
1303       gst_d3d11_device_get_device_context_handle (device);
1304   D3D11_TEXTURE2D_DESC dst_desc = { 0, };
1305   D3D11_TEXTURE2D_DESC src_desc = { 0, };
1306   GstMemory *copy = NULL;
1307   GstMapInfo info;
1308   HRESULT hr;
1309   UINT bind_flags = 0;
1310   UINT supported_flags = 0;
1311
1312   if (dmem->priv->native_type != GST_D3D11_MEMORY_NATIVE_TYPE_TEXTURE_2D)
1313     return priv->fallback_copy (mem, offset, size);
1314
1315   /* non-zero offset or different size is not supported */
1316   if (offset != 0 || (size != -1 && (gsize) size != mem->size)) {
1317     GST_DEBUG_OBJECT (alloc, "Different size/offset, try fallback copy");
1318     return priv->fallback_copy (mem, offset, size);
1319   }
1320
1321   gst_d3d11_device_lock (device);
1322   if (!gst_memory_map (mem, &info,
1323           (GstMapFlags) (GST_MAP_READ | GST_MAP_D3D11))) {
1324     gst_d3d11_device_unlock (device);
1325
1326     GST_WARNING_OBJECT (alloc, "Failed to map memory, try fallback copy");
1327
1328     return priv->fallback_copy (mem, offset, size);
1329   }
1330
1331   dmem->priv->texture->GetDesc (&src_desc);
1332   dst_desc.Width = src_desc.Width;
1333   dst_desc.Height = src_desc.Height;
1334   dst_desc.MipLevels = 1;
1335   dst_desc.Format = src_desc.Format;
1336   dst_desc.SampleDesc.Count = 1;
1337   dst_desc.ArraySize = 1;
1338   dst_desc.Usage = D3D11_USAGE_DEFAULT;
1339
1340   /* If supported, use bind flags for SRV/RTV */
1341   hr = device_handle->CheckFormatSupport (src_desc.Format, &supported_flags);
1342   if (gst_d3d11_result (hr, device)) {
1343     if ((supported_flags & D3D11_FORMAT_SUPPORT_SHADER_SAMPLE) ==
1344         D3D11_FORMAT_SUPPORT_SHADER_SAMPLE) {
1345       bind_flags |= D3D11_BIND_SHADER_RESOURCE;
1346     }
1347
1348     if ((supported_flags & D3D11_FORMAT_SUPPORT_RENDER_TARGET) ==
1349         D3D11_FORMAT_SUPPORT_RENDER_TARGET) {
1350       bind_flags |= D3D11_BIND_RENDER_TARGET;
1351     }
1352   }
1353
1354   copy = gst_d3d11_allocator_alloc_internal (alloc, device, &dst_desc);
1355   if (!copy) {
1356     gst_memory_unmap (mem, &info);
1357     gst_d3d11_device_unlock (device);
1358
1359     GST_WARNING_OBJECT (alloc,
1360         "Failed to allocate new d3d11 map memory, try fallback copy");
1361
1362     return priv->fallback_copy (mem, offset, size);
1363   }
1364
1365   copy_dmem = GST_D3D11_MEMORY_CAST (copy);
1366   device_context->CopySubresourceRegion (copy_dmem->priv->texture, 0, 0, 0, 0,
1367       dmem->priv->texture, dmem->priv->subresource_index, NULL);
1368   copy->maxsize = copy->size = mem->maxsize;
1369   gst_memory_unmap (mem, &info);
1370   gst_d3d11_device_unlock (device);
1371
1372   /* newly allocated memory holds valid image data. We need download this
1373    * pixel data into staging memory for CPU access */
1374   GST_MINI_OBJECT_FLAG_SET (mem, GST_D3D11_MEMORY_TRANSFER_NEED_DOWNLOAD);
1375
1376   return copy;
1377 }
1378
1379 static void
1380 gst_d3d11_allocator_init (GstD3D11Allocator * allocator)
1381 {
1382   GstAllocator *alloc = GST_ALLOCATOR_CAST (allocator);
1383   GstD3D11AllocatorPrivate *priv;
1384
1385   priv = allocator->priv = (GstD3D11AllocatorPrivate *)
1386       gst_d3d11_allocator_get_instance_private (allocator);
1387
1388   alloc->mem_type = GST_D3D11_MEMORY_NAME;
1389   alloc->mem_map_full = gst_d3d11_memory_map_full;
1390   alloc->mem_unmap_full = gst_d3d11_memory_unmap_full;
1391   alloc->mem_share = gst_d3d11_memory_share;
1392
1393   /* Store pointer to default mem_copy method for fallback copy */
1394   priv->fallback_copy = alloc->mem_copy;
1395   alloc->mem_copy = gst_d3d11_memory_copy;
1396
1397   GST_OBJECT_FLAG_SET (alloc, GST_ALLOCATOR_FLAG_CUSTOM_ALLOC);
1398 }
1399
1400 static GstMemory *
1401 gst_d3d11_allocator_dummy_alloc (GstAllocator * allocator, gsize size,
1402     GstAllocationParams * params)
1403 {
1404   g_return_val_if_reached (NULL);
1405 }
1406
1407 static void
1408 gst_d3d11_allocator_free (GstAllocator * allocator, GstMemory * mem)
1409 {
1410   GstD3D11Memory *dmem = GST_D3D11_MEMORY_CAST (mem);
1411   GstD3D11MemoryPrivate *dmem_priv = dmem->priv;
1412   gint i;
1413
1414   GST_LOG_OBJECT (allocator, "Free memory %p", mem);
1415
1416   for (i = 0; i < GST_VIDEO_MAX_PLANES; i++) {
1417     GST_D3D11_CLEAR_COM (dmem_priv->render_target_view[i]);
1418     GST_D3D11_CLEAR_COM (dmem_priv->shader_resource_view[i]);
1419   }
1420
1421   GST_D3D11_CLEAR_COM (dmem_priv->decoder_output_view);
1422   GST_D3D11_CLEAR_COM (dmem_priv->processor_input_view);
1423   GST_D3D11_CLEAR_COM (dmem_priv->processor_output_view);
1424   GST_D3D11_CLEAR_COM (dmem_priv->texture);
1425   GST_D3D11_CLEAR_COM (dmem_priv->staging);
1426   GST_D3D11_CLEAR_COM (dmem_priv->buffer);
1427
1428   GST_D3D11_CLEAR_COM (dmem_priv->decoder_handle);
1429
1430   gst_clear_object (&dmem->device);
1431   g_mutex_clear (&dmem_priv->lock);
1432   g_free (dmem->priv);
1433   g_free (dmem);
1434 }
1435
1436 static GstMemory *
1437 gst_d3d11_allocator_alloc_wrapped (GstD3D11Allocator * self,
1438     GstD3D11Device * device, const D3D11_TEXTURE2D_DESC * desc,
1439     ID3D11Texture2D * texture)
1440 {
1441   GstD3D11Memory *mem;
1442
1443   mem = g_new0 (GstD3D11Memory, 1);
1444   mem->priv = g_new0 (GstD3D11MemoryPrivate, 1);
1445
1446   gst_memory_init (GST_MEMORY_CAST (mem),
1447       (GstMemoryFlags) 0, GST_ALLOCATOR_CAST (self), NULL, 0, 0, 0, 0);
1448   g_mutex_init (&mem->priv->lock);
1449   mem->priv->texture = texture;
1450   mem->priv->desc = *desc;
1451   mem->priv->native_type = GST_D3D11_MEMORY_NATIVE_TYPE_TEXTURE_2D;
1452   mem->device = (GstD3D11Device *) gst_object_ref (device);
1453
1454   return GST_MEMORY_CAST (mem);
1455 }
1456
1457 typedef void (*GstD3D11ClearRTVFunc) (ID3D11DeviceContext * context_handle,
1458     ID3D11RenderTargetView * rtv);
1459
1460 static void
1461 clear_rtv_chroma (ID3D11DeviceContext * context_handle,
1462     ID3D11RenderTargetView * rtv)
1463 {
1464   const FLOAT clear_color[4] = { 0.5f, 0.5f, 0.5f, 1.0f };
1465
1466   context_handle->ClearRenderTargetView (rtv, clear_color);
1467 }
1468
1469 static void
1470 clear_rtv_vuya (ID3D11DeviceContext * context_handle,
1471     ID3D11RenderTargetView * rtv)
1472 {
1473   const FLOAT clear_color[4] = { 0.5f, 0.5f, 0.0f, 1.0f };
1474
1475   context_handle->ClearRenderTargetView (rtv, clear_color);
1476 }
1477
1478 static GstMemory *
1479 gst_d3d11_allocator_alloc_internal (GstD3D11Allocator * self,
1480     GstD3D11Device * device, const D3D11_TEXTURE2D_DESC * desc)
1481 {
1482   ID3D11Texture2D *texture = NULL;
1483   ID3D11Device *device_handle;
1484   ID3D11DeviceContext *context_handle;
1485   HRESULT hr;
1486   GstMemory *mem;
1487   GstD3D11Memory *dmem;
1488   ID3D11RenderTargetView *rtv = nullptr;
1489   GstD3D11ClearRTVFunc clear_func = nullptr;
1490
1491   device_handle = gst_d3d11_device_get_device_handle (device);
1492
1493   hr = device_handle->CreateTexture2D (desc, NULL, &texture);
1494   if (!gst_d3d11_result (hr, device)) {
1495     GST_ERROR_OBJECT (self, "Couldn't create texture");
1496     return NULL;
1497   }
1498
1499   mem = gst_d3d11_allocator_alloc_wrapped (self, device, desc, texture);
1500   if (!mem)
1501     return nullptr;
1502
1503   /* Clear with YUV black if needed and possible
1504    * TODO: do this using UAV if RTV is not allowed (e.g., packed YUV formats) */
1505   if ((desc->BindFlags & D3D11_BIND_RENDER_TARGET) == 0)
1506     return mem;
1507
1508   dmem = GST_D3D11_MEMORY_CAST (mem);
1509   switch (desc->Format) {
1510     case DXGI_FORMAT_NV12:
1511     case DXGI_FORMAT_P010:
1512     case DXGI_FORMAT_P016:
1513       /* Y component will be zero already */
1514       rtv = gst_d3d11_memory_get_render_target_view (dmem, 1);
1515       clear_func = (GstD3D11ClearRTVFunc) clear_rtv_chroma;
1516       break;
1517     case DXGI_FORMAT_AYUV:
1518       rtv = gst_d3d11_memory_get_render_target_view (dmem, 0);
1519       clear_func = (GstD3D11ClearRTVFunc) clear_rtv_vuya;
1520       break;
1521     default:
1522       return mem;
1523   }
1524
1525   if (!rtv)
1526     return mem;
1527
1528   context_handle = gst_d3d11_device_get_device_context_handle (device);
1529   gst_d3d11_device_lock (device);
1530   clear_func (context_handle, rtv);
1531   gst_d3d11_device_unlock (device);
1532
1533   return mem;
1534 }
1535
1536 /**
1537  * gst_d3d11_allocator_alloc:
1538  * @allocator: a #GstD3D11Allocator
1539  * @device: a #GstD3D11Device
1540  * @desc: a D3D11_TEXTURE2D_DESC struct
1541  *
1542  * Returns: a newly allocated #GstD3D11Memory with given parameters.
1543  *
1544  * Since: 1.20
1545  */
1546 GstMemory *
1547 gst_d3d11_allocator_alloc (GstD3D11Allocator * allocator,
1548     GstD3D11Device * device, const D3D11_TEXTURE2D_DESC * desc)
1549 {
1550   GstMemory *mem;
1551
1552   g_return_val_if_fail (GST_IS_D3D11_ALLOCATOR (allocator), NULL);
1553   g_return_val_if_fail (GST_IS_D3D11_DEVICE (device), NULL);
1554   g_return_val_if_fail (desc != NULL, NULL);
1555
1556   mem = gst_d3d11_allocator_alloc_internal (allocator, device, desc);
1557   if (!mem)
1558     return NULL;
1559
1560   if (!gst_d3d11_memory_update_size (mem)) {
1561     GST_ERROR_OBJECT (allocator, "Failed to calculate size");
1562     gst_memory_unref (mem);
1563     return NULL;
1564   }
1565
1566   return mem;
1567 }
1568
1569 /**
1570  * gst_d3d11_allocator_alloc_buffer:
1571  * @allocator: a #GstD3D11Allocator
1572  * @device: a #GstD3D11Device
1573  * @desc: a D3D11_BUFFER_DESC struct
1574  *
1575  * Returns: a newly allocated #GstD3D11Memory with given parameters.
1576  *
1577  * Since: 1.22
1578  */
1579 GstMemory *
1580 gst_d3d11_allocator_alloc_buffer (GstD3D11Allocator * allocator,
1581     GstD3D11Device * device, const D3D11_BUFFER_DESC * desc)
1582 {
1583   GstD3D11Memory *mem;
1584   ID3D11Buffer *buffer;
1585   ID3D11Device *device_handle;
1586   HRESULT hr;
1587
1588   g_return_val_if_fail (GST_IS_D3D11_ALLOCATOR (allocator), nullptr);
1589   g_return_val_if_fail (GST_IS_D3D11_DEVICE (device), nullptr);
1590   g_return_val_if_fail (desc != nullptr, nullptr);
1591
1592   if (desc->Usage != D3D11_USAGE_STAGING) {
1593     GST_FIXME_OBJECT (allocator, "Non staging buffer is not supported");
1594     return nullptr;
1595   }
1596
1597   device_handle = gst_d3d11_device_get_device_handle (device);
1598
1599   hr = device_handle->CreateBuffer (desc, nullptr, &buffer);
1600   if (!gst_d3d11_result (hr, device)) {
1601     GST_ERROR_OBJECT (allocator, "Couldn't create buffer");
1602     return nullptr;
1603   }
1604
1605   mem = g_new0 (GstD3D11Memory, 1);
1606   mem->priv = g_new0 (GstD3D11MemoryPrivate, 1);
1607
1608   gst_memory_init (GST_MEMORY_CAST (mem),
1609       (GstMemoryFlags) 0, GST_ALLOCATOR_CAST (allocator), nullptr, 0, 0, 0, 0);
1610   g_mutex_init (&mem->priv->lock);
1611   mem->priv->buffer = buffer;
1612   mem->priv->buffer_desc = *desc;
1613   mem->priv->native_type = GST_D3D11_MEMORY_NATIVE_TYPE_BUFFER;
1614   mem->device = (GstD3D11Device *) gst_object_ref (device);
1615
1616   GST_MEMORY_CAST (mem)->maxsize = GST_MEMORY_CAST (mem)->size =
1617       desc->ByteWidth;
1618
1619   return GST_MEMORY_CAST (mem);
1620 }
1621
1622 gboolean
1623 gst_d3d11_allocator_set_active (GstD3D11Allocator * allocator, gboolean active)
1624 {
1625   GstD3D11AllocatorClass *klass;
1626
1627   g_return_val_if_fail (GST_IS_D3D11_ALLOCATOR (allocator), FALSE);
1628
1629   klass = GST_D3D11_ALLOCATOR_GET_CLASS (allocator);
1630   if (klass->set_actvie)
1631     return klass->set_actvie (allocator, active);
1632
1633   return TRUE;
1634 }
1635
1636 /* GstD3D11PoolAllocator */
1637 #define GST_D3D11_POOL_ALLOCATOR_LOCK(alloc)   (g_rec_mutex_lock(&alloc->priv->lock))
1638 #define GST_D3D11_POOL_ALLOCATOR_UNLOCK(alloc) (g_rec_mutex_unlock(&alloc->priv->lock))
1639 #define GST_D3D11_POOL_ALLOCATOR_IS_FLUSHING(alloc)  (g_atomic_int_get (&alloc->priv->flushing))
1640
1641 struct _GstD3D11PoolAllocatorPrivate
1642 {
1643   /* parent texture when array typed memory is used */
1644   ID3D11Texture2D *texture;
1645   D3D11_TEXTURE2D_DESC desc;
1646
1647   /* All below member variables are analogous to that of GstBufferPool */
1648   GstAtomicQueue *queue;
1649   GstPoll *poll;
1650
1651   /* This lock will protect all below variables apart from atomic ones
1652    * (identical to GstBufferPool::priv::rec_lock) */
1653   GRecMutex lock;
1654   gboolean started;
1655   gboolean active;
1656
1657   /* atomic */
1658   gint outstanding;
1659   guint max_mems;
1660   guint cur_mems;
1661   gboolean flushing;
1662
1663   /* Calculated memory size, based on Direct3D11 staging texture map.
1664    * Note that, we cannot know the actually staging texture memory size prior
1665    * to map the staging texture because driver will likely require padding */
1666   gsize mem_size;
1667 };
1668
1669 static void gst_d3d11_pool_allocator_dispose (GObject * object);
1670 static void gst_d3d11_pool_allocator_finalize (GObject * object);
1671
1672 static gboolean
1673 gst_d3d11_pool_allocator_set_active (GstD3D11Allocator * allocator,
1674     gboolean active);
1675
1676 static gboolean gst_d3d11_pool_allocator_start (GstD3D11PoolAllocator * self);
1677 static gboolean gst_d3d11_pool_allocator_stop (GstD3D11PoolAllocator * self);
1678 static gboolean gst_d3d11_memory_release (GstMiniObject * mini_object);
1679
1680 #define gst_d3d11_pool_allocator_parent_class pool_alloc_parent_class
1681 G_DEFINE_TYPE_WITH_PRIVATE (GstD3D11PoolAllocator,
1682     gst_d3d11_pool_allocator, GST_TYPE_D3D11_ALLOCATOR);
1683
1684 static void
1685 gst_d3d11_pool_allocator_class_init (GstD3D11PoolAllocatorClass * klass)
1686 {
1687   GObjectClass *gobject_class = G_OBJECT_CLASS (klass);
1688   GstD3D11AllocatorClass *d3d11alloc_class = GST_D3D11_ALLOCATOR_CLASS (klass);
1689
1690   gobject_class->dispose = gst_d3d11_pool_allocator_dispose;
1691   gobject_class->finalize = gst_d3d11_pool_allocator_finalize;
1692
1693   d3d11alloc_class->set_actvie = gst_d3d11_pool_allocator_set_active;
1694 }
1695
1696 static void
1697 gst_d3d11_pool_allocator_init (GstD3D11PoolAllocator * allocator)
1698 {
1699   GstD3D11PoolAllocatorPrivate *priv;
1700
1701   priv = allocator->priv = (GstD3D11PoolAllocatorPrivate *)
1702       gst_d3d11_pool_allocator_get_instance_private (allocator);
1703   g_rec_mutex_init (&priv->lock);
1704
1705   priv->poll = gst_poll_new_timer ();
1706   priv->queue = gst_atomic_queue_new (16);
1707   priv->flushing = 1;
1708   priv->active = FALSE;
1709   priv->started = FALSE;
1710
1711   /* 1 control write for flushing - the flush token */
1712   gst_poll_write_control (priv->poll);
1713   /* 1 control write for marking that we are not waiting for poll - the wait token */
1714   gst_poll_write_control (priv->poll);
1715 }
1716
1717 static void
1718 gst_d3d11_pool_allocator_dispose (GObject * object)
1719 {
1720   GstD3D11PoolAllocator *self = GST_D3D11_POOL_ALLOCATOR (object);
1721
1722   gst_clear_object (&self->device);
1723
1724   G_OBJECT_CLASS (pool_alloc_parent_class)->dispose (object);
1725 }
1726
1727 static void
1728 gst_d3d11_pool_allocator_finalize (GObject * object)
1729 {
1730   GstD3D11PoolAllocator *self = GST_D3D11_POOL_ALLOCATOR (object);
1731   GstD3D11PoolAllocatorPrivate *priv = self->priv;
1732
1733   GST_DEBUG_OBJECT (self, "Finalize");
1734
1735   gst_d3d11_pool_allocator_stop (self);
1736   gst_atomic_queue_unref (priv->queue);
1737   gst_poll_free (priv->poll);
1738   g_rec_mutex_clear (&priv->lock);
1739
1740   GST_D3D11_CLEAR_COM (priv->texture);
1741
1742   G_OBJECT_CLASS (pool_alloc_parent_class)->finalize (object);
1743 }
1744
1745 static gboolean
1746 gst_d3d11_pool_allocator_start (GstD3D11PoolAllocator * self)
1747 {
1748   GstD3D11PoolAllocatorPrivate *priv = self->priv;
1749   ID3D11Device *device_handle;
1750   HRESULT hr;
1751   guint i;
1752
1753   if (priv->started)
1754     return TRUE;
1755
1756   /* Nothing to do */
1757   if (priv->desc.ArraySize == 1) {
1758     priv->started = TRUE;
1759     return TRUE;
1760   }
1761
1762   device_handle = gst_d3d11_device_get_device_handle (self->device);
1763
1764   if (!priv->texture) {
1765     hr = device_handle->CreateTexture2D (&priv->desc, NULL, &priv->texture);
1766     if (!gst_d3d11_result (hr, self->device)) {
1767       GST_ERROR_OBJECT (self, "Failed to allocate texture");
1768       return FALSE;
1769     }
1770   }
1771
1772   /* Pre-allocate memory objects */
1773   for (i = 0; i < priv->desc.ArraySize; i++) {
1774     GstMemory *mem;
1775
1776     priv->texture->AddRef ();
1777     mem =
1778         gst_d3d11_allocator_alloc_wrapped (GST_D3D11_ALLOCATOR_CAST
1779         (_d3d11_memory_allocator), self->device, &priv->desc, priv->texture);
1780
1781     if (i == 0) {
1782       if (!gst_d3d11_memory_update_size (mem)) {
1783         GST_ERROR_OBJECT (self, "Failed to calculate memory size");
1784         gst_memory_unref (mem);
1785         return FALSE;
1786       }
1787
1788       priv->mem_size = mem->size;
1789     } else {
1790       mem->size = mem->maxsize = priv->mem_size;
1791     }
1792
1793     GST_D3D11_MEMORY_CAST (mem)->priv->subresource_index = i;
1794
1795     g_atomic_int_add (&priv->cur_mems, 1);
1796     gst_atomic_queue_push (priv->queue, mem);
1797     gst_poll_write_control (priv->poll);
1798   }
1799
1800   priv->started = TRUE;
1801
1802   return TRUE;
1803 }
1804
1805 static void
1806 gst_d3d11_pool_allocator_do_set_flushing (GstD3D11PoolAllocator * self,
1807     gboolean flushing)
1808 {
1809   GstD3D11PoolAllocatorPrivate *priv = self->priv;
1810
1811   if (GST_D3D11_POOL_ALLOCATOR_IS_FLUSHING (self) == flushing)
1812     return;
1813
1814   if (flushing) {
1815     g_atomic_int_set (&priv->flushing, 1);
1816     /* Write the flush token to wake up any waiters */
1817     gst_poll_write_control (priv->poll);
1818   } else {
1819     while (!gst_poll_read_control (priv->poll)) {
1820       if (errno == EWOULDBLOCK) {
1821         /* This should not really happen unless flushing and unflushing
1822          * happens on different threads. Let's wait a bit to get back flush
1823          * token from the thread that was setting it to flushing */
1824         g_thread_yield ();
1825         continue;
1826       } else {
1827         /* Critical error but GstPoll already complained */
1828         break;
1829       }
1830     }
1831
1832     g_atomic_int_set (&priv->flushing, 0);
1833   }
1834 }
1835
1836 static gboolean
1837 gst_d3d11_pool_allocator_set_active (GstD3D11Allocator * allocator,
1838     gboolean active)
1839 {
1840   GstD3D11PoolAllocator *self = GST_D3D11_POOL_ALLOCATOR (allocator);
1841   GstD3D11PoolAllocatorPrivate *priv = self->priv;
1842
1843   GST_LOG_OBJECT (self, "active %d", active);
1844
1845   GST_D3D11_POOL_ALLOCATOR_LOCK (self);
1846   /* just return if we are already in the right state */
1847   if (priv->active == active)
1848     goto was_ok;
1849
1850   if (active) {
1851     if (!gst_d3d11_pool_allocator_start (self))
1852       goto start_failed;
1853
1854     /* flush_stop may release memory objects, setting to active to avoid running
1855      * do_stop while activating the pool */
1856     priv->active = TRUE;
1857
1858     gst_d3d11_pool_allocator_do_set_flushing (self, FALSE);
1859   } else {
1860     gint outstanding;
1861
1862     /* set to flushing first */
1863     gst_d3d11_pool_allocator_do_set_flushing (self, TRUE);
1864
1865     /* when all memory objects are in the pool, free them. Else they will be
1866      * freed when they are released */
1867     outstanding = g_atomic_int_get (&priv->outstanding);
1868     GST_LOG_OBJECT (self, "outstanding memories %d, (in queue %d)",
1869         outstanding, gst_atomic_queue_length (priv->queue));
1870     if (outstanding == 0) {
1871       if (!gst_d3d11_pool_allocator_stop (self))
1872         goto stop_failed;
1873     }
1874
1875     priv->active = FALSE;
1876   }
1877
1878   GST_D3D11_POOL_ALLOCATOR_UNLOCK (self);
1879
1880   return TRUE;
1881
1882 was_ok:
1883   {
1884     GST_DEBUG_OBJECT (self, "allocator was in the right state");
1885     GST_D3D11_POOL_ALLOCATOR_UNLOCK (self);
1886     return TRUE;
1887   }
1888 start_failed:
1889   {
1890     GST_ERROR_OBJECT (self, "start failed");
1891     GST_D3D11_POOL_ALLOCATOR_UNLOCK (self);
1892     return FALSE;
1893   }
1894 stop_failed:
1895   {
1896     GST_ERROR_OBJECT (self, "stop failed");
1897     GST_D3D11_POOL_ALLOCATOR_UNLOCK (self);
1898     return FALSE;
1899   }
1900 }
1901
1902 static void
1903 gst_d3d11_pool_allocator_free_memory (GstD3D11PoolAllocator * self,
1904     GstMemory * mem)
1905 {
1906   GstD3D11PoolAllocatorPrivate *priv = self->priv;
1907
1908   g_atomic_int_add (&priv->cur_mems, -1);
1909   GST_LOG_OBJECT (self, "freeing memory %p (%u left)", mem, priv->cur_mems);
1910
1911   GST_MINI_OBJECT_CAST (mem)->dispose = NULL;
1912   gst_memory_unref (mem);
1913 }
1914
1915 /* must be called with the lock */
1916 static gboolean
1917 gst_d3d11_pool_allocator_clear_queue (GstD3D11PoolAllocator * self)
1918 {
1919   GstD3D11PoolAllocatorPrivate *priv = self->priv;
1920   GstMemory *memory;
1921
1922   GST_LOG_OBJECT (self, "Clearing queue");
1923
1924   /* clear the pool */
1925   while ((memory = (GstMemory *) gst_atomic_queue_pop (priv->queue))) {
1926     while (!gst_poll_read_control (priv->poll)) {
1927       if (errno == EWOULDBLOCK) {
1928         /* We put the memory into the queue but did not finish writing control
1929          * yet, let's wait a bit and retry */
1930         g_thread_yield ();
1931         continue;
1932       } else {
1933         /* Critical error but GstPoll already complained */
1934         break;
1935       }
1936     }
1937     gst_d3d11_pool_allocator_free_memory (self, memory);
1938   }
1939
1940   GST_LOG_OBJECT (self, "Clear done");
1941
1942   return priv->cur_mems == 0;
1943 }
1944
1945 /* must be called with the lock */
1946 static gboolean
1947 gst_d3d11_pool_allocator_stop (GstD3D11PoolAllocator * self)
1948 {
1949   GstD3D11PoolAllocatorPrivate *priv = self->priv;
1950
1951   GST_DEBUG_OBJECT (self, "Stop");
1952
1953   if (priv->started) {
1954     if (!gst_d3d11_pool_allocator_clear_queue (self))
1955       return FALSE;
1956
1957     priv->started = FALSE;
1958   } else {
1959     GST_DEBUG_OBJECT (self, "Wasn't started");
1960   }
1961
1962   return TRUE;
1963 }
1964
1965 static inline void
1966 dec_outstanding (GstD3D11PoolAllocator * self)
1967 {
1968   if (g_atomic_int_dec_and_test (&self->priv->outstanding)) {
1969     /* all memory objects are returned to the pool, see if we need to free them */
1970     if (GST_D3D11_POOL_ALLOCATOR_IS_FLUSHING (self)) {
1971       /* take the lock so that set_active is not run concurrently */
1972       GST_D3D11_POOL_ALLOCATOR_LOCK (self);
1973       /* now that we have the lock, check if we have been de-activated with
1974        * outstanding buffers */
1975       if (!self->priv->active)
1976         gst_d3d11_pool_allocator_stop (self);
1977
1978       GST_D3D11_POOL_ALLOCATOR_UNLOCK (self);
1979     }
1980   }
1981 }
1982
1983 static void
1984 gst_d3d11_pool_allocator_release_memory (GstD3D11PoolAllocator * self,
1985     GstMemory * mem)
1986 {
1987   GST_LOG_OBJECT (self, "Released memory %p", mem);
1988
1989   GST_MINI_OBJECT_CAST (mem)->dispose = NULL;
1990   mem->allocator = (GstAllocator *) gst_object_ref (_d3d11_memory_allocator);
1991   gst_object_unref (self);
1992
1993   /* keep it around in our queue */
1994   gst_atomic_queue_push (self->priv->queue, mem);
1995   gst_poll_write_control (self->priv->poll);
1996   dec_outstanding (self);
1997 }
1998
1999 static gboolean
2000 gst_d3d11_memory_release (GstMiniObject * mini_object)
2001 {
2002   GstMemory *mem = GST_MEMORY_CAST (mini_object);
2003   GstD3D11PoolAllocator *alloc;
2004
2005   g_assert (mem->allocator != NULL);
2006
2007   if (!GST_IS_D3D11_POOL_ALLOCATOR (mem->allocator)) {
2008     GST_LOG_OBJECT (mem->allocator, "Not our memory, free");
2009     return TRUE;
2010   }
2011
2012   alloc = GST_D3D11_POOL_ALLOCATOR (mem->allocator);
2013   /* if flushing, free this memory */
2014   if (GST_D3D11_POOL_ALLOCATOR_IS_FLUSHING (alloc)) {
2015     GST_LOG_OBJECT (alloc, "allocator is flushing, free %p", mem);
2016     return TRUE;
2017   }
2018
2019   /* return the memory to the allocator */
2020   gst_memory_ref (mem);
2021   gst_d3d11_pool_allocator_release_memory (alloc, mem);
2022
2023   return FALSE;
2024 }
2025
2026 static GstFlowReturn
2027 gst_d3d11_pool_allocator_alloc (GstD3D11PoolAllocator * self, GstMemory ** mem)
2028 {
2029   GstD3D11PoolAllocatorPrivate *priv = self->priv;
2030   GstMemory *new_mem;
2031
2032   /* we allcates texture array during start */
2033   if (priv->desc.ArraySize > 1)
2034     return GST_FLOW_EOS;
2035
2036   /* increment the allocation counter */
2037   g_atomic_int_add (&priv->cur_mems, 1);
2038   new_mem =
2039       gst_d3d11_allocator_alloc_internal (GST_D3D11_ALLOCATOR_CAST
2040       (_d3d11_memory_allocator), self->device, &priv->desc);
2041   if (!new_mem) {
2042     GST_ERROR_OBJECT (self, "Failed to allocate new memory");
2043     g_atomic_int_add (&priv->cur_mems, -1);
2044     return GST_FLOW_ERROR;
2045   }
2046
2047   if (!priv->mem_size) {
2048     if (!gst_d3d11_memory_update_size (new_mem)) {
2049       GST_ERROR_OBJECT (self, "Failed to calculate size");
2050       gst_memory_unref (new_mem);
2051       g_atomic_int_add (&priv->cur_mems, -1);
2052
2053       return GST_FLOW_ERROR;
2054     }
2055
2056     priv->mem_size = new_mem->size;
2057   }
2058
2059   new_mem->size = new_mem->maxsize = priv->mem_size;
2060
2061   *mem = new_mem;
2062
2063   return GST_FLOW_OK;
2064 }
2065
2066 static GstFlowReturn
2067 gst_d3d11_pool_allocator_acquire_memory_internal (GstD3D11PoolAllocator * self,
2068     GstMemory ** memory)
2069 {
2070   GstFlowReturn result;
2071   GstD3D11PoolAllocatorPrivate *priv = self->priv;
2072
2073   while (TRUE) {
2074     if (G_UNLIKELY (GST_D3D11_POOL_ALLOCATOR_IS_FLUSHING (self)))
2075       goto flushing;
2076
2077     /* try to get a memory from the queue */
2078     *memory = (GstMemory *) gst_atomic_queue_pop (priv->queue);
2079     if (G_LIKELY (*memory)) {
2080       while (!gst_poll_read_control (priv->poll)) {
2081         if (errno == EWOULDBLOCK) {
2082           /* We put the memory into the queue but did not finish writing control
2083            * yet, let's wait a bit and retry */
2084           g_thread_yield ();
2085           continue;
2086         } else {
2087           /* Critical error but GstPoll already complained */
2088           break;
2089         }
2090       }
2091       result = GST_FLOW_OK;
2092       GST_LOG_OBJECT (self, "acquired memory %p", *memory);
2093       break;
2094     }
2095
2096     /* no memory, try to allocate some more */
2097     GST_LOG_OBJECT (self, "no memory, trying to allocate");
2098     result = gst_d3d11_pool_allocator_alloc (self, memory);
2099     if (G_LIKELY (result == GST_FLOW_OK))
2100       /* we have a memory, return it */
2101       break;
2102
2103     if (G_UNLIKELY (result != GST_FLOW_EOS))
2104       /* something went wrong, return error */
2105       break;
2106
2107     /* now we release the control socket, we wait for a memory release or
2108      * flushing */
2109     if (!gst_poll_read_control (priv->poll)) {
2110       if (errno == EWOULDBLOCK) {
2111         /* This means that we have two threads trying to allocate memory
2112          * already, and the other one already got the wait token. This
2113          * means that we only have to wait for the poll now and not write the
2114          * token afterwards: we will be woken up once the other thread is
2115          * woken up and that one will write the wait token it removed */
2116         GST_LOG_OBJECT (self, "waiting for free memory or flushing");
2117         gst_poll_wait (priv->poll, GST_CLOCK_TIME_NONE);
2118       } else {
2119         /* This is a critical error, GstPoll already gave a warning */
2120         result = GST_FLOW_ERROR;
2121         break;
2122       }
2123     } else {
2124       /* We're the first thread waiting, we got the wait token and have to
2125        * write it again later
2126        * OR
2127        * We're a second thread and just consumed the flush token and block all
2128        * other threads, in which case we must not wait and give it back
2129        * immediately */
2130       if (!GST_D3D11_POOL_ALLOCATOR_IS_FLUSHING (self)) {
2131         GST_LOG_OBJECT (self, "waiting for free memory or flushing");
2132         gst_poll_wait (priv->poll, GST_CLOCK_TIME_NONE);
2133       }
2134       gst_poll_write_control (priv->poll);
2135     }
2136   }
2137
2138   return result;
2139
2140   /* ERRORS */
2141 flushing:
2142   {
2143     GST_DEBUG_OBJECT (self, "we are flushing");
2144     return GST_FLOW_FLUSHING;
2145   }
2146 }
2147
2148 /**
2149  * gst_d3d11_pool_allocator_new:
2150  * @device: a #GstD3D11Device
2151  * @desc: a D3D11_TEXTURE2D_DESC for texture allocation
2152  *
2153  * Creates a new #GstD3D11PoolAllocator instance.
2154  *
2155  * Returns: (transfer full): a new #GstD3D11PoolAllocator instance
2156  */
2157 GstD3D11PoolAllocator *
2158 gst_d3d11_pool_allocator_new (GstD3D11Device * device,
2159     const D3D11_TEXTURE2D_DESC * desc)
2160 {
2161   GstD3D11PoolAllocator *self;
2162
2163   g_return_val_if_fail (GST_IS_D3D11_DEVICE (device), NULL);
2164   g_return_val_if_fail (desc != NULL, NULL);
2165
2166   gst_d3d11_memory_init_once ();
2167
2168   self = (GstD3D11PoolAllocator *)
2169       g_object_new (GST_TYPE_D3D11_POOL_ALLOCATOR, NULL);
2170   gst_object_ref_sink (self);
2171
2172   self->device = (GstD3D11Device *) gst_object_ref (device);
2173   self->priv->desc = *desc;
2174
2175   return self;
2176 }
2177
2178 /**
2179  * gst_d3d11_pool_allocator_acquire_memory:
2180  * @allocator: a #GstD3D11PoolAllocator
2181  * @memory: (transfer full): a #GstMemory
2182  *
2183  * Acquires a #GstMemory from @allocator. @memory should point to a memory
2184  * location that can hold a pointer to the new #GstMemory.
2185  *
2186  * Returns: a #GstFlowReturn such as %GST_FLOW_FLUSHING when the allocator is
2187  * inactive.
2188  */
2189 GstFlowReturn
2190 gst_d3d11_pool_allocator_acquire_memory (GstD3D11PoolAllocator * allocator,
2191     GstMemory ** memory)
2192 {
2193   GstD3D11PoolAllocatorPrivate *priv;
2194   GstFlowReturn result;
2195
2196   g_return_val_if_fail (GST_IS_D3D11_POOL_ALLOCATOR (allocator),
2197       GST_FLOW_ERROR);
2198   g_return_val_if_fail (memory != NULL, GST_FLOW_ERROR);
2199
2200   priv = allocator->priv;
2201
2202   /* assume we'll have one more outstanding buffer we need to do that so
2203    * that concurrent set_active doesn't clear the buffers */
2204   g_atomic_int_inc (&priv->outstanding);
2205   result = gst_d3d11_pool_allocator_acquire_memory_internal (allocator, memory);
2206
2207   if (result == GST_FLOW_OK) {
2208     GstMemory *mem = *memory;
2209     /* Replace default allocator with ours */
2210     gst_object_unref (mem->allocator);
2211     mem->allocator = (GstAllocator *) gst_object_ref (allocator);
2212     GST_MINI_OBJECT_CAST (mem)->dispose = gst_d3d11_memory_release;
2213   } else {
2214     dec_outstanding (allocator);
2215   }
2216
2217   return result;
2218 }
2219
2220 /**
2221  * gst_d3d11_pool_allocator_get_pool_size:
2222  * @allocator: a #GstD3D11PoolAllocator
2223  * @max_size: (out) (optional): the max size of pool
2224  * @outstanding_size: (out) (optional): the number of outstanding memory
2225  *
2226  * Returns: %TRUE if the size of memory pool is known
2227  *
2228  * Since: 1.20
2229  */
2230 gboolean
2231 gst_d3d11_pool_allocator_get_pool_size (GstD3D11PoolAllocator * allocator,
2232     guint * max_size, guint * outstanding_size)
2233 {
2234   GstD3D11PoolAllocatorPrivate *priv;
2235
2236   g_return_val_if_fail (GST_IS_D3D11_POOL_ALLOCATOR (allocator), FALSE);
2237
2238   priv = allocator->priv;
2239
2240   if (max_size) {
2241     if (priv->desc.ArraySize > 1) {
2242       *max_size = priv->desc.ArraySize;
2243     } else {
2244       /* For non-texture-array memory, we don't have any limit yet */
2245       *max_size = 0;
2246     }
2247   }
2248
2249   if (outstanding_size)
2250     *outstanding_size = g_atomic_int_get (&priv->outstanding);
2251
2252   return TRUE;
2253 }