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