d3d11: Update library doc
[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: 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): 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   ID3D11Device *device_handle = gst_d3d11_device_get_device_handle (device);
1305   ID3D11DeviceContext *device_context =
1306       gst_d3d11_device_get_device_context_handle (device);
1307   D3D11_TEXTURE2D_DESC dst_desc = { 0, };
1308   D3D11_TEXTURE2D_DESC src_desc = { 0, };
1309   GstMemory *copy = NULL;
1310   GstMapInfo info;
1311   HRESULT hr;
1312   UINT bind_flags = 0;
1313   UINT supported_flags = 0;
1314
1315   if (dmem->priv->native_type != GST_D3D11_MEMORY_NATIVE_TYPE_TEXTURE_2D)
1316     return priv->fallback_copy (mem, offset, size);
1317
1318   /* non-zero offset or different size is not supported */
1319   if (offset != 0 || (size != -1 && (gsize) size != mem->size)) {
1320     GST_DEBUG_OBJECT (alloc, "Different size/offset, try fallback copy");
1321     return priv->fallback_copy (mem, offset, size);
1322   }
1323
1324   GstD3D11DeviceLockGuard lk (device);
1325
1326   if (!gst_memory_map (mem, &info,
1327           (GstMapFlags) (GST_MAP_READ | GST_MAP_D3D11))) {
1328
1329     GST_WARNING_OBJECT (alloc, "Failed to map memory, try fallback copy");
1330
1331     return priv->fallback_copy (mem, offset, size);
1332   }
1333
1334   dmem->priv->texture->GetDesc (&src_desc);
1335   dst_desc.Width = src_desc.Width;
1336   dst_desc.Height = src_desc.Height;
1337   dst_desc.MipLevels = 1;
1338   dst_desc.Format = src_desc.Format;
1339   dst_desc.SampleDesc.Count = 1;
1340   dst_desc.ArraySize = 1;
1341   dst_desc.Usage = D3D11_USAGE_DEFAULT;
1342
1343   /* If supported, use bind flags for SRV/RTV */
1344   hr = device_handle->CheckFormatSupport (src_desc.Format, &supported_flags);
1345   if (gst_d3d11_result (hr, device)) {
1346     if ((supported_flags & D3D11_FORMAT_SUPPORT_SHADER_SAMPLE) ==
1347         D3D11_FORMAT_SUPPORT_SHADER_SAMPLE) {
1348       bind_flags |= D3D11_BIND_SHADER_RESOURCE;
1349     }
1350
1351     if ((supported_flags & D3D11_FORMAT_SUPPORT_RENDER_TARGET) ==
1352         D3D11_FORMAT_SUPPORT_RENDER_TARGET) {
1353       bind_flags |= D3D11_BIND_RENDER_TARGET;
1354     }
1355   }
1356
1357   copy = gst_d3d11_allocator_alloc_internal (alloc, device, &dst_desc, nullptr);
1358   if (!copy) {
1359     gst_memory_unmap (mem, &info);
1360
1361     GST_WARNING_OBJECT (alloc,
1362         "Failed to allocate new d3d11 map memory, try fallback copy");
1363
1364     return priv->fallback_copy (mem, offset, size);
1365   }
1366
1367   copy_dmem = GST_D3D11_MEMORY_CAST (copy);
1368   device_context->CopySubresourceRegion (copy_dmem->priv->texture, 0, 0, 0, 0,
1369       dmem->priv->texture, dmem->priv->subresource_index, NULL);
1370   copy->maxsize = copy->size = mem->maxsize;
1371   gst_memory_unmap (mem, &info);
1372
1373   /* newly allocated memory holds valid image data. We need download this
1374    * pixel data into staging memory for CPU access */
1375   GST_MINI_OBJECT_FLAG_SET (mem, GST_D3D11_MEMORY_TRANSFER_NEED_DOWNLOAD);
1376
1377   return copy;
1378 }
1379
1380 static void
1381 gst_d3d11_allocator_init (GstD3D11Allocator * allocator)
1382 {
1383   GstAllocator *alloc = GST_ALLOCATOR_CAST (allocator);
1384   GstD3D11AllocatorPrivate *priv;
1385
1386   priv = allocator->priv = (GstD3D11AllocatorPrivate *)
1387       gst_d3d11_allocator_get_instance_private (allocator);
1388
1389   alloc->mem_type = GST_D3D11_MEMORY_NAME;
1390   alloc->mem_map_full = gst_d3d11_memory_map_full;
1391   alloc->mem_unmap_full = gst_d3d11_memory_unmap_full;
1392   alloc->mem_share = gst_d3d11_memory_share;
1393
1394   /* Store pointer to default mem_copy method for fallback copy */
1395   priv->fallback_copy = alloc->mem_copy;
1396   alloc->mem_copy = gst_d3d11_memory_copy;
1397
1398   GST_OBJECT_FLAG_SET (alloc, GST_ALLOCATOR_FLAG_CUSTOM_ALLOC);
1399 }
1400
1401 static GstMemory *
1402 gst_d3d11_allocator_dummy_alloc (GstAllocator * allocator, gsize size,
1403     GstAllocationParams * params)
1404 {
1405   g_return_val_if_reached (NULL);
1406 }
1407
1408 static void
1409 gst_d3d11_allocator_free (GstAllocator * allocator, GstMemory * mem)
1410 {
1411   GstD3D11Memory *dmem = GST_D3D11_MEMORY_CAST (mem);
1412   GstD3D11MemoryPrivate *dmem_priv = dmem->priv;
1413   gint i;
1414
1415   GST_LOG_OBJECT (allocator, "Free memory %p", mem);
1416
1417   for (i = 0; i < GST_VIDEO_MAX_PLANES; i++) {
1418     GST_D3D11_CLEAR_COM (dmem_priv->render_target_view[i]);
1419     GST_D3D11_CLEAR_COM (dmem_priv->shader_resource_view[i]);
1420   }
1421
1422   GST_D3D11_CLEAR_COM (dmem_priv->decoder_output_view);
1423   GST_D3D11_CLEAR_COM (dmem_priv->processor_input_view);
1424   GST_D3D11_CLEAR_COM (dmem_priv->processor_output_view);
1425   GST_D3D11_CLEAR_COM (dmem_priv->texture);
1426   GST_D3D11_CLEAR_COM (dmem_priv->staging);
1427   GST_D3D11_CLEAR_COM (dmem_priv->buffer);
1428
1429   GST_D3D11_CLEAR_COM (dmem_priv->decoder_handle);
1430
1431   gst_clear_object (&dmem->device);
1432
1433   if (dmem_priv->notify)
1434     dmem_priv->notify (dmem_priv->user_data);
1435
1436   g_free (dmem->priv);
1437   g_free (dmem);
1438 }
1439
1440 static GstMemory *
1441 gst_d3d11_allocator_alloc_wrapped_internal (GstD3D11Allocator * self,
1442     GstD3D11Device * device, const D3D11_TEXTURE2D_DESC * desc,
1443     ID3D11Texture2D * texture)
1444 {
1445   GstD3D11Memory *mem;
1446
1447   mem = g_new0 (GstD3D11Memory, 1);
1448   mem->priv = g_new0 (GstD3D11MemoryPrivate, 1);
1449
1450   gst_memory_init (GST_MEMORY_CAST (mem),
1451       (GstMemoryFlags) 0, GST_ALLOCATOR_CAST (self), NULL, 0, 0, 0, 0);
1452   mem->priv->texture = texture;
1453   mem->priv->desc = *desc;
1454   mem->priv->native_type = GST_D3D11_MEMORY_NATIVE_TYPE_TEXTURE_2D;
1455   mem->device = (GstD3D11Device *) gst_object_ref (device);
1456
1457   return GST_MEMORY_CAST (mem);
1458 }
1459
1460 typedef void (*GstD3D11ClearRTVFunc) (ID3D11DeviceContext * context_handle,
1461     ID3D11RenderTargetView * rtv);
1462
1463 static void
1464 clear_rtv_chroma (ID3D11DeviceContext * context_handle,
1465     ID3D11RenderTargetView * rtv)
1466 {
1467   const FLOAT clear_color[4] = { 0.5f, 0.5f, 0.5f, 1.0f };
1468
1469   context_handle->ClearRenderTargetView (rtv, clear_color);
1470 }
1471
1472 static void
1473 clear_rtv_vuya (ID3D11DeviceContext * context_handle,
1474     ID3D11RenderTargetView * rtv)
1475 {
1476   const FLOAT clear_color[4] = { 0.5f, 0.5f, 0.0f, 1.0f };
1477
1478   context_handle->ClearRenderTargetView (rtv, clear_color);
1479 }
1480
1481 static GstMemory *
1482 gst_d3d11_allocator_alloc_internal (GstD3D11Allocator * self,
1483     GstD3D11Device * device, const D3D11_TEXTURE2D_DESC * desc,
1484     ID3D11Texture2D * texture)
1485 {
1486   ID3D11Device *device_handle;
1487   ID3D11DeviceContext *context_handle;
1488   HRESULT hr;
1489   GstMemory *mem;
1490   GstD3D11Memory *dmem;
1491   ID3D11RenderTargetView *rtv = nullptr;
1492   GstD3D11ClearRTVFunc clear_func = nullptr;
1493
1494   device_handle = gst_d3d11_device_get_device_handle (device);
1495
1496   if (!texture) {
1497     hr = device_handle->CreateTexture2D (desc, nullptr, &texture);
1498     if (!gst_d3d11_result (hr, device)) {
1499       GST_ERROR_OBJECT (self, "Couldn't create texture");
1500       return nullptr;
1501     }
1502   }
1503
1504   mem =
1505       gst_d3d11_allocator_alloc_wrapped_internal (self, device, desc, texture);
1506   if (!mem)
1507     return nullptr;
1508
1509   /* Clear with YUV black if needed and possible
1510    * TODO: do this using UAV if RTV is not allowed (e.g., packed YUV formats) */
1511   if ((desc->BindFlags & D3D11_BIND_RENDER_TARGET) == 0)
1512     return mem;
1513
1514   dmem = GST_D3D11_MEMORY_CAST (mem);
1515   switch (desc->Format) {
1516     case DXGI_FORMAT_NV12:
1517     case DXGI_FORMAT_P010:
1518     case DXGI_FORMAT_P016:
1519       /* Y component will be zero already */
1520       rtv = gst_d3d11_memory_get_render_target_view (dmem, 1);
1521       clear_func = (GstD3D11ClearRTVFunc) clear_rtv_chroma;
1522       break;
1523     case DXGI_FORMAT_AYUV:
1524       rtv = gst_d3d11_memory_get_render_target_view (dmem, 0);
1525       clear_func = (GstD3D11ClearRTVFunc) clear_rtv_vuya;
1526       break;
1527     default:
1528       return mem;
1529   }
1530
1531   if (!rtv)
1532     return mem;
1533
1534   context_handle = gst_d3d11_device_get_device_context_handle (device);
1535   GstD3D11DeviceLockGuard lk (device);
1536   clear_func (context_handle, rtv);
1537
1538   return mem;
1539 }
1540
1541 /**
1542  * gst_d3d11_allocator_alloc:
1543  * @allocator: (transfer none) (allow-none): a #GstD3D11Allocator
1544  * @device: (transfer none): a #GstD3D11Device
1545  * @desc: a D3D11_TEXTURE2D_DESC struct
1546  *
1547  * Returns: a newly allocated #GstD3D11Memory with given parameters.
1548  *
1549  * Since: 1.22
1550  */
1551 GstMemory *
1552 gst_d3d11_allocator_alloc (GstD3D11Allocator * allocator,
1553     GstD3D11Device * device, const D3D11_TEXTURE2D_DESC * desc)
1554 {
1555   GstMemory *mem;
1556
1557   if (!allocator) {
1558     gst_d3d11_memory_init_once ();
1559     allocator = _d3d11_memory_allocator;
1560   }
1561
1562   g_return_val_if_fail (GST_IS_D3D11_ALLOCATOR (allocator), NULL);
1563   g_return_val_if_fail (GST_IS_D3D11_DEVICE (device), NULL);
1564   g_return_val_if_fail (desc != NULL, NULL);
1565
1566   mem = gst_d3d11_allocator_alloc_internal (allocator, device, desc, nullptr);
1567   if (!mem)
1568     return NULL;
1569
1570   if (!gst_d3d11_memory_update_size (mem)) {
1571     GST_ERROR_OBJECT (allocator, "Failed to calculate size");
1572     gst_memory_unref (mem);
1573     return NULL;
1574   }
1575
1576   return mem;
1577 }
1578
1579 /**
1580  * gst_d3d11_allocator_alloc_buffer:
1581  * @allocator: (transfer none) (allow-none): a #GstD3D11Allocator
1582  * @device: (transfer none): a #GstD3D11Device
1583  * @desc: a D3D11_BUFFER_DESC struct
1584  *
1585  * Returns: a newly allocated #GstD3D11Memory with given parameters.
1586  *
1587  * Since: 1.22
1588  */
1589 GstMemory *
1590 gst_d3d11_allocator_alloc_buffer (GstD3D11Allocator * allocator,
1591     GstD3D11Device * device, const D3D11_BUFFER_DESC * desc)
1592 {
1593   GstD3D11Memory *mem;
1594   ID3D11Buffer *buffer;
1595   ID3D11Device *device_handle;
1596   HRESULT hr;
1597
1598   if (!allocator) {
1599     gst_d3d11_memory_init_once ();
1600     allocator = _d3d11_memory_allocator;
1601   }
1602
1603   g_return_val_if_fail (GST_IS_D3D11_ALLOCATOR (allocator), nullptr);
1604   g_return_val_if_fail (GST_IS_D3D11_DEVICE (device), nullptr);
1605   g_return_val_if_fail (desc != nullptr, nullptr);
1606
1607   if (desc->Usage != D3D11_USAGE_STAGING) {
1608     GST_FIXME_OBJECT (allocator, "Non staging buffer is not supported");
1609     return nullptr;
1610   }
1611
1612   device_handle = gst_d3d11_device_get_device_handle (device);
1613
1614   hr = device_handle->CreateBuffer (desc, nullptr, &buffer);
1615   if (!gst_d3d11_result (hr, device)) {
1616     GST_ERROR_OBJECT (allocator, "Couldn't create buffer");
1617     return nullptr;
1618   }
1619
1620   mem = g_new0 (GstD3D11Memory, 1);
1621   mem->priv = g_new0 (GstD3D11MemoryPrivate, 1);
1622
1623   gst_memory_init (GST_MEMORY_CAST (mem),
1624       (GstMemoryFlags) 0, GST_ALLOCATOR_CAST (allocator), nullptr, 0, 0, 0, 0);
1625   mem->priv->buffer = buffer;
1626   mem->priv->buffer_desc = *desc;
1627   mem->priv->native_type = GST_D3D11_MEMORY_NATIVE_TYPE_BUFFER;
1628   mem->device = (GstD3D11Device *) gst_object_ref (device);
1629
1630   GST_MEMORY_CAST (mem)->maxsize = GST_MEMORY_CAST (mem)->size =
1631       desc->ByteWidth;
1632
1633   return GST_MEMORY_CAST (mem);
1634 }
1635
1636 /**
1637  * gst_d3d11_allocator_alloc_wrapped:
1638  * @allocator: (transfer none) (allow-none): a #GstD3D11Allocator
1639  * @device: (transfer none): a #GstD3D11Device
1640  * @texture: a ID3D11Texture2D
1641  * @size: CPU accessible memory size
1642  * @user_data: (allow-none): user data
1643  * @notify: (allow-none): called with @user_data when the memory is freed
1644  *
1645  * Allocates memory object with @texture. The refcount of @texture
1646  * will be increased by one.
1647  *
1648  * Caller should set valid CPU acessible memory value to @size
1649  * (which is typically calculated by using staging texture and Map/Unmap)
1650  * or zero is allowed. In that case, allocator will create a temporary staging
1651  * texture to get the size and the temporary staging texture will be released.
1652  *
1653  * Caller must not be confused that @size is CPU accessible size, not raw
1654  * texture size.
1655  *
1656  * Returns: a newly allocated #GstD3D11Memory with given @texture
1657  * if successful, or %NULL if @texture is not a valid handle or configuration
1658  * is not supported.
1659  *
1660  * Since: 1.22
1661  */
1662 GstMemory *
1663 gst_d3d11_allocator_alloc_wrapped (GstD3D11Allocator * allocator,
1664     GstD3D11Device * device, ID3D11Texture2D * texture, gsize size,
1665     gpointer user_data, GDestroyNotify notify)
1666 {
1667   GstMemory *mem;
1668   GstD3D11Memory *dmem;
1669   D3D11_TEXTURE2D_DESC desc = { 0, };
1670   ID3D11Texture2D *tex = nullptr;
1671   HRESULT hr;
1672
1673   if (!allocator) {
1674     gst_d3d11_memory_init_once ();
1675     allocator = _d3d11_memory_allocator;
1676   }
1677
1678   g_return_val_if_fail (GST_IS_D3D11_ALLOCATOR (allocator), nullptr);
1679   g_return_val_if_fail (GST_IS_D3D11_DEVICE (device), nullptr);
1680   g_return_val_if_fail (texture != nullptr, nullptr);
1681
1682   hr = texture->QueryInterface (IID_PPV_ARGS (&tex));
1683   if (FAILED (hr)) {
1684     GST_WARNING_OBJECT (allocator, "Not a valid texture handle");
1685     return nullptr;
1686   }
1687
1688   tex->GetDesc (&desc);
1689   mem = gst_d3d11_allocator_alloc_internal (allocator, device, &desc, tex);
1690
1691   if (!mem)
1692     return nullptr;
1693
1694   if (size == 0) {
1695     if (!gst_d3d11_memory_update_size (mem)) {
1696       GST_ERROR_OBJECT (allocator, "Failed to calculate size");
1697       gst_memory_unref (mem);
1698       return nullptr;
1699     }
1700   } else {
1701     mem->maxsize = mem->size = size;
1702   }
1703
1704   dmem = GST_D3D11_MEMORY_CAST (mem);
1705
1706   dmem->priv->user_data = user_data;
1707   dmem->priv->notify = notify;
1708
1709   return mem;
1710 }
1711
1712 /**
1713  * gst_d3d11_allocator_set_active:
1714  * @allocator: a #GstD3D11Allocator
1715  * @active: the new active state
1716  *
1717  * Controls the active state of @allocator. Default #GstD3D11Allocator is
1718  * stateless and therefore active state is ignored, but subclass implementation
1719  * (e.g., #GstD3D11PoolAllocator) will require explicit active state control
1720  * for its internal resource management.
1721  *
1722  * This method is conceptually identical to gst_buffer_pool_set_active method.
1723  *
1724  * Returns: %TRUE if active state of @allocator was successfully updated.
1725  *
1726  * Since: 1.22
1727  */
1728 gboolean
1729 gst_d3d11_allocator_set_active (GstD3D11Allocator * allocator, gboolean active)
1730 {
1731   GstD3D11AllocatorClass *klass;
1732
1733   g_return_val_if_fail (GST_IS_D3D11_ALLOCATOR (allocator), FALSE);
1734
1735   klass = GST_D3D11_ALLOCATOR_GET_CLASS (allocator);
1736   if (klass->set_actvie)
1737     return klass->set_actvie (allocator, active);
1738
1739   return TRUE;
1740 }
1741
1742 /* GstD3D11PoolAllocator */
1743 #define GST_D3D11_POOL_ALLOCATOR_GET_LOCK(alloc) \
1744   (&(GST_D3D11_POOL_ALLOCATOR_CAST(alloc)->priv->lock))
1745 #define GST_D3D11_POOL_ALLOCATOR_IS_FLUSHING(alloc)  (g_atomic_int_get (&alloc->priv->flushing))
1746
1747 struct _GstD3D11PoolAllocatorPrivate
1748 {
1749   /* parent texture when array typed memory is used */
1750   ID3D11Texture2D *texture;
1751   D3D11_TEXTURE2D_DESC desc;
1752
1753   /* All below member variables are analogous to that of GstBufferPool */
1754   GstAtomicQueue *queue;
1755   GstPoll *poll;
1756
1757   /* This lock will protect all below variables apart from atomic ones
1758    * (identical to GstBufferPool::priv::rec_lock) */
1759   CRITICAL_SECTION lock;
1760   gboolean started;
1761   gboolean active;
1762
1763   /* atomic */
1764   gint outstanding;
1765   guint max_mems;
1766   guint cur_mems;
1767   gboolean flushing;
1768
1769   /* Calculated memory size, based on Direct3D11 staging texture map.
1770    * Note that, we cannot know the actually staging texture memory size prior
1771    * to map the staging texture because driver will likely require padding */
1772   gsize mem_size;
1773 };
1774
1775 static void gst_d3d11_pool_allocator_dispose (GObject * object);
1776 static void gst_d3d11_pool_allocator_finalize (GObject * object);
1777
1778 static gboolean
1779 gst_d3d11_pool_allocator_set_active (GstD3D11Allocator * allocator,
1780     gboolean active);
1781
1782 static gboolean gst_d3d11_pool_allocator_start (GstD3D11PoolAllocator * self);
1783 static gboolean gst_d3d11_pool_allocator_stop (GstD3D11PoolAllocator * self);
1784 static gboolean gst_d3d11_memory_release (GstMiniObject * mini_object);
1785
1786 #define gst_d3d11_pool_allocator_parent_class pool_alloc_parent_class
1787 G_DEFINE_TYPE_WITH_PRIVATE (GstD3D11PoolAllocator,
1788     gst_d3d11_pool_allocator, GST_TYPE_D3D11_ALLOCATOR);
1789
1790 static void
1791 gst_d3d11_pool_allocator_class_init (GstD3D11PoolAllocatorClass * klass)
1792 {
1793   GObjectClass *gobject_class = G_OBJECT_CLASS (klass);
1794   GstD3D11AllocatorClass *d3d11alloc_class = GST_D3D11_ALLOCATOR_CLASS (klass);
1795
1796   gobject_class->dispose = gst_d3d11_pool_allocator_dispose;
1797   gobject_class->finalize = gst_d3d11_pool_allocator_finalize;
1798
1799   d3d11alloc_class->set_actvie = gst_d3d11_pool_allocator_set_active;
1800 }
1801
1802 static void
1803 gst_d3d11_pool_allocator_init (GstD3D11PoolAllocator * allocator)
1804 {
1805   GstD3D11PoolAllocatorPrivate *priv;
1806
1807   priv = allocator->priv = (GstD3D11PoolAllocatorPrivate *)
1808       gst_d3d11_pool_allocator_get_instance_private (allocator);
1809
1810   InitializeCriticalSection (&priv->lock);
1811
1812   priv->poll = gst_poll_new_timer ();
1813   priv->queue = gst_atomic_queue_new (16);
1814   priv->flushing = 1;
1815   priv->active = FALSE;
1816   priv->started = FALSE;
1817
1818   /* 1 control write for flushing - the flush token */
1819   gst_poll_write_control (priv->poll);
1820   /* 1 control write for marking that we are not waiting for poll - the wait token */
1821   gst_poll_write_control (priv->poll);
1822 }
1823
1824 static void
1825 gst_d3d11_pool_allocator_dispose (GObject * object)
1826 {
1827   GstD3D11PoolAllocator *self = GST_D3D11_POOL_ALLOCATOR (object);
1828
1829   gst_clear_object (&self->device);
1830
1831   G_OBJECT_CLASS (pool_alloc_parent_class)->dispose (object);
1832 }
1833
1834 static void
1835 gst_d3d11_pool_allocator_finalize (GObject * object)
1836 {
1837   GstD3D11PoolAllocator *self = GST_D3D11_POOL_ALLOCATOR (object);
1838   GstD3D11PoolAllocatorPrivate *priv = self->priv;
1839
1840   GST_DEBUG_OBJECT (self, "Finalize");
1841
1842   gst_d3d11_pool_allocator_stop (self);
1843   gst_atomic_queue_unref (priv->queue);
1844   gst_poll_free (priv->poll);
1845   DeleteCriticalSection (&priv->lock);
1846
1847   GST_D3D11_CLEAR_COM (priv->texture);
1848
1849   G_OBJECT_CLASS (pool_alloc_parent_class)->finalize (object);
1850 }
1851
1852 static gboolean
1853 gst_d3d11_pool_allocator_start (GstD3D11PoolAllocator * self)
1854 {
1855   GstD3D11PoolAllocatorPrivate *priv = self->priv;
1856   ID3D11Device *device_handle;
1857   HRESULT hr;
1858   guint i;
1859
1860   if (priv->started)
1861     return TRUE;
1862
1863   /* Nothing to do */
1864   if (priv->desc.ArraySize == 1) {
1865     priv->started = TRUE;
1866     return TRUE;
1867   }
1868
1869   device_handle = gst_d3d11_device_get_device_handle (self->device);
1870
1871   if (!priv->texture) {
1872     hr = device_handle->CreateTexture2D (&priv->desc, NULL, &priv->texture);
1873     if (!gst_d3d11_result (hr, self->device)) {
1874       GST_ERROR_OBJECT (self, "Failed to allocate texture");
1875       return FALSE;
1876     }
1877   }
1878
1879   /* Pre-allocate memory objects */
1880   for (i = 0; i < priv->desc.ArraySize; i++) {
1881     GstMemory *mem;
1882
1883     priv->texture->AddRef ();
1884     mem = gst_d3d11_allocator_alloc_wrapped_internal (_d3d11_memory_allocator,
1885         self->device, &priv->desc, priv->texture);
1886
1887     if (i == 0) {
1888       if (!gst_d3d11_memory_update_size (mem)) {
1889         GST_ERROR_OBJECT (self, "Failed to calculate memory size");
1890         gst_memory_unref (mem);
1891         return FALSE;
1892       }
1893
1894       priv->mem_size = mem->size;
1895     } else {
1896       mem->size = mem->maxsize = priv->mem_size;
1897     }
1898
1899     GST_D3D11_MEMORY_CAST (mem)->priv->subresource_index = i;
1900
1901     g_atomic_int_add (&priv->cur_mems, 1);
1902     gst_atomic_queue_push (priv->queue, mem);
1903     gst_poll_write_control (priv->poll);
1904   }
1905
1906   priv->started = TRUE;
1907
1908   return TRUE;
1909 }
1910
1911 static void
1912 gst_d3d11_pool_allocator_do_set_flushing (GstD3D11PoolAllocator * self,
1913     gboolean flushing)
1914 {
1915   GstD3D11PoolAllocatorPrivate *priv = self->priv;
1916
1917   if (GST_D3D11_POOL_ALLOCATOR_IS_FLUSHING (self) == flushing)
1918     return;
1919
1920   if (flushing) {
1921     g_atomic_int_set (&priv->flushing, 1);
1922     /* Write the flush token to wake up any waiters */
1923     gst_poll_write_control (priv->poll);
1924   } else {
1925     while (!gst_poll_read_control (priv->poll)) {
1926       if (errno == EWOULDBLOCK) {
1927         /* This should not really happen unless flushing and unflushing
1928          * happens on different threads. Let's wait a bit to get back flush
1929          * token from the thread that was setting it to flushing */
1930         g_thread_yield ();
1931         continue;
1932       } else {
1933         /* Critical error but GstPoll already complained */
1934         break;
1935       }
1936     }
1937
1938     g_atomic_int_set (&priv->flushing, 0);
1939   }
1940 }
1941
1942 static gboolean
1943 gst_d3d11_pool_allocator_set_active (GstD3D11Allocator * allocator,
1944     gboolean active)
1945 {
1946   GstD3D11PoolAllocator *self = GST_D3D11_POOL_ALLOCATOR (allocator);
1947   GstD3D11PoolAllocatorPrivate *priv = self->priv;
1948
1949   GST_LOG_OBJECT (self, "active %d", active);
1950
1951   GstD3D11CSLockGuard lk (GST_D3D11_POOL_ALLOCATOR_GET_LOCK (self));
1952   /* just return if we are already in the right state */
1953   if (priv->active == active)
1954     return TRUE;
1955
1956   if (active) {
1957     if (!gst_d3d11_pool_allocator_start (self)) {
1958       GST_ERROR_OBJECT (self, "start failed");
1959       return FALSE;
1960     }
1961
1962     /* flush_stop may release memory objects, setting to active to avoid running
1963      * do_stop while activating the pool */
1964     priv->active = TRUE;
1965
1966     gst_d3d11_pool_allocator_do_set_flushing (self, FALSE);
1967   } else {
1968     gint outstanding;
1969
1970     /* set to flushing first */
1971     gst_d3d11_pool_allocator_do_set_flushing (self, TRUE);
1972
1973     /* when all memory objects are in the pool, free them. Else they will be
1974      * freed when they are released */
1975     outstanding = g_atomic_int_get (&priv->outstanding);
1976     GST_LOG_OBJECT (self, "outstanding memories %d, (in queue %d)",
1977         outstanding, gst_atomic_queue_length (priv->queue));
1978     if (outstanding == 0) {
1979       if (!gst_d3d11_pool_allocator_stop (self)) {
1980         GST_ERROR_OBJECT (self, "stop failed");
1981         return FALSE;
1982       }
1983     }
1984
1985     priv->active = FALSE;
1986   }
1987
1988   return TRUE;
1989 }
1990
1991 static void
1992 gst_d3d11_pool_allocator_free_memory (GstD3D11PoolAllocator * self,
1993     GstMemory * mem)
1994 {
1995   GstD3D11PoolAllocatorPrivate *priv = self->priv;
1996
1997   g_atomic_int_add (&priv->cur_mems, -1);
1998   GST_LOG_OBJECT (self, "freeing memory %p (%u left)", mem, priv->cur_mems);
1999
2000   GST_MINI_OBJECT_CAST (mem)->dispose = NULL;
2001   gst_memory_unref (mem);
2002 }
2003
2004 /* must be called with the lock */
2005 static gboolean
2006 gst_d3d11_pool_allocator_clear_queue (GstD3D11PoolAllocator * self)
2007 {
2008   GstD3D11PoolAllocatorPrivate *priv = self->priv;
2009   GstMemory *memory;
2010
2011   GST_LOG_OBJECT (self, "Clearing queue");
2012
2013   /* clear the pool */
2014   while ((memory = (GstMemory *) gst_atomic_queue_pop (priv->queue))) {
2015     while (!gst_poll_read_control (priv->poll)) {
2016       if (errno == EWOULDBLOCK) {
2017         /* We put the memory into the queue but did not finish writing control
2018          * yet, let's wait a bit and retry */
2019         g_thread_yield ();
2020         continue;
2021       } else {
2022         /* Critical error but GstPoll already complained */
2023         break;
2024       }
2025     }
2026     gst_d3d11_pool_allocator_free_memory (self, memory);
2027   }
2028
2029   GST_LOG_OBJECT (self, "Clear done");
2030
2031   return priv->cur_mems == 0;
2032 }
2033
2034 /* must be called with the lock */
2035 static gboolean
2036 gst_d3d11_pool_allocator_stop (GstD3D11PoolAllocator * self)
2037 {
2038   GstD3D11PoolAllocatorPrivate *priv = self->priv;
2039
2040   GST_DEBUG_OBJECT (self, "Stop");
2041
2042   if (priv->started) {
2043     if (!gst_d3d11_pool_allocator_clear_queue (self))
2044       return FALSE;
2045
2046     priv->started = FALSE;
2047   } else {
2048     GST_DEBUG_OBJECT (self, "Wasn't started");
2049   }
2050
2051   return TRUE;
2052 }
2053
2054 static inline void
2055 dec_outstanding (GstD3D11PoolAllocator * self)
2056 {
2057   if (g_atomic_int_dec_and_test (&self->priv->outstanding)) {
2058     /* all memory objects are returned to the pool, see if we need to free them */
2059     if (GST_D3D11_POOL_ALLOCATOR_IS_FLUSHING (self)) {
2060       /* take the lock so that set_active is not run concurrently */
2061       GstD3D11CSLockGuard lk (GST_D3D11_POOL_ALLOCATOR_GET_LOCK (self));
2062       /* now that we have the lock, check if we have been de-activated with
2063        * outstanding buffers */
2064       if (!self->priv->active)
2065         gst_d3d11_pool_allocator_stop (self);
2066     }
2067   }
2068 }
2069
2070 static void
2071 gst_d3d11_pool_allocator_release_memory (GstD3D11PoolAllocator * self,
2072     GstMemory * mem)
2073 {
2074   GST_LOG_OBJECT (self, "Released memory %p", mem);
2075
2076   GST_MINI_OBJECT_CAST (mem)->dispose = NULL;
2077   mem->allocator = (GstAllocator *) gst_object_ref (_d3d11_memory_allocator);
2078   gst_object_unref (self);
2079
2080   /* keep it around in our queue */
2081   gst_atomic_queue_push (self->priv->queue, mem);
2082   gst_poll_write_control (self->priv->poll);
2083   dec_outstanding (self);
2084 }
2085
2086 static gboolean
2087 gst_d3d11_memory_release (GstMiniObject * mini_object)
2088 {
2089   GstMemory *mem = GST_MEMORY_CAST (mini_object);
2090   GstD3D11PoolAllocator *alloc;
2091
2092   g_assert (mem->allocator != NULL);
2093
2094   if (!GST_IS_D3D11_POOL_ALLOCATOR (mem->allocator)) {
2095     GST_LOG_OBJECT (mem->allocator, "Not our memory, free");
2096     return TRUE;
2097   }
2098
2099   alloc = GST_D3D11_POOL_ALLOCATOR (mem->allocator);
2100   /* if flushing, free this memory */
2101   if (GST_D3D11_POOL_ALLOCATOR_IS_FLUSHING (alloc)) {
2102     GST_LOG_OBJECT (alloc, "allocator is flushing, free %p", mem);
2103     return TRUE;
2104   }
2105
2106   /* return the memory to the allocator */
2107   gst_memory_ref (mem);
2108   gst_d3d11_pool_allocator_release_memory (alloc, mem);
2109
2110   return FALSE;
2111 }
2112
2113 static GstFlowReturn
2114 gst_d3d11_pool_allocator_alloc (GstD3D11PoolAllocator * self, GstMemory ** mem)
2115 {
2116   GstD3D11PoolAllocatorPrivate *priv = self->priv;
2117   GstMemory *new_mem;
2118
2119   /* we allcates texture array during start */
2120   if (priv->desc.ArraySize > 1)
2121     return GST_FLOW_EOS;
2122
2123   /* increment the allocation counter */
2124   g_atomic_int_add (&priv->cur_mems, 1);
2125   new_mem = gst_d3d11_allocator_alloc_internal (_d3d11_memory_allocator,
2126       self->device, &priv->desc, nullptr);
2127   if (!new_mem) {
2128     GST_ERROR_OBJECT (self, "Failed to allocate new memory");
2129     g_atomic_int_add (&priv->cur_mems, -1);
2130     return GST_FLOW_ERROR;
2131   }
2132
2133   if (!priv->mem_size) {
2134     if (!gst_d3d11_memory_update_size (new_mem)) {
2135       GST_ERROR_OBJECT (self, "Failed to calculate size");
2136       gst_memory_unref (new_mem);
2137       g_atomic_int_add (&priv->cur_mems, -1);
2138
2139       return GST_FLOW_ERROR;
2140     }
2141
2142     priv->mem_size = new_mem->size;
2143   }
2144
2145   new_mem->size = new_mem->maxsize = priv->mem_size;
2146
2147   *mem = new_mem;
2148
2149   return GST_FLOW_OK;
2150 }
2151
2152 static GstFlowReturn
2153 gst_d3d11_pool_allocator_acquire_memory_internal (GstD3D11PoolAllocator * self,
2154     GstMemory ** memory)
2155 {
2156   GstFlowReturn result;
2157   GstD3D11PoolAllocatorPrivate *priv = self->priv;
2158
2159   while (TRUE) {
2160     if (G_UNLIKELY (GST_D3D11_POOL_ALLOCATOR_IS_FLUSHING (self)))
2161       goto flushing;
2162
2163     /* try to get a memory from the queue */
2164     *memory = (GstMemory *) gst_atomic_queue_pop (priv->queue);
2165     if (G_LIKELY (*memory)) {
2166       while (!gst_poll_read_control (priv->poll)) {
2167         if (errno == EWOULDBLOCK) {
2168           /* We put the memory into the queue but did not finish writing control
2169            * yet, let's wait a bit and retry */
2170           g_thread_yield ();
2171           continue;
2172         } else {
2173           /* Critical error but GstPoll already complained */
2174           break;
2175         }
2176       }
2177       result = GST_FLOW_OK;
2178       GST_LOG_OBJECT (self, "acquired memory %p", *memory);
2179       break;
2180     }
2181
2182     /* no memory, try to allocate some more */
2183     GST_LOG_OBJECT (self, "no memory, trying to allocate");
2184     result = gst_d3d11_pool_allocator_alloc (self, memory);
2185     if (G_LIKELY (result == GST_FLOW_OK))
2186       /* we have a memory, return it */
2187       break;
2188
2189     if (G_UNLIKELY (result != GST_FLOW_EOS))
2190       /* something went wrong, return error */
2191       break;
2192
2193     /* now we release the control socket, we wait for a memory release or
2194      * flushing */
2195     if (!gst_poll_read_control (priv->poll)) {
2196       if (errno == EWOULDBLOCK) {
2197         /* This means that we have two threads trying to allocate memory
2198          * already, and the other one already got the wait token. This
2199          * means that we only have to wait for the poll now and not write the
2200          * token afterwards: we will be woken up once the other thread is
2201          * woken up and that one will write the wait token it removed */
2202         GST_LOG_OBJECT (self, "waiting for free memory or flushing");
2203         gst_poll_wait (priv->poll, GST_CLOCK_TIME_NONE);
2204       } else {
2205         /* This is a critical error, GstPoll already gave a warning */
2206         result = GST_FLOW_ERROR;
2207         break;
2208       }
2209     } else {
2210       /* We're the first thread waiting, we got the wait token and have to
2211        * write it again later
2212        * OR
2213        * We're a second thread and just consumed the flush token and block all
2214        * other threads, in which case we must not wait and give it back
2215        * immediately */
2216       if (!GST_D3D11_POOL_ALLOCATOR_IS_FLUSHING (self)) {
2217         GST_LOG_OBJECT (self, "waiting for free memory or flushing");
2218         gst_poll_wait (priv->poll, GST_CLOCK_TIME_NONE);
2219       }
2220       gst_poll_write_control (priv->poll);
2221     }
2222   }
2223
2224   return result;
2225
2226   /* ERRORS */
2227 flushing:
2228   {
2229     GST_DEBUG_OBJECT (self, "we are flushing");
2230     return GST_FLOW_FLUSHING;
2231   }
2232 }
2233
2234 /**
2235  * gst_d3d11_pool_allocator_new:
2236  * @device: a #GstD3D11Device
2237  * @desc: a D3D11_TEXTURE2D_DESC for texture allocation
2238  *
2239  * Creates a new #GstD3D11PoolAllocator instance.
2240  *
2241  * Returns: (transfer full): a new #GstD3D11PoolAllocator instance
2242  *
2243  * Since: 1.22
2244  */
2245 GstD3D11PoolAllocator *
2246 gst_d3d11_pool_allocator_new (GstD3D11Device * device,
2247     const D3D11_TEXTURE2D_DESC * desc)
2248 {
2249   GstD3D11PoolAllocator *self;
2250
2251   g_return_val_if_fail (GST_IS_D3D11_DEVICE (device), NULL);
2252   g_return_val_if_fail (desc != NULL, NULL);
2253
2254   gst_d3d11_memory_init_once ();
2255
2256   self = (GstD3D11PoolAllocator *)
2257       g_object_new (GST_TYPE_D3D11_POOL_ALLOCATOR, NULL);
2258   gst_object_ref_sink (self);
2259
2260   self->device = (GstD3D11Device *) gst_object_ref (device);
2261   self->priv->desc = *desc;
2262
2263   return self;
2264 }
2265
2266 /**
2267  * gst_d3d11_pool_allocator_acquire_memory:
2268  * @allocator: a #GstD3D11PoolAllocator
2269  * @memory: (out): a #GstMemory
2270  *
2271  * Acquires a #GstMemory from @allocator. @memory should point to a memory
2272  * location that can hold a pointer to the new #GstMemory.
2273  *
2274  * Returns: a #GstFlowReturn such as %GST_FLOW_FLUSHING when the allocator is
2275  * inactive.
2276  */
2277 GstFlowReturn
2278 gst_d3d11_pool_allocator_acquire_memory (GstD3D11PoolAllocator * allocator,
2279     GstMemory ** memory)
2280 {
2281   GstD3D11PoolAllocatorPrivate *priv;
2282   GstFlowReturn result;
2283
2284   g_return_val_if_fail (GST_IS_D3D11_POOL_ALLOCATOR (allocator),
2285       GST_FLOW_ERROR);
2286   g_return_val_if_fail (memory != NULL, GST_FLOW_ERROR);
2287
2288   priv = allocator->priv;
2289
2290   /* assume we'll have one more outstanding buffer we need to do that so
2291    * that concurrent set_active doesn't clear the buffers */
2292   g_atomic_int_inc (&priv->outstanding);
2293   result = gst_d3d11_pool_allocator_acquire_memory_internal (allocator, memory);
2294
2295   if (result == GST_FLOW_OK) {
2296     GstMemory *mem = *memory;
2297     /* Replace default allocator with ours */
2298     gst_object_unref (mem->allocator);
2299     mem->allocator = (GstAllocator *) gst_object_ref (allocator);
2300     GST_MINI_OBJECT_CAST (mem)->dispose = gst_d3d11_memory_release;
2301   } else {
2302     dec_outstanding (allocator);
2303   }
2304
2305   return result;
2306 }
2307
2308 /**
2309  * gst_d3d11_pool_allocator_get_pool_size:
2310  * @allocator: a #GstD3D11PoolAllocator
2311  * @max_size: (out) (optional): the max size of pool
2312  * @outstanding_size: (out) (optional): the number of outstanding memory
2313  *
2314  * Returns: %TRUE if the size of memory pool is known
2315  *
2316  * Since: 1.22
2317  */
2318 gboolean
2319 gst_d3d11_pool_allocator_get_pool_size (GstD3D11PoolAllocator * allocator,
2320     guint * max_size, guint * outstanding_size)
2321 {
2322   GstD3D11PoolAllocatorPrivate *priv;
2323
2324   g_return_val_if_fail (GST_IS_D3D11_POOL_ALLOCATOR (allocator), FALSE);
2325
2326   priv = allocator->priv;
2327
2328   if (max_size) {
2329     if (priv->desc.ArraySize > 1) {
2330       *max_size = priv->desc.ArraySize;
2331     } else {
2332       /* For non-texture-array memory, we don't have any limit yet */
2333       *max_size = 0;
2334     }
2335   }
2336
2337   if (outstanding_size)
2338     *outstanding_size = g_atomic_int_get (&priv->outstanding);
2339
2340   return TRUE;
2341 }