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