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