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