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