d3d11memory: Fix typo in vfunc name
[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_dispose (GObject * object);
1759 static void gst_d3d11_pool_allocator_finalize (GObject * object);
1760
1761 static gboolean
1762 gst_d3d11_pool_allocator_set_active (GstD3D11Allocator * allocator,
1763     gboolean active);
1764
1765 static gboolean gst_d3d11_pool_allocator_start (GstD3D11PoolAllocator * self);
1766 static gboolean gst_d3d11_pool_allocator_stop (GstD3D11PoolAllocator * self);
1767 static gboolean gst_d3d11_memory_release (GstMiniObject * mini_object);
1768
1769 #define gst_d3d11_pool_allocator_parent_class pool_alloc_parent_class
1770 G_DEFINE_TYPE_WITH_PRIVATE (GstD3D11PoolAllocator,
1771     gst_d3d11_pool_allocator, GST_TYPE_D3D11_ALLOCATOR);
1772
1773 static void
1774 gst_d3d11_pool_allocator_class_init (GstD3D11PoolAllocatorClass * klass)
1775 {
1776   GObjectClass *gobject_class = G_OBJECT_CLASS (klass);
1777   GstD3D11AllocatorClass *d3d11alloc_class = GST_D3D11_ALLOCATOR_CLASS (klass);
1778
1779   gobject_class->dispose = gst_d3d11_pool_allocator_dispose;
1780   gobject_class->finalize = gst_d3d11_pool_allocator_finalize;
1781
1782   d3d11alloc_class->set_active = gst_d3d11_pool_allocator_set_active;
1783 }
1784
1785 static void
1786 gst_d3d11_pool_allocator_init (GstD3D11PoolAllocator * allocator)
1787 {
1788   GstD3D11PoolAllocatorPrivate *priv;
1789
1790   priv = allocator->priv = (GstD3D11PoolAllocatorPrivate *)
1791       gst_d3d11_pool_allocator_get_instance_private (allocator);
1792
1793   InitializeCriticalSection (&priv->lock);
1794
1795   priv->poll = gst_poll_new_timer ();
1796   priv->queue = gst_atomic_queue_new (16);
1797   priv->flushing = 1;
1798   priv->active = FALSE;
1799   priv->started = FALSE;
1800
1801   /* 1 control write for flushing - the flush token */
1802   gst_poll_write_control (priv->poll);
1803   /* 1 control write for marking that we are not waiting for poll - the wait token */
1804   gst_poll_write_control (priv->poll);
1805 }
1806
1807 static void
1808 gst_d3d11_pool_allocator_dispose (GObject * object)
1809 {
1810   GstD3D11PoolAllocator *self = GST_D3D11_POOL_ALLOCATOR (object);
1811
1812   gst_clear_object (&self->device);
1813
1814   G_OBJECT_CLASS (pool_alloc_parent_class)->dispose (object);
1815 }
1816
1817 static void
1818 gst_d3d11_pool_allocator_finalize (GObject * object)
1819 {
1820   GstD3D11PoolAllocator *self = GST_D3D11_POOL_ALLOCATOR (object);
1821   GstD3D11PoolAllocatorPrivate *priv = self->priv;
1822
1823   GST_DEBUG_OBJECT (self, "Finalize");
1824
1825   gst_d3d11_pool_allocator_stop (self);
1826   gst_atomic_queue_unref (priv->queue);
1827   gst_poll_free (priv->poll);
1828   DeleteCriticalSection (&priv->lock);
1829
1830   GST_D3D11_CLEAR_COM (priv->texture);
1831
1832   G_OBJECT_CLASS (pool_alloc_parent_class)->finalize (object);
1833 }
1834
1835 static gboolean
1836 gst_d3d11_pool_allocator_start (GstD3D11PoolAllocator * self)
1837 {
1838   GstD3D11PoolAllocatorPrivate *priv = self->priv;
1839   ID3D11Device *device_handle;
1840   HRESULT hr;
1841   guint i;
1842
1843   if (priv->started)
1844     return TRUE;
1845
1846   /* Nothing to do */
1847   if (priv->desc.ArraySize == 1) {
1848     priv->started = TRUE;
1849     return TRUE;
1850   }
1851
1852   device_handle = gst_d3d11_device_get_device_handle (self->device);
1853
1854   if (!priv->texture) {
1855     hr = device_handle->CreateTexture2D (&priv->desc, NULL, &priv->texture);
1856     if (!gst_d3d11_result (hr, self->device)) {
1857       GST_ERROR_OBJECT (self, "Failed to allocate texture");
1858       return FALSE;
1859     }
1860   }
1861
1862   /* Pre-allocate memory objects */
1863   for (i = 0; i < priv->desc.ArraySize; i++) {
1864     GstMemory *mem;
1865
1866     priv->texture->AddRef ();
1867     mem = gst_d3d11_allocator_alloc_wrapped_internal (_d3d11_memory_allocator,
1868         self->device, &priv->desc, priv->texture);
1869
1870     if (i == 0) {
1871       if (!gst_d3d11_memory_update_size (mem)) {
1872         GST_ERROR_OBJECT (self, "Failed to calculate memory size");
1873         gst_memory_unref (mem);
1874         return FALSE;
1875       }
1876
1877       priv->mem_size = mem->size;
1878     } else {
1879       mem->size = mem->maxsize = priv->mem_size;
1880     }
1881
1882     GST_D3D11_MEMORY_CAST (mem)->priv->subresource_index = i;
1883
1884     g_atomic_int_add (&priv->cur_mems, 1);
1885     gst_atomic_queue_push (priv->queue, mem);
1886     gst_poll_write_control (priv->poll);
1887   }
1888
1889   priv->started = TRUE;
1890
1891   return TRUE;
1892 }
1893
1894 static void
1895 gst_d3d11_pool_allocator_do_set_flushing (GstD3D11PoolAllocator * self,
1896     gboolean flushing)
1897 {
1898   GstD3D11PoolAllocatorPrivate *priv = self->priv;
1899
1900   if (GST_D3D11_POOL_ALLOCATOR_IS_FLUSHING (self) == flushing)
1901     return;
1902
1903   if (flushing) {
1904     g_atomic_int_set (&priv->flushing, 1);
1905     /* Write the flush token to wake up any waiters */
1906     gst_poll_write_control (priv->poll);
1907   } else {
1908     while (!gst_poll_read_control (priv->poll)) {
1909       if (errno == EWOULDBLOCK) {
1910         /* This should not really happen unless flushing and unflushing
1911          * happens on different threads. Let's wait a bit to get back flush
1912          * token from the thread that was setting it to flushing */
1913         g_thread_yield ();
1914         continue;
1915       } else {
1916         /* Critical error but GstPoll already complained */
1917         break;
1918       }
1919     }
1920
1921     g_atomic_int_set (&priv->flushing, 0);
1922   }
1923 }
1924
1925 static gboolean
1926 gst_d3d11_pool_allocator_set_active (GstD3D11Allocator * allocator,
1927     gboolean active)
1928 {
1929   GstD3D11PoolAllocator *self = GST_D3D11_POOL_ALLOCATOR (allocator);
1930   GstD3D11PoolAllocatorPrivate *priv = self->priv;
1931
1932   GST_LOG_OBJECT (self, "active %d", active);
1933
1934   GstD3D11CSLockGuard lk (GST_D3D11_POOL_ALLOCATOR_GET_LOCK (self));
1935   /* just return if we are already in the right state */
1936   if (priv->active == active)
1937     return TRUE;
1938
1939   if (active) {
1940     if (!gst_d3d11_pool_allocator_start (self)) {
1941       GST_ERROR_OBJECT (self, "start failed");
1942       return FALSE;
1943     }
1944
1945     /* flush_stop may release memory objects, setting to active to avoid running
1946      * do_stop while activating the pool */
1947     priv->active = TRUE;
1948
1949     gst_d3d11_pool_allocator_do_set_flushing (self, FALSE);
1950   } else {
1951     gint outstanding;
1952
1953     /* set to flushing first */
1954     gst_d3d11_pool_allocator_do_set_flushing (self, TRUE);
1955
1956     /* when all memory objects are in the pool, free them. Else they will be
1957      * freed when they are released */
1958     outstanding = g_atomic_int_get (&priv->outstanding);
1959     GST_LOG_OBJECT (self, "outstanding memories %d, (in queue %d)",
1960         outstanding, gst_atomic_queue_length (priv->queue));
1961     if (outstanding == 0) {
1962       if (!gst_d3d11_pool_allocator_stop (self)) {
1963         GST_ERROR_OBJECT (self, "stop failed");
1964         return FALSE;
1965       }
1966     }
1967
1968     priv->active = FALSE;
1969   }
1970
1971   return TRUE;
1972 }
1973
1974 static void
1975 gst_d3d11_pool_allocator_free_memory (GstD3D11PoolAllocator * self,
1976     GstMemory * mem)
1977 {
1978   GstD3D11PoolAllocatorPrivate *priv = self->priv;
1979
1980   g_atomic_int_add (&priv->cur_mems, -1);
1981   GST_LOG_OBJECT (self, "freeing memory %p (%u left)", mem, priv->cur_mems);
1982
1983   GST_MINI_OBJECT_CAST (mem)->dispose = NULL;
1984   gst_memory_unref (mem);
1985 }
1986
1987 /* must be called with the lock */
1988 static gboolean
1989 gst_d3d11_pool_allocator_clear_queue (GstD3D11PoolAllocator * self)
1990 {
1991   GstD3D11PoolAllocatorPrivate *priv = self->priv;
1992   GstMemory *memory;
1993
1994   GST_LOG_OBJECT (self, "Clearing queue");
1995
1996   /* clear the pool */
1997   while ((memory = (GstMemory *) gst_atomic_queue_pop (priv->queue))) {
1998     while (!gst_poll_read_control (priv->poll)) {
1999       if (errno == EWOULDBLOCK) {
2000         /* We put the memory into the queue but did not finish writing control
2001          * yet, let's wait a bit and retry */
2002         g_thread_yield ();
2003         continue;
2004       } else {
2005         /* Critical error but GstPoll already complained */
2006         break;
2007       }
2008     }
2009     gst_d3d11_pool_allocator_free_memory (self, memory);
2010   }
2011
2012   GST_LOG_OBJECT (self, "Clear done");
2013
2014   return priv->cur_mems == 0;
2015 }
2016
2017 /* must be called with the lock */
2018 static gboolean
2019 gst_d3d11_pool_allocator_stop (GstD3D11PoolAllocator * self)
2020 {
2021   GstD3D11PoolAllocatorPrivate *priv = self->priv;
2022
2023   GST_DEBUG_OBJECT (self, "Stop");
2024
2025   if (priv->started) {
2026     if (!gst_d3d11_pool_allocator_clear_queue (self))
2027       return FALSE;
2028
2029     priv->started = FALSE;
2030   } else {
2031     GST_DEBUG_OBJECT (self, "Wasn't started");
2032   }
2033
2034   return TRUE;
2035 }
2036
2037 static inline void
2038 dec_outstanding (GstD3D11PoolAllocator * self)
2039 {
2040   if (g_atomic_int_dec_and_test (&self->priv->outstanding)) {
2041     /* all memory objects are returned to the pool, see if we need to free them */
2042     if (GST_D3D11_POOL_ALLOCATOR_IS_FLUSHING (self)) {
2043       /* take the lock so that set_active is not run concurrently */
2044       GstD3D11CSLockGuard lk (GST_D3D11_POOL_ALLOCATOR_GET_LOCK (self));
2045       /* now that we have the lock, check if we have been de-activated with
2046        * outstanding buffers */
2047       if (!self->priv->active)
2048         gst_d3d11_pool_allocator_stop (self);
2049     }
2050   }
2051 }
2052
2053 static void
2054 gst_d3d11_pool_allocator_release_memory (GstD3D11PoolAllocator * self,
2055     GstMemory * mem)
2056 {
2057   GST_LOG_OBJECT (self, "Released memory %p", mem);
2058
2059   GST_MINI_OBJECT_CAST (mem)->dispose = NULL;
2060   mem->allocator = (GstAllocator *) gst_object_ref (_d3d11_memory_allocator);
2061   gst_object_unref (self);
2062
2063   /* keep it around in our queue */
2064   gst_atomic_queue_push (self->priv->queue, mem);
2065   gst_poll_write_control (self->priv->poll);
2066   dec_outstanding (self);
2067 }
2068
2069 static gboolean
2070 gst_d3d11_memory_release (GstMiniObject * mini_object)
2071 {
2072   GstMemory *mem = GST_MEMORY_CAST (mini_object);
2073   GstD3D11PoolAllocator *alloc;
2074
2075   g_assert (mem->allocator != NULL);
2076
2077   if (!GST_IS_D3D11_POOL_ALLOCATOR (mem->allocator)) {
2078     GST_LOG_OBJECT (mem->allocator, "Not our memory, free");
2079     return TRUE;
2080   }
2081
2082   alloc = GST_D3D11_POOL_ALLOCATOR (mem->allocator);
2083   /* if flushing, free this memory */
2084   if (GST_D3D11_POOL_ALLOCATOR_IS_FLUSHING (alloc)) {
2085     GST_LOG_OBJECT (alloc, "allocator is flushing, free %p", mem);
2086     return TRUE;
2087   }
2088
2089   /* return the memory to the allocator */
2090   gst_memory_ref (mem);
2091   gst_d3d11_pool_allocator_release_memory (alloc, mem);
2092
2093   return FALSE;
2094 }
2095
2096 static GstFlowReturn
2097 gst_d3d11_pool_allocator_alloc (GstD3D11PoolAllocator * self, GstMemory ** mem)
2098 {
2099   GstD3D11PoolAllocatorPrivate *priv = self->priv;
2100   GstMemory *new_mem;
2101
2102   /* we allcates texture array during start */
2103   if (priv->desc.ArraySize > 1)
2104     return GST_FLOW_EOS;
2105
2106   /* increment the allocation counter */
2107   g_atomic_int_add (&priv->cur_mems, 1);
2108   new_mem = gst_d3d11_allocator_alloc_internal (_d3d11_memory_allocator,
2109       self->device, &priv->desc, nullptr);
2110   if (!new_mem) {
2111     GST_ERROR_OBJECT (self, "Failed to allocate new memory");
2112     g_atomic_int_add (&priv->cur_mems, -1);
2113     return GST_FLOW_ERROR;
2114   }
2115
2116   if (!priv->mem_size) {
2117     if (!gst_d3d11_memory_update_size (new_mem)) {
2118       GST_ERROR_OBJECT (self, "Failed to calculate size");
2119       gst_memory_unref (new_mem);
2120       g_atomic_int_add (&priv->cur_mems, -1);
2121
2122       return GST_FLOW_ERROR;
2123     }
2124
2125     priv->mem_size = new_mem->size;
2126   }
2127
2128   new_mem->size = new_mem->maxsize = priv->mem_size;
2129
2130   *mem = new_mem;
2131
2132   return GST_FLOW_OK;
2133 }
2134
2135 static GstFlowReturn
2136 gst_d3d11_pool_allocator_acquire_memory_internal (GstD3D11PoolAllocator * self,
2137     GstMemory ** memory)
2138 {
2139   GstFlowReturn result;
2140   GstD3D11PoolAllocatorPrivate *priv = self->priv;
2141
2142   while (TRUE) {
2143     if (G_UNLIKELY (GST_D3D11_POOL_ALLOCATOR_IS_FLUSHING (self)))
2144       goto flushing;
2145
2146     /* try to get a memory from the queue */
2147     *memory = (GstMemory *) gst_atomic_queue_pop (priv->queue);
2148     if (G_LIKELY (*memory)) {
2149       while (!gst_poll_read_control (priv->poll)) {
2150         if (errno == EWOULDBLOCK) {
2151           /* We put the memory into the queue but did not finish writing control
2152            * yet, let's wait a bit and retry */
2153           g_thread_yield ();
2154           continue;
2155         } else {
2156           /* Critical error but GstPoll already complained */
2157           break;
2158         }
2159       }
2160       result = GST_FLOW_OK;
2161       GST_LOG_OBJECT (self, "acquired memory %p", *memory);
2162       break;
2163     }
2164
2165     /* no memory, try to allocate some more */
2166     GST_LOG_OBJECT (self, "no memory, trying to allocate");
2167     result = gst_d3d11_pool_allocator_alloc (self, memory);
2168     if (G_LIKELY (result == GST_FLOW_OK))
2169       /* we have a memory, return it */
2170       break;
2171
2172     if (G_UNLIKELY (result != GST_FLOW_EOS))
2173       /* something went wrong, return error */
2174       break;
2175
2176     /* now we release the control socket, we wait for a memory release or
2177      * flushing */
2178     if (!gst_poll_read_control (priv->poll)) {
2179       if (errno == EWOULDBLOCK) {
2180         /* This means that we have two threads trying to allocate memory
2181          * already, and the other one already got the wait token. This
2182          * means that we only have to wait for the poll now and not write the
2183          * token afterwards: we will be woken up once the other thread is
2184          * woken up and that one will write the wait token it removed */
2185         GST_LOG_OBJECT (self, "waiting for free memory or flushing");
2186         gst_poll_wait (priv->poll, GST_CLOCK_TIME_NONE);
2187       } else {
2188         /* This is a critical error, GstPoll already gave a warning */
2189         result = GST_FLOW_ERROR;
2190         break;
2191       }
2192     } else {
2193       /* We're the first thread waiting, we got the wait token and have to
2194        * write it again later
2195        * OR
2196        * We're a second thread and just consumed the flush token and block all
2197        * other threads, in which case we must not wait and give it back
2198        * immediately */
2199       if (!GST_D3D11_POOL_ALLOCATOR_IS_FLUSHING (self)) {
2200         GST_LOG_OBJECT (self, "waiting for free memory or flushing");
2201         gst_poll_wait (priv->poll, GST_CLOCK_TIME_NONE);
2202       }
2203       gst_poll_write_control (priv->poll);
2204     }
2205   }
2206
2207   return result;
2208
2209   /* ERRORS */
2210 flushing:
2211   {
2212     GST_DEBUG_OBJECT (self, "we are flushing");
2213     return GST_FLOW_FLUSHING;
2214   }
2215 }
2216
2217 /**
2218  * gst_d3d11_pool_allocator_new:
2219  * @device: a #GstD3D11Device
2220  * @desc: a D3D11_TEXTURE2D_DESC for texture allocation
2221  *
2222  * Creates a new #GstD3D11PoolAllocator instance.
2223  *
2224  * Returns: (transfer full): a new #GstD3D11PoolAllocator instance
2225  *
2226  * Since: 1.22
2227  */
2228 GstD3D11PoolAllocator *
2229 gst_d3d11_pool_allocator_new (GstD3D11Device * device,
2230     const D3D11_TEXTURE2D_DESC * desc)
2231 {
2232   GstD3D11PoolAllocator *self;
2233
2234   g_return_val_if_fail (GST_IS_D3D11_DEVICE (device), NULL);
2235   g_return_val_if_fail (desc != NULL, NULL);
2236
2237   gst_d3d11_memory_init_once ();
2238
2239   self = (GstD3D11PoolAllocator *)
2240       g_object_new (GST_TYPE_D3D11_POOL_ALLOCATOR, NULL);
2241   gst_object_ref_sink (self);
2242
2243   self->device = (GstD3D11Device *) gst_object_ref (device);
2244   self->priv->desc = *desc;
2245
2246   return self;
2247 }
2248
2249 /**
2250  * gst_d3d11_pool_allocator_acquire_memory:
2251  * @allocator: a #GstD3D11PoolAllocator
2252  * @memory: (out): a #GstMemory
2253  *
2254  * Acquires a #GstMemory from @allocator. @memory should point to a memory
2255  * location that can hold a pointer to the new #GstMemory.
2256  *
2257  * Returns: a #GstFlowReturn such as %GST_FLOW_FLUSHING when the allocator is
2258  * inactive.
2259  */
2260 GstFlowReturn
2261 gst_d3d11_pool_allocator_acquire_memory (GstD3D11PoolAllocator * allocator,
2262     GstMemory ** memory)
2263 {
2264   GstD3D11PoolAllocatorPrivate *priv;
2265   GstFlowReturn result;
2266
2267   g_return_val_if_fail (GST_IS_D3D11_POOL_ALLOCATOR (allocator),
2268       GST_FLOW_ERROR);
2269   g_return_val_if_fail (memory != NULL, GST_FLOW_ERROR);
2270
2271   priv = allocator->priv;
2272
2273   /* assume we'll have one more outstanding buffer we need to do that so
2274    * that concurrent set_active doesn't clear the buffers */
2275   g_atomic_int_inc (&priv->outstanding);
2276   result = gst_d3d11_pool_allocator_acquire_memory_internal (allocator, memory);
2277
2278   if (result == GST_FLOW_OK) {
2279     GstMemory *mem = *memory;
2280     /* Replace default allocator with ours */
2281     gst_object_unref (mem->allocator);
2282     mem->allocator = (GstAllocator *) gst_object_ref (allocator);
2283     GST_MINI_OBJECT_CAST (mem)->dispose = gst_d3d11_memory_release;
2284   } else {
2285     dec_outstanding (allocator);
2286   }
2287
2288   return result;
2289 }
2290
2291 /**
2292  * gst_d3d11_pool_allocator_get_pool_size:
2293  * @allocator: a #GstD3D11PoolAllocator
2294  * @max_size: (out) (optional): the max size of pool
2295  * @outstanding_size: (out) (optional): the number of outstanding memory
2296  *
2297  * Returns: %TRUE if the size of memory pool is known
2298  *
2299  * Since: 1.22
2300  */
2301 gboolean
2302 gst_d3d11_pool_allocator_get_pool_size (GstD3D11PoolAllocator * allocator,
2303     guint * max_size, guint * outstanding_size)
2304 {
2305   GstD3D11PoolAllocatorPrivate *priv;
2306
2307   g_return_val_if_fail (GST_IS_D3D11_POOL_ALLOCATOR (allocator), FALSE);
2308
2309   priv = allocator->priv;
2310
2311   if (max_size) {
2312     if (priv->desc.ArraySize > 1) {
2313       *max_size = priv->desc.ArraySize;
2314     } else {
2315       /* For non-texture-array memory, we don't have any limit yet */
2316       *max_size = 0;
2317     }
2318   }
2319
2320   if (outstanding_size)
2321     *outstanding_size = g_atomic_int_get (&priv->outstanding);
2322
2323   return TRUE;
2324 }