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